yomna-ashraf commited on
Commit
acb2a86
·
verified ·
1 Parent(s): b5836d4

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +73 -75
app.py CHANGED
@@ -1,75 +1,73 @@
1
- from flask import Flask, request, jsonify
2
- from transformers import AutoModelForImageClassification, AutoProcessor
3
- from PIL import Image
4
- import io
5
- import fitz # PyMuPDF
6
- from flask_cors import CORS
7
- import os
8
-
9
- app = Flask(__name__)
10
- CORS(app)
11
-
12
- model_name = "AsmaaElnagger/Diabetic_RetinoPathy_detection"
13
- model = AutoModelForImageClassification.from_pretrained(model_name)
14
- processor = AutoProcessor.from_pretrained(model_name)
15
-
16
- def pdf_to_images_pymupdf(pdf_data):
17
- try:
18
- pdf_document = fitz.open(stream=pdf_data, filetype="pdf")
19
- images = []
20
- for page_num in range(pdf_document.page_count):
21
- page = pdf_document.load_page(page_num)
22
- pix = page.get_pixmap()
23
- img_data = pix.tobytes("jpeg") # Or "png"
24
- images.append(img_data)
25
- return images
26
- except Exception as e:
27
- print(f"Error converting PDF: {e}")
28
- return None
29
-
30
- @app.route('/classify', methods=['POST'])
31
- def classify_file():
32
- if 'file' not in request.files:
33
- return jsonify({'error': 'No file provided'}), 400
34
-
35
- uploaded_file = request.files['file']
36
- file_type = uploaded_file.filename.rsplit('.', 1)[1].lower()
37
-
38
- try:
39
- if file_type in ['jpg', 'jpeg', 'png', 'gif']:
40
- # Handle image upload
41
- img_data = uploaded_file.read()
42
- image = Image.open(io.BytesIO(img_data)).convert("RGB")
43
- inputs = processor(images=image, return_tensors="pt")
44
- outputs = model(**inputs)
45
- logits = outputs.logits
46
- predicted_class_idx = logits.argmax(-1).item()
47
- result = model.config.id2label[predicted_class_idx]
48
- return jsonify({'result': result})
49
-
50
- elif file_type == 'pdf':
51
- # Handle PDF upload
52
- pdf_data = uploaded_file.read()
53
- images = pdf_to_images_pymupdf(pdf_data)
54
-
55
- if images:
56
- # Process the first image in the pdf, you may need to loop through all images.
57
- image = Image.open(io.BytesIO(images[0])).convert("RGB")
58
- inputs = processor(images=image, return_tensors="pt")
59
- outputs = model(**inputs)
60
- logits = outputs.logits
61
- predicted_class_idx = logits.argmax(-1).item()
62
- result = model.config.id2label[predicted_class_idx]
63
- return jsonify({'result': result})
64
- else:
65
- return jsonify({'error': 'PDF conversion failed.'}), 500
66
-
67
- else:
68
- return jsonify({'error': 'Unsupported file type'}), 400
69
-
70
- except Exception as e:
71
- return jsonify({'error': f'An error occurred: {e}'}), 500
72
-
73
- if __name__ == '__main__':
74
- # For Hugging Face Spaces, we need to bind to 0.0.0.0 and use the default port 8080
75
- app.run(debug=False, host="0.0.0.0", port=int(os.environ.get("PORT", 8080)))
 
1
+ import gradio as gr
2
+ from transformers import AutoModelForImageClassification, AutoProcessor
3
+ from PIL import Image
4
+ import io
5
+ import fitz # PyMuPDF
6
+
7
+ model_name = "AsmaaElnagger/Diabetic_RetinoPathy_detection"
8
+ model = AutoModelForImageClassification.from_pretrained(model_name)
9
+ processor = AutoProcessor.from_pretrained(model_name)
10
+
11
+ def pdf_to_images_pymupdf(pdf_data):
12
+ try:
13
+ pdf_document = fitz.open(stream=pdf_data, filetype="pdf")
14
+ images = []
15
+ for page_num in range(pdf_document.page_count):
16
+ page = pdf_document.load_page(page_num)
17
+ pix = page.get_pixmap()
18
+ img_data = pix.tobytes("jpeg") # Or "png"
19
+ images.append(img_data)
20
+ return images
21
+ except Exception as e:
22
+ print(f"Error converting PDF: {e}")
23
+ return None
24
+
25
+ def classify_file(file):
26
+ # Get the file type
27
+ file_type = file.name.split('.')[-1].lower()
28
+
29
+ try:
30
+ if file_type in ['jpg', 'jpeg', 'png', 'gif']:
31
+ # Handle image upload
32
+ image = Image.open(file).convert("RGB")
33
+ inputs = processor(images=image, return_tensors="pt")
34
+ outputs = model(**inputs)
35
+ logits = outputs.logits
36
+ predicted_class_idx = logits.argmax(-1).item()
37
+ result = model.config.id2label[predicted_class_idx]
38
+ return result
39
+
40
+ elif file_type == 'pdf':
41
+ # Handle PDF upload
42
+ pdf_data = file.read()
43
+ images = pdf_to_images_pymupdf(pdf_data)
44
+
45
+ if images:
46
+ # Process the first image in the pdf, you may need to loop through all images.
47
+ image = Image.open(io.BytesIO(images[0])).convert("RGB")
48
+ inputs = processor(images=image, return_tensors="pt")
49
+ outputs = model(**inputs)
50
+ logits = outputs.logits
51
+ predicted_class_idx = logits.argmax(-1).item()
52
+ result = model.config.id2label[predicted_class_idx]
53
+ return result
54
+ else:
55
+ return 'PDF conversion failed.'
56
+
57
+ else:
58
+ return 'Unsupported file type'
59
+
60
+ except Exception as e:
61
+ return f'An error occurred: {e}'
62
+
63
+ # Create the Gradio interface
64
+ demo = gr.Interface(
65
+ fn=classify_file,
66
+ inputs=gr.File(label="Upload PDF or Image"),
67
+ outputs="text",
68
+ title="Diabetic Retinopathy Detection",
69
+ description="Upload an image or PDF for classification."
70
+ )
71
+
72
+ # Launch the Gradio app
73
+ demo.launch()