Spaces:
Sleeping
Sleeping
randomshit11
commited on
Upload 2 files
Browse files- main.py +20 -0
- predict.py +36 -0
main.py
ADDED
@@ -0,0 +1,20 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from fastapi import FastAPI, File
|
2 |
+
from io import BytesIO
|
3 |
+
from PIL import Image
|
4 |
+
from predict import read_image, transformacao
|
5 |
+
|
6 |
+
app = FastAPI()
|
7 |
+
|
8 |
+
@app.get("/")
|
9 |
+
async def root():
|
10 |
+
return {"message": "Idiot, you are in the wrong place!"}
|
11 |
+
|
12 |
+
@app.post("/uploadfile/")
|
13 |
+
async def create_upload_file(file: bytes = File(...)):
|
14 |
+
|
15 |
+
# read image
|
16 |
+
imagem = read_image(file)
|
17 |
+
# transform and prediction
|
18 |
+
prediction = transformacao(imagem)
|
19 |
+
|
20 |
+
return prediction
|
predict.py
ADDED
@@ -0,0 +1,36 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from transformers import AutoImageProcessor, AutoModelForImageClassification
|
2 |
+
from PIL import Image
|
3 |
+
import torch
|
4 |
+
import numpy as np
|
5 |
+
from io import BytesIO # Add this import statement
|
6 |
+
|
7 |
+
processor = AutoImageProcessor.from_pretrained("dima806/medicinal_plants_image_detection")
|
8 |
+
model = AutoModelForImageClassification.from_pretrained("dima806/medicinal_plants_image_detection")
|
9 |
+
|
10 |
+
def read_image(file) -> Image.Image:
|
11 |
+
pil_image = Image.open(BytesIO(file))
|
12 |
+
return pil_image
|
13 |
+
|
14 |
+
def transformacao(file: Image.Image):
|
15 |
+
inputs = processor(images=file, return_tensors="pt", padding=True)
|
16 |
+
|
17 |
+
with torch.no_grad():
|
18 |
+
outputs = model(**inputs)
|
19 |
+
|
20 |
+
logits = outputs.logits
|
21 |
+
probabilities = logits.softmax(dim=1).squeeze()
|
22 |
+
|
23 |
+
# Get top 3 predictions
|
24 |
+
top3_probabilities, top3_indices = torch.topk(probabilities, 3)
|
25 |
+
|
26 |
+
labels = model.config.id2label
|
27 |
+
|
28 |
+
response = []
|
29 |
+
for prob, idx in zip(top3_probabilities, top3_indices):
|
30 |
+
resp = {}
|
31 |
+
resp["class"] = labels[idx.item()]
|
32 |
+
resp["confidence"] = f"{prob.item()*100:0.2f} %"
|
33 |
+
response.append(resp)
|
34 |
+
|
35 |
+
return response
|
36 |
+
|