Spaces:
Sleeping
Sleeping
Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,57 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
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 |
+
|
8 |
+
app = Flask(__name__)
|
9 |
+
|
10 |
+
# Configuration
|
11 |
+
UPLOAD_FOLDER = 'static/captures'
|
12 |
+
os.makedirs(UPLOAD_FOLDER, exist_ok=True)
|
13 |
+
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
|
14 |
+
|
15 |
+
# Hugging Face API settings (replace with your API key)
|
16 |
+
HF_API_TOKEN = "your_hugging_face_api_token" # Get from https://huggingface.co/settings/tokens
|
17 |
+
HF_API_URL = "https://api-inference.huggingface.co/models/facebook/detr-resnet-50" # Example model for object detection
|
18 |
+
|
19 |
+
def query_hugging_face(image_data):
|
20 |
+
headers = {"Authorization": f"Bearer {HF_API_TOKEN}"}
|
21 |
+
response = requests.post(HF_API_URL, headers=headers, data=image_data)
|
22 |
+
return response.json()
|
23 |
+
|
24 |
+
@app.route('/')
|
25 |
+
def index():
|
26 |
+
return render_template('index.html')
|
27 |
+
|
28 |
+
@app.route('/capture', methods=['POST'])
|
29 |
+
def capture():
|
30 |
+
try:
|
31 |
+
# Get the base64 image data from the request
|
32 |
+
data = request.form['image']
|
33 |
+
header, encoded = data.split(",", 1)
|
34 |
+
binary_data = base64.b64decode(encoded)
|
35 |
+
|
36 |
+
# Save the image
|
37 |
+
filename = f"capture_{len(os.listdir(app.config['UPLOAD_FOLDER'])) + 1}.jpg"
|
38 |
+
filepath = os.path.join(app.config['UPLOAD_FOLDER'], filename)
|
39 |
+
with open(filepath, "wb") as f:
|
40 |
+
f.write(binary_data)
|
41 |
+
|
42 |
+
# Process with Hugging Face API
|
43 |
+
with open(filepath, "rb") as f:
|
44 |
+
hf_result = query_hugging_face(f.read())
|
45 |
+
|
46 |
+
# Return the image URL and Hugging Face result
|
47 |
+
image_url = f"/{filepath}"
|
48 |
+
return jsonify({
|
49 |
+
'status': 'success',
|
50 |
+
'image_url': image_url,
|
51 |
+
'hf_result': hf_result
|
52 |
+
})
|
53 |
+
except Exception as e:
|
54 |
+
return jsonify({'status': 'error', 'message': str(e)})
|
55 |
+
|
56 |
+
if __name__ == '__main__':
|
57 |
+
app.run(debug=True, host='0.0.0.0', port=5000)
|