Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -2,8 +2,6 @@ from flask import Flask, render_template, request, jsonify
|
|
| 2 |
import os
|
| 3 |
import base64
|
| 4 |
import requests
|
| 5 |
-
from PIL import Image
|
| 6 |
-
from io import BytesIO
|
| 7 |
import logging
|
| 8 |
from requests.adapters import HTTPAdapter
|
| 9 |
from urllib3.util.retry import Retry
|
|
@@ -18,49 +16,24 @@ UPLOAD_FOLDER = 'static/captures'
|
|
| 18 |
os.makedirs(UPLOAD_FOLDER, exist_ok=True)
|
| 19 |
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
|
| 20 |
|
| 21 |
-
# Hugging Face API settings
|
| 22 |
-
HF_API_TOKEN = os.getenv('HF_API_TOKEN') # Load token from environment variable
|
| 23 |
-
HF_API_URL = "https://api-inference.huggingface.co/models/facebook/detr-resnet-50" # Example model for object detection
|
| 24 |
-
|
| 25 |
# Zapier webhook settings
|
| 26 |
ZAPIER_WEBHOOK_URL = os.getenv('ZAPIER_WEBHOOK_URL') # Load webhook URL from environment variable
|
| 27 |
|
| 28 |
-
def query_hugging_face(image_data):
|
| 29 |
-
if not HF_API_TOKEN:
|
| 30 |
-
logging.error("Hugging Face API token not set.")
|
| 31 |
-
return {"error": "Hugging Face API token not set. Please set the HF_API_TOKEN environment variable."}
|
| 32 |
-
try:
|
| 33 |
-
session = requests.Session()
|
| 34 |
-
retries = Retry(total=3, backoff_factor=1, status_forcelist=[502, 503, 504])
|
| 35 |
-
session.mount('https://', HTTPAdapter(max_retries=retries))
|
| 36 |
-
headers = {"Authorization": f"Bearer {HF_API_TOKEN}"}
|
| 37 |
-
logging.debug(f"Sending request to {HF_API_URL}")
|
| 38 |
-
response = session.post(HF_API_URL, headers=headers, data=image_data, timeout=10)
|
| 39 |
-
response.raise_for_status()
|
| 40 |
-
logging.debug("Hugging Face API request successful.")
|
| 41 |
-
return response.json()
|
| 42 |
-
except requests.exceptions.RequestException as e:
|
| 43 |
-
logging.error(f"Failed to connect to Hugging Face API: {str(e)}")
|
| 44 |
-
return {"error": f"Failed to connect to Hugging Face API: {str(e)}"}
|
| 45 |
-
|
| 46 |
def send_to_zapier(image_path):
|
| 47 |
if not ZAPIER_WEBHOOK_URL:
|
| 48 |
logging.error("Zapier webhook URL not set.")
|
| 49 |
return {"error": "Zapier webhook URL not set. Please set the ZAPIER_WEBHOOK_URL environment variable."}
|
| 50 |
try:
|
| 51 |
-
# Read the image file
|
| 52 |
with open(image_path, "rb") as f:
|
| 53 |
image_data = f.read()
|
| 54 |
encoded_image = base64.b64encode(image_data).decode('utf-8')
|
| 55 |
|
| 56 |
-
# Prepare data for Zapier
|
| 57 |
payload = {
|
| 58 |
'image': encoded_image,
|
| 59 |
'filename': os.path.basename(image_path),
|
| 60 |
'content_type': 'image/jpeg'
|
| 61 |
}
|
| 62 |
|
| 63 |
-
# Send to Zapier webhook
|
| 64 |
session = requests.Session()
|
| 65 |
retries = Retry(total=3, backoff_factor=1, status_forcelist=[502, 503, 504])
|
| 66 |
session.mount('https://', HTTPAdapter(max_retries=retries))
|
|
@@ -71,6 +44,8 @@ def send_to_zapier(image_path):
|
|
| 71 |
return {"status": "success"}
|
| 72 |
except requests.exceptions.RequestException as e:
|
| 73 |
logging.error(f"Failed to send to Zapier: {str(e)}")
|
|
|
|
|
|
|
| 74 |
return {"error": f"Failed to send to Zapier: {str(e)}"}
|
| 75 |
|
| 76 |
@app.route('/')
|
|
@@ -80,27 +55,19 @@ def index():
|
|
| 80 |
@app.route('/capture', methods=['POST'])
|
| 81 |
def capture():
|
| 82 |
try:
|
| 83 |
-
# Get the base64 image data from the request
|
| 84 |
data = request.form['image']
|
| 85 |
header, encoded = data.split(",", 1)
|
| 86 |
binary_data = base64.b64decode(encoded)
|
| 87 |
|
| 88 |
-
# Save the image
|
| 89 |
filename = f"capture_{len(os.listdir(app.config['UPLOAD_FOLDER'])) + 1}.jpg"
|
| 90 |
filepath = os.path.join(app.config['UPLOAD_FOLDER'], filename)
|
| 91 |
with open(filepath, "wb") as f:
|
| 92 |
f.write(binary_data)
|
| 93 |
|
| 94 |
-
# Process with Hugging Face API
|
| 95 |
-
with open(filepath, "rb") as f:
|
| 96 |
-
hf_result = query_hugging_face(f.read())
|
| 97 |
-
|
| 98 |
-
# Return the image URL and Hugging Face result
|
| 99 |
image_url = f"/{filepath}"
|
| 100 |
return jsonify({
|
| 101 |
'status': 'success',
|
| 102 |
-
'image_url': image_url
|
| 103 |
-
'hf_result': hf_result
|
| 104 |
})
|
| 105 |
except Exception as e:
|
| 106 |
logging.error(f"Error in capture: {str(e)}")
|
|
@@ -121,15 +88,5 @@ def upload_zapier():
|
|
| 121 |
logging.error(f"Error in upload_zapier: {str(e)}")
|
| 122 |
return jsonify({'status': 'error', 'message': str(e)})
|
| 123 |
|
| 124 |
-
@app.route('/test_connectivity')
|
| 125 |
-
def test_connectivity():
|
| 126 |
-
try:
|
| 127 |
-
response = requests.get('https://www.google.com', timeout=5)
|
| 128 |
-
logging.debug(f"Connectivity test to Google: {response.status_code}")
|
| 129 |
-
return jsonify({'status': 'success', 'code': response.status_code})
|
| 130 |
-
except requests.exceptions.RequestException as e:
|
| 131 |
-
logging.error(f"Connectivity test failed: {str(e)}")
|
| 132 |
-
return jsonify({'status': 'error', 'message': str(e)})
|
| 133 |
-
|
| 134 |
if __name__ == '__main__':
|
| 135 |
app.run(debug=True, host='0.0.0.0', port=7860)
|
|
|
|
| 2 |
import os
|
| 3 |
import base64
|
| 4 |
import requests
|
|
|
|
|
|
|
| 5 |
import logging
|
| 6 |
from requests.adapters import HTTPAdapter
|
| 7 |
from urllib3.util.retry import Retry
|
|
|
|
| 16 |
os.makedirs(UPLOAD_FOLDER, exist_ok=True)
|
| 17 |
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
|
| 18 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 19 |
# Zapier webhook settings
|
| 20 |
ZAPIER_WEBHOOK_URL = os.getenv('ZAPIER_WEBHOOK_URL') # Load webhook URL from environment variable
|
| 21 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 22 |
def send_to_zapier(image_path):
|
| 23 |
if not ZAPIER_WEBHOOK_URL:
|
| 24 |
logging.error("Zapier webhook URL not set.")
|
| 25 |
return {"error": "Zapier webhook URL not set. Please set the ZAPIER_WEBHOOK_URL environment variable."}
|
| 26 |
try:
|
|
|
|
| 27 |
with open(image_path, "rb") as f:
|
| 28 |
image_data = f.read()
|
| 29 |
encoded_image = base64.b64encode(image_data).decode('utf-8')
|
| 30 |
|
|
|
|
| 31 |
payload = {
|
| 32 |
'image': encoded_image,
|
| 33 |
'filename': os.path.basename(image_path),
|
| 34 |
'content_type': 'image/jpeg'
|
| 35 |
}
|
| 36 |
|
|
|
|
| 37 |
session = requests.Session()
|
| 38 |
retries = Retry(total=3, backoff_factor=1, status_forcelist=[502, 503, 504])
|
| 39 |
session.mount('https://', HTTPAdapter(max_retries=retries))
|
|
|
|
| 44 |
return {"status": "success"}
|
| 45 |
except requests.exceptions.RequestException as e:
|
| 46 |
logging.error(f"Failed to send to Zapier: {str(e)}")
|
| 47 |
+
if e.response is not None:
|
| 48 |
+
logging.error(f"Response details: {e.response.text}")
|
| 49 |
return {"error": f"Failed to send to Zapier: {str(e)}"}
|
| 50 |
|
| 51 |
@app.route('/')
|
|
|
|
| 55 |
@app.route('/capture', methods=['POST'])
|
| 56 |
def capture():
|
| 57 |
try:
|
|
|
|
| 58 |
data = request.form['image']
|
| 59 |
header, encoded = data.split(",", 1)
|
| 60 |
binary_data = base64.b64decode(encoded)
|
| 61 |
|
|
|
|
| 62 |
filename = f"capture_{len(os.listdir(app.config['UPLOAD_FOLDER'])) + 1}.jpg"
|
| 63 |
filepath = os.path.join(app.config['UPLOAD_FOLDER'], filename)
|
| 64 |
with open(filepath, "wb") as f:
|
| 65 |
f.write(binary_data)
|
| 66 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 67 |
image_url = f"/{filepath}"
|
| 68 |
return jsonify({
|
| 69 |
'status': 'success',
|
| 70 |
+
'image_url': image_url
|
|
|
|
| 71 |
})
|
| 72 |
except Exception as e:
|
| 73 |
logging.error(f"Error in capture: {str(e)}")
|
|
|
|
| 88 |
logging.error(f"Error in upload_zapier: {str(e)}")
|
| 89 |
return jsonify({'status': 'error', 'message': str(e)})
|
| 90 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 91 |
if __name__ == '__main__':
|
| 92 |
app.run(debug=True, host='0.0.0.0', port=7860)
|