Spaces:
Runtime error
Runtime error
Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,122 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from flask import Flask, render_template, request, jsonify
|
2 |
+
import os
|
3 |
+
import requests
|
4 |
+
import json
|
5 |
+
import http.server
|
6 |
+
import socketserver
|
7 |
+
import threading
|
8 |
+
import subprocess
|
9 |
+
import time
|
10 |
+
from dotenv import load_dotenv
|
11 |
+
from PIL import Image
|
12 |
+
import io
|
13 |
+
from transformers import pipeline
|
14 |
+
import base64
|
15 |
+
|
16 |
+
app = Flask(__name__)
|
17 |
+
load_dotenv()
|
18 |
+
|
19 |
+
# Configuration
|
20 |
+
INSTAGRAM_ACCESS_TOKEN = os.getenv('INSTAGRAM_ACCESS_TOKEN')
|
21 |
+
INSTAGRAM_USER_ID = os.getenv('INSTAGRAM_USER_ID')
|
22 |
+
HUGGINGFACE_API_TOKEN = os.getenv('HUGGINGFACE_API_TOKEN')
|
23 |
+
UPLOAD_FOLDER = 'uploads'
|
24 |
+
PORT = 8000
|
25 |
+
|
26 |
+
# Ensure upload folder exists
|
27 |
+
os.makedirs(UPLOAD_FOLDER, exist_ok=True)
|
28 |
+
|
29 |
+
# Start local HTTP server to serve images
|
30 |
+
Handler = http.server.SimpleHTTPRequestHandler
|
31 |
+
httpd = socketserver.TCPServer(("", PORT), Handler)
|
32 |
+
server_thread = threading.Thread(target=httpd.serve_forever)
|
33 |
+
server_thread.daemon = True
|
34 |
+
server_thread.start()
|
35 |
+
|
36 |
+
# Start ngrok to create a public URL
|
37 |
+
ngrok_process = None
|
38 |
+
|
39 |
+
def start_ngrok():
|
40 |
+
global ngrok_process
|
41 |
+
ngrok_process = subprocess.Popen(["ngrok", "http", str(PORT)], stdout=subprocess.PIPE)
|
42 |
+
time.sleep(2) # Wait for ngrok to start
|
43 |
+
resp = requests.get("http://localhost:4040/api/tunnels")
|
44 |
+
public_url = resp.json()["tunnels"][0]["public_url"]
|
45 |
+
return public_url
|
46 |
+
|
47 |
+
# Hugging Face captioning pipeline
|
48 |
+
caption_pipeline = pipeline("image-to-text", model="Salesforce/blip-image-captioning-base")
|
49 |
+
|
50 |
+
@app.route('/')
|
51 |
+
def index():
|
52 |
+
return render_template('index.html')
|
53 |
+
|
54 |
+
@app.route('/upload', methods=['POST'])
|
55 |
+
def upload_image():
|
56 |
+
try:
|
57 |
+
# Get base64 image from request
|
58 |
+
image_data = request.json['image'].split(',')[1]
|
59 |
+
image_bytes = base64.b64decode(image_data)
|
60 |
+
|
61 |
+
# Save image to uploads folder
|
62 |
+
image_path = os.path.join(UPLOAD_FOLDER, 'captured_image.jpg')
|
63 |
+
with open(image_path, 'wb') as f:
|
64 |
+
f.write(image_bytes)
|
65 |
+
|
66 |
+
# Generate caption using Hugging Face
|
67 |
+
image = Image.open(io.BytesIO(image_bytes))
|
68 |
+
caption_result = caption_pipeline(image)
|
69 |
+
caption = caption_result[0]['generated_text']
|
70 |
+
|
71 |
+
# Get public URL from ngrok
|
72 |
+
public_url = start_ngrok()
|
73 |
+
image_url = f"{public_url}/uploads/captured_image.jpg"
|
74 |
+
|
75 |
+
# Create Instagram media container
|
76 |
+
create_url = f"https://graph.facebook.com/v20.0/{INSTAGRAM_USER_ID}/media"
|
77 |
+
payload = {
|
78 |
+
"image_url": image_url,
|
79 |
+
"caption": caption,
|
80 |
+
"access_token": INSTAGRAM_ACCESS_TOKEN
|
81 |
+
}
|
82 |
+
response = requests.post(create_url, params=payload)
|
83 |
+
result = response.json()
|
84 |
+
|
85 |
+
if 'id' in result:
|
86 |
+
creation_id = result['id']
|
87 |
+
# Publish the media
|
88 |
+
publish_url = f"https://graph.facebook.com/v20.0/{INSTAGRAM_USER_ID}/media_publish"
|
89 |
+
publish_payload = {
|
90 |
+
"creation_id": creation_id,
|
91 |
+
"access_token": INSTAGRAM_ACCESS_TOKEN
|
92 |
+
}
|
93 |
+
publish_response = requests.post(publish_url, params=publish_payload)
|
94 |
+
publish_result = publish_response.json()
|
95 |
+
|
96 |
+
if 'id' in publish_result:
|
97 |
+
return jsonify({"status": "success", "message": "Image posted to Instagram", "caption": caption})
|
98 |
+
else:
|
99 |
+
return jsonify({"status": "error", "message": publish_result.get('error', {}).get('message', 'Failed to publish')})
|
100 |
+
else:
|
101 |
+
return jsonify({"status": "error", "message": result.get('error', {}).get('message', 'Failed to create media container')})
|
102 |
+
except Exception as e:
|
103 |
+
return jsonify({"status": "error", "message": str(e)})
|
104 |
+
finally:
|
105 |
+
# Clean up ngrok
|
106 |
+
if ngrok_process:
|
107 |
+
ngrok_process.terminate()
|
108 |
+
|
109 |
+
@app.route('/shutdown', methods=['POST'])
|
110 |
+
def shutdown():
|
111 |
+
httpd.shutdown()
|
112 |
+
if ngrok_process:
|
113 |
+
ngrok_process.terminate()
|
114 |
+
return jsonify({"status": "success", "message": "Server shutdown"})
|
115 |
+
|
116 |
+
if __name__ == '__main__':
|
117 |
+
try:
|
118 |
+
app.run(debug=True)
|
119 |
+
finally:
|
120 |
+
httpd.shutdown()
|
121 |
+
if ngrok_process:
|
122 |
+
ngrok_process.terminate()
|