-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
212 lines (179 loc) · 7.39 KB
/
app.py
File metadata and controls
212 lines (179 loc) · 7.39 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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
import os
import uuid
import json
import base64
import requests
from flask import Flask, render_template, request, redirect, url_for, flash, session, jsonify
from werkzeug.utils import secure_filename
from inference_sdk import InferenceHTTPClient
from flask_cors import CORS
import PIL.Image
app = Flask(__name__)
CORS(app)
app.secret_key = 'development-secret-key'
app.config['UPLOAD_FOLDER'] = 'static/uploads'
app.config['RESULTS_FOLDER'] = 'static/results'
app.config['VISUALIZATIONS_FOLDER'] = 'static/visualizations'
app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024
app.config['ALLOWED_EXTENSIONS'] = {'png', 'jpg', 'jpeg'}
os.makedirs(app.config['UPLOAD_FOLDER'], exist_ok=True)
os.makedirs(app.config['RESULTS_FOLDER'], exist_ok=True)
os.makedirs(app.config['VISUALIZATIONS_FOLDER'], exist_ok=True)
roboflow_client = InferenceHTTPClient(
api_url="https://detect.roboflow.com",
api_key="API PLACEHOLDER" # add your own roboflow API key here
)
def allowed_file(filename):
return '.' in filename and \
filename.rsplit('.', 1)[1].lower() in app.config['ALLOWED_EXTENSIONS']
def download_image(url, save_path):
try:
response = requests.get(url, stream=True)
response.raise_for_status()
with open(save_path, 'wb') as f:
for chunk in response.iter_content(chunk_size=8192):
f.write(chunk)
return True
except Exception as e:
print(f"Error downloading image: {e}")
return False
def save_base64_image(base64_data, save_path):
try:
# Remove the data URL prefix if present
if base64_data.startswith('data:'):
base64_data = base64_data.split(',', 1)[1]
# Decode and save the image
with open(save_path, 'wb') as f:
f.write(base64.b64decode(base64_data))
return True
except Exception as e:
print(f"Error saving base64 image: {e}")
return False
@app.route('/')
def index():
return render_template('index.html')
@app.route('/text-inference')
def text_inference():
return render_template('text_inference.html')
@app.route('/upload', methods=['POST'])
def upload_file():
# Accept multiple files: file0, file1, ...
files = [f for key, f in request.files.items() if key.startswith('file') and allowed_file(f.filename)]
if not files:
flash('No valid files uploaded')
return redirect(request.url)
result_id = str(uuid.uuid4())
all_results = []
all_visualized_images = []
all_filenames = []
for idx, file in enumerate(files):
filename = f"{result_id}_{idx+1}_{secure_filename(file.filename)}"
filepath = os.path.join(app.config['UPLOAD_FOLDER'], filename)
file.save(filepath)
all_filenames.append(filename)
try:
result = roboflow_client.run_workflow(
workspace_name="grind-space",
workflow_id="detect-count-and-visualize",
images={
"image": filepath
},
use_cache=True
)
all_results.append(result)
# Visualized image
local_visualized_image = None
if isinstance(result, list) and len(result) > 0:
result_item = result[0]
if 'output_image' in result_item and result_item['output_image']:
visualization_filename = f"{result_id}_{idx+1}_visualization.jpg"
local_visualization_path = os.path.join(app.config['VISUALIZATIONS_FOLDER'], visualization_filename)
if save_base64_image(result_item['output_image'], local_visualization_path):
local_visualized_image = url_for('static', filename=f'visualizations/{visualization_filename}')
else:
if 'output_image' in result and result['output_image']:
visualization_filename = f"{result_id}_{idx+1}_visualization.jpg"
local_visualization_path = os.path.join(app.config['VISUALIZATIONS_FOLDER'], visualization_filename)
if save_base64_image(result['output_image'], local_visualization_path):
local_visualized_image = url_for('static', filename=f'visualizations/{visualization_filename}')
all_visualized_images.append(local_visualized_image)
except Exception as e:
flash(f'Error processing image: {str(e)}')
return redirect(request.url)
results_data = {
'original_images': all_filenames,
'detection_results': all_results,
'visualized_images': all_visualized_images
}
results_file = os.path.join(app.config['RESULTS_FOLDER'], f"{result_id}.json")
with open(results_file, 'w') as f:
json.dump(results_data, f)
session['result_id'] = result_id
return redirect(url_for('results'))
@app.route('/results')
def results():
if 'result_id' not in session:
flash('No results found. Please upload an image first.')
return redirect(url_for('index'))
result_id = session['result_id']
results_file = os.path.join(app.config['RESULTS_FOLDER'], f"{result_id}.json")
if not os.path.exists(results_file):
flash('Results not found. Please try again.')
return redirect(url_for('index'))
# Load results from file
with open(results_file, 'r') as f:
results = json.load(f)
return render_template('results.html',
results=results,
original_images=results['original_images'])
@app.route('/send-to-inference', methods=['POST'])
def send_to_inference():
try:
# Get the classes text from the request
data = request.json
if not data or 'text' not in data:
return jsonify({'error': 'No text provided'}), 400
classes_text = data['text']
# Send to inference endpoint
response = requests.post(
'http://127.0.0.1:9000/transliterate',
headers={'Content-Type': 'application/json'},
json={'text': classes_text}
)
# Ensure the response is valid JSON
try:
result = response.json()
return jsonify(result), response.status_code
except ValueError as e:
return jsonify({
'error': 'Invalid JSON response from API',
'response_text': response.text
}), 500
except Exception as e:
return jsonify({'error': str(e)}), 500
@app.route('/proxy/inference', methods=['POST'])
def proxy_inference():
try:
# Get the request data
data = request.json
if not data or 'text' not in data:
return jsonify({'error': 'No text provided'}), 400
text = data['text']
# Forward the request to the target API
response = requests.post(
'http://127.0.0.1:9000/transliterate',
headers={'Content-Type': 'application/json'},
json={'text': text}
)
try:
result = response.json()
return jsonify(result), response.status_code
except ValueError as e:
return jsonify({
'error': 'Invalid JSON response from API',
'response_text': response.text
}), 500
except Exception as e:
return jsonify({'error': str(e)}), 500
if __name__ == '__main__':
app.run(debug=True)