Image4 / app.py
nagasurendra's picture
Update app.py
f213592 verified
raw
history blame
3.41 kB
from flask import Flask, render_template, request, jsonify
import os
import base64
import requests
import logging
from requests.adapters import HTTPAdapter
from urllib3.util.retry import Retry
# Configure logging
logging.basicConfig(level=logging.DEBUG, format='%(asctime)s - %(levelname)s - %(message)s')
app = Flask(__name__)
# Configuration
UPLOAD_FOLDER = 'static/captures'
os.makedirs(UPLOAD_FOLDER, exist_ok=True)
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
# Zapier webhook settings
ZAPIER_WEBHOOK_URL = os.getenv('ZAPIER_WEBHOOK_URL') # Load webhook URL from environment variable
def send_to_zapier(image_path):
if not ZAPIER_WEBHOOK_URL:
logging.error("Zapier webhook URL not set.")
return {"error": "Zapier webhook URL not set. Please set the ZAPIER_WEBHOOK_URL environment variable."}
try:
with open(image_path, "rb") as f:
image_data = f.read()
encoded_image = base64.b64encode(image_data).decode('utf-8')
payload = {
'image': encoded_image,
'filename': os.path.basename(image_path),
'content_type': 'image/jpeg'
}
session = requests.Session()
retries = Retry(total=3, backoff_factor=1, status_forcelist=[502, 503, 504])
session.mount('https://', HTTPAdapter(max_retries=retries))
logging.debug(f"Sending image to Zapier webhook: {ZAPIER_WEBHOOK_URL}")
response = session.post(ZAPIER_WEBHOOK_URL, json=payload, timeout=10)
response.raise_for_status()
logging.debug("Image sent to Zapier successfully.")
return {"status": "success"}
except requests.exceptions.RequestException as e:
logging.error(f"Failed to send to Zapier: {str(e)}")
if e.response is not None:
logging.error(f"Response details: {e.response.text}")
return {"error": f"Failed to send to Zapier: {str(e)}"}
@app.route('/')
def index():
return render_template('index.html')
@app.route('/capture', methods=['POST'])
def capture():
try:
data = request.form['image']
header, encoded = data.split(",", 1)
binary_data = base64.b64decode(encoded)
filename = f"capture_{len(os.listdir(app.config['UPLOAD_FOLDER'])) + 1}.jpg"
filepath = os.path.join(app.config['UPLOAD_FOLDER'], filename)
with open(filepath, "wb") as f:
f.write(binary_data)
image_url = f"/{filepath}"
return jsonify({
'status': 'success',
'image_url': image_url
})
except Exception as e:
logging.error(f"Error in capture: {str(e)}")
return jsonify({'status': 'error', 'message': str(e)})
@app.route('/upload_zapier', methods=['POST'])
def upload_zapier():
try:
image_url = request.form['image_url']
if not image_url.startswith('/static/captures/'):
return jsonify({'status': 'error', 'message': 'Invalid image path.'})
result = send_to_zapier(image_url.lstrip('/'))
if 'error' in result:
return jsonify({'status': 'error', 'message': result['error']})
return jsonify({'status': 'success'})
except Exception as e:
logging.error(f"Error in upload_zapier: {str(e)}")
return jsonify({'status': 'error', 'message': str(e)})
if __name__ == '__main__':
app.run(debug=True, host='0.0.0.0', port=7860)