nagasurendra commited on
Commit
9d283dd
·
verified ·
1 Parent(s): c84554e

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +28 -32
app.py CHANGED
@@ -22,9 +22,8 @@ app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
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
- # Instagram API settings
26
- INSTAGRAM_ACCESS_TOKEN = os.getenv('INSTAGRAM_ACCESS_TOKEN') # Load token from environment variable
27
- INSTAGRAM_API_URL = "https://graph.instagram.com/v21.0/me/media"
28
 
29
  def query_hugging_face(image_data):
30
  if not HF_API_TOKEN:
@@ -32,7 +31,6 @@ def query_hugging_face(image_data):
32
  return {"error": "Hugging Face API token not set. Please set the HF_API_TOKEN environment variable."}
33
  try:
34
  session = requests.Session()
35
- # Configure retries: 3 attempts, backoff factor of 1s, retry on 502/503/504
36
  retries = Retry(total=3, backoff_factor=1, status_forcelist=[502, 503, 504])
37
  session.mount('https://', HTTPAdapter(max_retries=retries))
38
  headers = {"Authorization": f"Bearer {HF_API_TOKEN}"}
@@ -45,37 +43,35 @@ def query_hugging_face(image_data):
45
  logging.error(f"Failed to connect to Hugging Face API: {str(e)}")
46
  return {"error": f"Failed to connect to Hugging Face API: {str(e)}"}
47
 
48
- def upload_to_instagram(image_path):
49
- if not INSTAGRAM_ACCESS_TOKEN:
50
- logging.error("Instagram access token not set.")
51
- return {"error": "Instagram access token not set. Please set the INSTAGRAM_ACCESS_TOKEN environment variable."}
52
  try:
53
- # Step 1: Create media object
 
 
 
 
 
 
 
 
 
 
 
 
54
  session = requests.Session()
55
  retries = Retry(total=3, backoff_factor=1, status_forcelist=[502, 503, 504])
56
  session.mount('https://', HTTPAdapter(max_retries=retries))
57
-
58
- media_url = f"{INSTAGRAM_API_URL}?image_url={request.url_root}{image_path}&caption=Uploaded%20via%20Flask%20Camera%20App&access_token={INSTAGRAM_ACCESS_TOKEN}"
59
- logging.debug(f"Sending media creation request to Instagram: {media_url}")
60
- response = session.post(media_url, timeout=10)
61
  response.raise_for_status()
62
- media_data = response.json()
63
-
64
- if 'id' not in media_data:
65
- logging.error(f"Failed to create media: {media_data}")
66
- return {"error": f"Failed to create media: {media_data}"}
67
-
68
- # Step 2: Publish media
69
- media_id = media_data['id']
70
- publish_url = f"https://graph.instagram.com/v21.0/me/media_publish?creation_id={media_id}&access_token={INSTAGRAM_ACCESS_TOKEN}"
71
- logging.debug(f"Sending publish request to Instagram: {publish_url}")
72
- publish_response = session.post(publish_url, timeout=10)
73
- publish_response.raise_for_status()
74
- logging.debug("Instagram upload successful.")
75
  return {"status": "success"}
76
  except requests.exceptions.RequestException as e:
77
- logging.error(f"Failed to upload to Instagram: {str(e)}")
78
- return {"error": f"Failed to upload to Instagram: {str(e)}"}
79
 
80
  @app.route('/')
81
  def index():
@@ -110,19 +106,19 @@ def capture():
110
  logging.error(f"Error in capture: {str(e)}")
111
  return jsonify({'status': 'error', 'message': str(e)})
112
 
113
- @app.route('/upload_instagram', methods=['POST'])
114
- def upload_instagram():
115
  try:
116
  image_url = request.form['image_url']
117
  if not image_url.startswith('/static/captures/'):
118
  return jsonify({'status': 'error', 'message': 'Invalid image path.'})
119
 
120
- result = upload_to_instagram(image_url.lstrip('/'))
121
  if 'error' in result:
122
  return jsonify({'status': 'error', 'message': result['error']})
123
  return jsonify({'status': 'success'})
124
  except Exception as e:
125
- logging.error(f"Error in upload_instagram: {str(e)}")
126
  return jsonify({'status': 'error', 'message': str(e)})
127
 
128
  @app.route('/test_connectivity')
 
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:
 
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}"}
 
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))
67
+ logging.debug(f"Sending image to Zapier webhook: {ZAPIER_WEBHOOK_URL}")
68
+ response = session.post(ZAPIER_WEBHOOK_URL, json=payload, timeout=10)
 
 
69
  response.raise_for_status()
70
+ logging.debug("Image sent to Zapier successfully.")
 
 
 
 
 
 
 
 
 
 
 
 
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('/')
77
  def index():
 
106
  logging.error(f"Error in capture: {str(e)}")
107
  return jsonify({'status': 'error', 'message': str(e)})
108
 
109
+ @app.route('/upload_zapier', methods=['POST'])
110
+ def upload_zapier():
111
  try:
112
  image_url = request.form['image_url']
113
  if not image_url.startswith('/static/captures/'):
114
  return jsonify({'status': 'error', 'message': 'Invalid image path.'})
115
 
116
+ result = send_to_zapier(image_url.lstrip('/'))
117
  if 'error' in result:
118
  return jsonify({'status': 'error', 'message': result['error']})
119
  return jsonify({'status': 'success'})
120
  except Exception as e:
121
+ logging.error(f"Error in upload_zapier: {str(e)}")
122
  return jsonify({'status': 'error', 'message': str(e)})
123
 
124
  @app.route('/test_connectivity')