yomna-ashraf commited on
Commit
167c1f9
·
verified ·
1 Parent(s): 6e597cb

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +82 -61
app.py CHANGED
@@ -1,61 +1,82 @@
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
-
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")
18
- images = []
19
- for page_num in range(pdf_document.page_count):
20
- page = pdf_document.load_page(page_num)
21
- pix = page.get_pixmap()
22
- img_data = pix.tobytes("jpeg")
23
- images.append(img_data)
24
- return images
25
- except Exception as e:
26
- print(f"Error converting PDF: {e}")
27
- return None
28
-
29
- @app.route('/classify', methods=['POST'])
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
- if file_type in ['jpg', 'jpeg', 'png']:
39
- image = Image.open(uploaded_file).convert("RGB")
40
- elif file_type == 'pdf':
41
- pdf_data = uploaded_file.read()
42
- images = pdf_to_images_pymupdf(pdf_data)
43
- if not images:
44
- return jsonify({'error': 'Failed to convert PDF.'}), 500
45
- image = Image.open(io.BytesIO(images[0])).convert("RGB")
46
- else:
47
- return jsonify({'error': 'Unsupported file type'}), 400
48
-
49
- inputs = processor(images=image, return_tensors="pt")
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
- return jsonify({'result': result})
56
-
57
- except Exception as e:
58
- return jsonify({'error': str(e)}), 500
59
-
60
- if __name__ == '__main__':
61
- app.run(host="0.0.0.0", port=7860)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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, cross_origin
7
+
8
+ app = Flask(__name__)
9
+ CORS(app)
10
+
11
+ # Add debugging logs to check the model loading process
12
+ model_name = "AsmaaElnagger/Diabetic_RetinoPathy_detection"
13
+
14
+ try:
15
+ print("Loading model...")
16
+ model = AutoModelForImageClassification.from_pretrained(model_name, cache_dir="/mnt/data") # Specifying the cache dir for Hugging Face Space
17
+ processor = AutoProcessor.from_pretrained(model_name, cache_dir="/mnt/data")
18
+ print("Model loaded successfully.")
19
+ except Exception as e:
20
+ print(f"Error loading model: {e}")
21
+
22
+ # Function to convert PDF to images
23
+ def pdf_to_images_pymupdf(pdf_data):
24
+ try:
25
+ pdf_document = fitz.open(stream=pdf_data, filetype="pdf")
26
+ images = []
27
+ for page_num in range(pdf_document.page_count):
28
+ page = pdf_document.load_page(page_num)
29
+ pix = page.get_pixmap()
30
+ img_data = pix.tobytes("jpeg") # Or "png"
31
+ images.append(img_data)
32
+ return images
33
+ except Exception as e:
34
+ print(f"Error converting PDF: {e}")
35
+ return None
36
+
37
+ @app.route('/classify', methods=['POST'])
38
+ @cross_origin() # Allows cross-origin requests (important for frontend)
39
+ def classify_file():
40
+ if 'file' not in request.files:
41
+ return jsonify({'error': 'No file provided'}), 400
42
+
43
+ uploaded_file = request.files['file']
44
+ file_type = uploaded_file.filename.rsplit('.', 1)[1].lower()
45
+
46
+ try:
47
+ if file_type in ['jpg', 'jpeg', 'png', 'gif']:
48
+ # Handle image upload
49
+ img_data = uploaded_file.read()
50
+ image = Image.open(io.BytesIO(img_data)).convert("RGB")
51
+ inputs = processor(images=image, return_tensors="pt")
52
+ outputs = model(**inputs)
53
+ logits = outputs.logits
54
+ predicted_class_idx = logits.argmax(-1).item()
55
+ result = model.config.id2label[predicted_class_idx]
56
+ return jsonify({'result': result})
57
+
58
+ elif file_type == 'pdf':
59
+ # Handle PDF upload
60
+ pdf_data = uploaded_file.read()
61
+ images = pdf_to_images_pymupdf(pdf_data)
62
+
63
+ if images:
64
+ # Process the first image in the pdf, you may need to loop through all images.
65
+ image = Image.open(io.BytesIO(images[0])).convert("RGB")
66
+ inputs = processor(images=image, return_tensors="pt")
67
+ outputs = model(**inputs)
68
+ logits = outputs.logits
69
+ predicted_class_idx = logits.argmax(-1).item()
70
+ result = model.config.id2label[predicted_class_idx]
71
+ return jsonify({'result': result})
72
+ else:
73
+ return jsonify({'error': 'PDF conversion failed.'}), 500
74
+
75
+ else:
76
+ return jsonify({'error': 'Unsupported file type'}), 400
77
+
78
+ except Exception as e:
79
+ return jsonify({'error': f'An error occurred: {e}'}), 500
80
+
81
+ if __name__ == '__main__':
82
+ app.run(port=5001, debug=True)