Spaces:
Paused
Paused
Update app.py
Browse files
app.py
CHANGED
@@ -4,6 +4,11 @@ from PIL import Image, ImageDraw
|
|
4 |
import torch
|
5 |
import os
|
6 |
import uuid
|
|
|
|
|
|
|
|
|
|
|
7 |
|
8 |
app = Flask(__name__)
|
9 |
|
@@ -13,8 +18,10 @@ os.makedirs(UPLOAD_FOLDER, exist_ok=True)
|
|
13 |
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
|
14 |
|
15 |
# Load DETR model and processor
|
|
|
16 |
processor = DetrImageProcessor.from_pretrained("facebook/detr-resnet-50")
|
17 |
model = DetrForObjectDetection.from_pretrained("facebook/detr-resnet-50")
|
|
|
18 |
|
19 |
@app.route('/')
|
20 |
def index():
|
@@ -23,40 +30,51 @@ def index():
|
|
23 |
@app.route('/upload', methods=['POST'])
|
24 |
def upload_file():
|
25 |
if 'file' not in request.files:
|
|
|
26 |
return redirect(request.url)
|
27 |
file = request.files['file']
|
28 |
if file.filename == '':
|
|
|
29 |
return redirect(request.url)
|
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 |
if __name__ == '__main__':
|
62 |
app.run(host='0.0.0.0', port=7860)
|
|
|
4 |
import torch
|
5 |
import os
|
6 |
import uuid
|
7 |
+
import logging
|
8 |
+
|
9 |
+
# Configure logging
|
10 |
+
logging.basicConfig(level=logging.INFO)
|
11 |
+
logger = logging.getLogger(__name__)
|
12 |
|
13 |
app = Flask(__name__)
|
14 |
|
|
|
18 |
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
|
19 |
|
20 |
# Load DETR model and processor
|
21 |
+
logger.info("Loading DETR model and processor...")
|
22 |
processor = DetrImageProcessor.from_pretrained("facebook/detr-resnet-50")
|
23 |
model = DetrForObjectDetection.from_pretrained("facebook/detr-resnet-50")
|
24 |
+
logger.info("Model and processor loaded successfully.")
|
25 |
|
26 |
@app.route('/')
|
27 |
def index():
|
|
|
30 |
@app.route('/upload', methods=['POST'])
|
31 |
def upload_file():
|
32 |
if 'file' not in request.files:
|
33 |
+
logger.warning("No file part in request.")
|
34 |
return redirect(request.url)
|
35 |
file = request.files['file']
|
36 |
if file.filename == '':
|
37 |
+
logger.warning("No file selected.")
|
38 |
return redirect(request.url)
|
39 |
|
40 |
+
try:
|
41 |
+
# Save uploaded file
|
42 |
+
filename = str(uuid.uuid4()) + os.path.splitext(file.filename)[1]
|
43 |
+
filepath = os.path.join(app.config['UPLOAD_FOLDER'], filename)
|
44 |
+
file.save(filepath)
|
45 |
+
logger.info(f"File saved: {filename}")
|
46 |
+
|
47 |
+
# Process image
|
48 |
+
image = Image.open(filepath).convert("RGB")
|
49 |
+
image = image.resize((800, 600)) # Resize for performance
|
50 |
+
inputs = processor(images=image, return_tensors="pt")
|
51 |
+
outputs = model(**inputs)
|
52 |
+
|
53 |
+
# Post-process outputs
|
54 |
+
target_sizes = torch.tensor([image.size[::-1]])
|
55 |
+
results = processor.post_process_object_detection(outputs, target_sizes=target_sizes, threshold=0.9)[0]
|
56 |
+
|
57 |
+
# Draw bounding boxes
|
58 |
+
draw = ImageDraw.Draw(image)
|
59 |
+
for score, label, box in zip(results["scores"], results["labels"], results["boxes"]):
|
60 |
+
box = [round(i, 2) for i in box.tolist()]
|
61 |
+
label_str = model.config.id2label[label.item()]
|
62 |
+
draw.rectangle(box, outline="red", width=3)
|
63 |
+
draw.text((box[0], box[1]), f"{label_str}: {score:.2f}", fill="red")
|
64 |
+
|
65 |
+
# Save output image
|
66 |
+
output_filename = f"output_{filename}"
|
67 |
+
output_filepath = os.path.join(app.config['UPLOAD_FOLDER'], output_filename)
|
68 |
+
image.save(output_filepath)
|
69 |
+
logger.info(f"Processed image saved: {output_filename}")
|
70 |
+
|
71 |
+
return render_template('results.html',
|
72 |
+
original_image=url_for('static', filename=f'uploads/{filename}'),
|
73 |
+
processed_image=url_for('static', filename=f'uploads/{output_filename}'))
|
74 |
|
75 |
+
except Exception as e:
|
76 |
+
logger.error(f"Error processing file: {str(e)}")
|
77 |
+
return render_template('index.html', error=f"Error processing file: {str(e)}")
|
78 |
|
79 |
if __name__ == '__main__':
|
80 |
app.run(host='0.0.0.0', port=7860)
|