-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathweb.py
More file actions
58 lines (48 loc) · 1.77 KB
/
web.py
File metadata and controls
58 lines (48 loc) · 1.77 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
#web.py
from flask import Flask, render_template, request, jsonify
import requests
import os
from dotenv import load_dotenv
load_dotenv()
API_URL = os.getenv("HUGGING_FACE_API_URL")
headers = {'Authorization': f'Bearer {os.getenv("HUGGING_FACE_API_KEY")}'}
app = Flask(__name__)
def get_content_type(filename):
ext = filename.lower().split('.')[-1]
if ext == 'png':
return 'image/png'
elif ext in ['jpg', 'jpeg']:
return 'image/jpeg'
elif ext == 'gif':
return 'image/gif'
# Add more types if needed
return 'application/octet-stream'
def query(data, content_type):
headers_with_type = headers.copy()
headers_with_type['Content-Type'] = content_type
response = requests.post(API_URL, headers=headers_with_type, data=data)
print("Status code:", response.status_code)
print("Response content:", response.content)
try:
return response.json()
except Exception as e:
return {"error": f"API did not return JSON: {str(e)}", "raw_response": response.content.decode(errors='ignore')}
@app.route('/', methods=['GET', 'POST'])
def index():
return render_template('index.html')
@app.route('/upload', methods=['POST'])
def upload():
if 'file1' not in request.files:
return jsonify({'error': 'No file part'}), 400
file = request.files['file1']
if file.filename == '':
return jsonify({'error': 'No selected file'}), 400
try:
file_bytes = file.read()
content_type = get_content_type(file.filename)
modeldata = query(file_bytes, content_type)
return jsonify(modeldata)
except Exception as e:
return jsonify({'error': str(e)}), 500
if __name__ == '__main__':
app.run(host='0.0.0.0', port=81)