Spaces:
Sleeping
Sleeping
Delete bad version app-hf.py
Browse files
app-hf.py
DELETED
|
@@ -1,53 +0,0 @@
|
|
| 1 |
-
from fastapi import FastAPI, HTTPException, Response
|
| 2 |
-
from fastapi.responses import HTMLResponse
|
| 3 |
-
from transformers import pipeline, YolosForObjectDetection, YolosImageProcessor
|
| 4 |
-
from PIL import Image, ImageDraw
|
| 5 |
-
import torch
|
| 6 |
-
import requests
|
| 7 |
-
import io
|
| 8 |
-
import base64
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
app = FastAPI() # Create a new FastAPI app instance
|
| 12 |
-
|
| 13 |
-
# Initialize the Yolos model and image processor
|
| 14 |
-
yolos_model = YolosForObjectDetection.from_pretrained('hustvl/yolos-tiny')
|
| 15 |
-
yolos_image_processor = YolosImageProcessor.from_pretrained("hustvl/yolos-tiny")
|
| 16 |
-
|
| 17 |
-
# Define a route for the root "/"
|
| 18 |
-
@app.get("/")
|
| 19 |
-
def read_root():
|
| 20 |
-
return {"message": "Welcome to the YOLOS Object Detection API!"}
|
| 21 |
-
|
| 22 |
-
# Define a route for detecting objects from an image URL
|
| 23 |
-
@app.get("/", response_class=HTMLResponse)
|
| 24 |
-
def detect_objects(url: str):
|
| 25 |
-
try:
|
| 26 |
-
# Download the image from the specified URL
|
| 27 |
-
image = Image.open(requests.get(url, stream=True).raw)
|
| 28 |
-
|
| 29 |
-
# Preprocess the image using the Yolos image processor
|
| 30 |
-
inputs = yolos_image_processor(images=image, return_tensors="pt")
|
| 31 |
-
|
| 32 |
-
# Run the Yolos model on the preprocessed image
|
| 33 |
-
outputs = yolos_model(**inputs)
|
| 34 |
-
|
| 35 |
-
# Post-process the object detection results
|
| 36 |
-
target_sizes = torch.tensor([image.size[::-1]])
|
| 37 |
-
results = yolos_image_processor.post_process_object_detection(outputs, threshold=0.9, target_sizes=target_sizes)[0]
|
| 38 |
-
|
| 39 |
-
# Draw bounding boxes on the image
|
| 40 |
-
for score, label, box in zip(results["scores"], results["labels"], results["boxes"]):
|
| 41 |
-
image_draw = ImageDraw.Draw(image)
|
| 42 |
-
image_draw.rectangle(box.tolist(), outline="red", width=2)
|
| 43 |
-
image_draw.text((box[0], box[1]), f"{yolos_model.config.id2label[label.item()]}: {round(score.item(), 3)}", fill="red")
|
| 44 |
-
|
| 45 |
-
# Save the modified image to a byte stream
|
| 46 |
-
image_byte_array = io.BytesIO()
|
| 47 |
-
image.save(image_byte_array, format="PNG")
|
| 48 |
-
|
| 49 |
-
# Return the image as a Response with content type "image/png"
|
| 50 |
-
return Response(content=image_byte_array.getvalue(), media_type="image/png")
|
| 51 |
-
|
| 52 |
-
except Exception as e:
|
| 53 |
-
raise HTTPException(status_code=500, detail=f"Error processing image: {str(e)}")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|