Spaces:
Build error
Build error
Update app.py
Browse files
app.py
CHANGED
@@ -3,15 +3,19 @@ from transformers import AutoModelForImageClassification, AutoProcessor
|
|
3 |
from PIL import Image
|
4 |
import io
|
5 |
import fitz # PyMuPDF
|
6 |
-
|
|
|
|
|
|
|
7 |
|
8 |
app = Flask(__name__)
|
9 |
-
CORS(app)
|
10 |
|
|
|
11 |
model_name = "AsmaaElnagger/Diabetic_RetinoPathy_detection"
|
12 |
model = AutoModelForImageClassification.from_pretrained(model_name)
|
13 |
processor = AutoProcessor.from_pretrained(model_name)
|
14 |
|
|
|
15 |
def pdf_to_images_pymupdf(pdf_data):
|
16 |
try:
|
17 |
pdf_document = fitz.open(stream=pdf_data, filetype="pdf")
|
@@ -26,36 +30,62 @@ def pdf_to_images_pymupdf(pdf_data):
|
|
26 |
print(f"Error converting PDF: {e}")
|
27 |
return None
|
28 |
|
29 |
-
|
30 |
-
def classify_file():
|
31 |
-
if 'file' not in request.files:
|
32 |
-
return jsonify({'error': 'No file provided'}), 400
|
33 |
-
|
34 |
-
uploaded_file = request.files['file']
|
35 |
-
file_type = uploaded_file.filename.rsplit('.', 1)[-1].lower()
|
36 |
-
|
37 |
try:
|
38 |
-
|
39 |
-
|
40 |
-
|
41 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
42 |
images = pdf_to_images_pymupdf(pdf_data)
|
43 |
-
if
|
44 |
-
|
45 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
46 |
else:
|
47 |
-
return
|
48 |
-
|
49 |
-
|
50 |
-
outputs = model(**inputs)
|
51 |
-
logits = outputs.logits
|
52 |
-
predicted_class_idx = logits.argmax(-1).item()
|
53 |
-
result = model.config.id2label[predicted_class_idx]
|
54 |
|
55 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
56 |
|
57 |
-
|
58 |
-
|
|
|
|
|
|
|
|
|
59 |
|
60 |
if __name__ == '__main__':
|
61 |
-
app.run(host=
|
|
|
3 |
from PIL import Image
|
4 |
import io
|
5 |
import fitz # PyMuPDF
|
6 |
+
import os
|
7 |
+
import torch
|
8 |
+
import torch.nn.functional as F
|
9 |
+
from werkzeug.utils import secure_filename
|
10 |
|
11 |
app = Flask(__name__)
|
|
|
12 |
|
13 |
+
# Load model and processor
|
14 |
model_name = "AsmaaElnagger/Diabetic_RetinoPathy_detection"
|
15 |
model = AutoModelForImageClassification.from_pretrained(model_name)
|
16 |
processor = AutoProcessor.from_pretrained(model_name)
|
17 |
|
18 |
+
# PDF to image conversion
|
19 |
def pdf_to_images_pymupdf(pdf_data):
|
20 |
try:
|
21 |
pdf_document = fitz.open(stream=pdf_data, filetype="pdf")
|
|
|
30 |
print(f"Error converting PDF: {e}")
|
31 |
return None
|
32 |
|
33 |
+
# File classification function (modified for API)
|
34 |
+
def classify_file(file_path):
|
|
|
|
|
|
|
|
|
|
|
|
|
35 |
try:
|
36 |
+
file_ext = os.path.splitext(file_path)[-1].lower()
|
37 |
+
if file_ext in ['.jpg', '.jpeg', '.png', '.gif']:
|
38 |
+
# Handle image upload
|
39 |
+
image = Image.open(file_path).convert("RGB")
|
40 |
+
inputs = processor(images=image, return_tensors="pt")
|
41 |
+
outputs = model(**inputs)
|
42 |
+
probabilities = F.softmax(outputs.logits, dim=-1)[0].tolist()
|
43 |
+
predicted_class_idx = outputs.logits.argmax(-1).item()
|
44 |
+
result_label = model.config.id2label[predicted_class_idx]
|
45 |
+
confidence = probabilities[predicted_class_idx] * 100
|
46 |
+
return {
|
47 |
+
"prediction": result_label,
|
48 |
+
"confidence": confidence
|
49 |
+
}
|
50 |
+
elif file_ext == '.pdf':
|
51 |
+
# Handle PDF upload
|
52 |
+
with open(file_path, "rb") as f:
|
53 |
+
pdf_data = f.read()
|
54 |
images = pdf_to_images_pymupdf(pdf_data)
|
55 |
+
if images:
|
56 |
+
image = Image.open(io.BytesIO(images[0])).convert("RGB")
|
57 |
+
inputs = processor(images=image, return_tensors="pt")
|
58 |
+
outputs = model(**inputs)
|
59 |
+
probabilities = F.softmax(outputs.logits, dim=-1)[0].tolist()
|
60 |
+
predicted_class_idx = outputs.logits.argmax(-1).item()
|
61 |
+
result_label = model.config.id2label[predicted_class_idx]
|
62 |
+
confidence = probabilities[predicted_class_idx] * 100
|
63 |
+
return {
|
64 |
+
"prediction": result_label,
|
65 |
+
"confidence": confidence
|
66 |
+
}
|
67 |
+
else:
|
68 |
+
return {"error": "PDF conversion failed."}
|
69 |
else:
|
70 |
+
return {"error": "Unsupported file type."}
|
71 |
+
except Exception as e:
|
72 |
+
return {"error": f"An error occurred: {e}"}
|
|
|
|
|
|
|
|
|
73 |
|
74 |
+
# API endpoint for file classification
|
75 |
+
@app.route('/classify', methods=['POST'])
|
76 |
+
def classify():
|
77 |
+
if 'file' not in request.files:
|
78 |
+
return jsonify({"error": "No file part"}), 400
|
79 |
+
file = request.files['file']
|
80 |
+
if file.filename == '':
|
81 |
+
return jsonify({"error": "No file selected"}), 400
|
82 |
|
83 |
+
filename = secure_filename(file.filename)
|
84 |
+
filepath = os.path.join('/tmp', filename) # Save to a temporary location
|
85 |
+
file.save(filepath)
|
86 |
+
result = classify_file(filepath)
|
87 |
+
os.remove(filepath) #remove temp file
|
88 |
+
return jsonify(result), 200 # Return JSON response
|
89 |
|
90 |
if __name__ == '__main__':
|
91 |
+
app.run(host='0.0.0.0', port=5000)
|