nagasurendra commited on
Commit
acf390f
·
verified ·
1 Parent(s): c1d9edd

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +95 -0
app.py CHANGED
@@ -334,6 +334,101 @@ def submit_customization_ingredients():
334
  except Exception as e:
335
  logger.error(f"Failed to submit: {str(e)}")
336
  return jsonify({"error": f"Failed to submit: {str(e)}"}), 500
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
337
 
338
 
339
  if __name__ == "__main__":
 
334
  except Exception as e:
335
  logger.error(f"Failed to submit: {str(e)}")
336
  return jsonify({"error": f"Failed to submit: {str(e)}"}), 500
337
+ from flask import Flask, render_template, request, jsonify
338
+ import os
339
+ import base64
340
+ import requests
341
+ import logging
342
+ from requests.adapters import HTTPAdapter
343
+ from urllib3.util.retry import Retry
344
+
345
+ # Configure logging
346
+ logging.basicConfig(level=logging.DEBUG, format='%(asctime)s - %(levelname)s - %(message)s')
347
+
348
+ app = Flask(__name__)
349
+
350
+ # Configuration
351
+ UPLOAD_FOLDER = 'static/captures'
352
+ os.makedirs(UPLOAD_FOLDER, exist_ok=True)
353
+ app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
354
+
355
+ # Zapier webhook settings
356
+ ZAPIER_WEBHOOK_URL = os.getenv('ZAPIER_WEBHOOK_URL') # Load webhook URL from environment variable
357
+
358
+ @app.route('/')
359
+ def index():
360
+ return render_template('index.html') # Render the main page
361
+
362
+ @app.route('/camera')
363
+ def camera():
364
+ return render_template('camera.html') # Render the camera capture page
365
+
366
+ @app.route('/capture', methods=['POST'])
367
+ def capture():
368
+ try:
369
+ # Get the base64 encoded image from the request
370
+ data = request.form['image']
371
+ header, encoded = data.split(",", 1)
372
+ binary_data = base64.b64decode(encoded)
373
+
374
+ # Save the image to the server
375
+ filename = f"capture_{len(os.listdir(app.config['UPLOAD_FOLDER'])) + 1}.jpg"
376
+ filepath = os.path.join(app.config['UPLOAD_FOLDER'], filename)
377
+ with open(filepath, "wb") as f:
378
+ f.write(binary_data)
379
+
380
+ # Return the URL of the saved image
381
+ image_url = f"/{filepath}"
382
+ return jsonify({
383
+ 'status': 'success',
384
+ 'image_url': image_url
385
+ })
386
+ except Exception as e:
387
+ logging.error(f"Error in capture: {str(e)}")
388
+ return jsonify({'status': 'error', 'message': str(e)})
389
+
390
+ @app.route('/upload_zapier', methods=['POST'])
391
+ def upload_zapier():
392
+ try:
393
+ # Get the image URL from the request
394
+ image_url = request.form['image_url']
395
+ if not image_url.startswith('/static/captures/'):
396
+ return jsonify({'status': 'error', 'message': 'Invalid image path.'})
397
+
398
+ # Send the image URL to Zapier
399
+ result = send_to_zapier(image_url.lstrip('/'))
400
+ if 'error' in result:
401
+ return jsonify({'status': 'error', 'message': result['error']})
402
+ return jsonify({'status': 'success'})
403
+ except Exception as e:
404
+ logging.error(f"Error in upload_zapier: {str(e)}")
405
+ return jsonify({'status': 'error', 'message': str(e)})
406
+
407
+ def send_to_zapier(image_path):
408
+ if not ZAPIER_WEBHOOK_URL:
409
+ logging.error("Zapier webhook URL not set.")
410
+ return {"error": "Zapier webhook URL not set. Please set the ZAPIER_WEBHOOK_URL environment variable."}
411
+ try:
412
+ payload = {
413
+ 'image_url': request.url_root + image_path,
414
+ 'filename': os.path.basename(image_path),
415
+ 'content_type': 'image/jpeg'
416
+ }
417
+
418
+ session = requests.Session()
419
+ retries = Retry(total=3, backoff_factor=1, status_forcelist=[502, 503, 504])
420
+ session.mount('https://', HTTPAdapter(max_retries=retries))
421
+ logging.debug(f"Sending image URL to Zapier webhook: {ZAPIER_WEBHOOK_URL}")
422
+ response = session.post(ZAPIER_WEBHOOK_URL, json=payload, timeout=10)
423
+ response.raise_for_status()
424
+ logging.debug("Image URL sent to Zapier successfully.")
425
+ return {"status": "success"}
426
+ except requests.exceptions.RequestException as e:
427
+ logging.error(f"Failed to send to Zapier: {str(e)}")
428
+ if e.response is not None:
429
+ logging.error(f"Response details: {e.response.text}")
430
+ return {"error": f"Failed to send to Zapier: {str(e)}"}
431
+
432
 
433
 
434
  if __name__ == "__main__":