kerols77 commited on
Commit
04945ca
·
verified ·
1 Parent(s): 91b465f

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +114 -122
app.py CHANGED
@@ -1,122 +1,114 @@
1
- import os
2
- import cv2
3
- from paddleocr import PaddleOCR
4
- import re
5
- from flask import Flask, request, jsonify
6
- from PIL import Image
7
- import pandas as pd
8
- import requests
9
- from datetime import datetime
10
- import random
11
-
12
- app = Flask(__name__)
13
- app.config['UPLOAD_FOLDER'] = 'uploads/'
14
-
15
- os.makedirs(app.config['UPLOAD_FOLDER'], exist_ok=True)
16
-
17
- def convert_image_format(input_path, output_format='PNG'):
18
- try:
19
- image = Image.open(input_path)
20
- if hasattr(image, '_getexif'):
21
- exif = image._getexif()
22
- if exif and 0x112 in exif:
23
- orientation = exif[0x112]
24
- rotations = {3: 180, 6: 270, 8: 90}
25
- if orientation in rotations:
26
- image = image.rotate(rotations[orientation], expand=True)
27
- output_path = os.path.splitext(input_path)[0] + '.' + output_format.lower()
28
- image.convert("RGB").save(output_path, format=output_format)
29
- return output_path
30
- except Exception as e:
31
- return input_path
32
-
33
- def extract_text_with_paddleocr(file_path):
34
- ocr = PaddleOCR(use_angle_cls=True, lang='en', show_log=False)
35
- result = ocr.ocr(file_path, cls=True)
36
- return result
37
-
38
- def extract_numbers_from_paddleocr(result):
39
- detected_numbers = []
40
- for line in result:
41
- for res in line:
42
- text = res[1][0]
43
- numbers = re.findall(r'\d+', text)
44
- if numbers:
45
- number_str = ''.join(numbers)
46
- detected_numbers.append(number_str)
47
- return detected_numbers
48
-
49
- def compare_numbers_with_excel(detected_numbers, excel_path='data/test.xlsx'):
50
- df = pd.read_excel(excel_path)
51
- matched_names = []
52
- for number in detected_numbers:
53
- try:
54
- match = df[df['ID'] == int(number)]
55
- if not match.empty:
56
- name = match['Name'].values[0]
57
- matched_names.append({"ID": number, "name": name})
58
- else:
59
- matched_names.append({"ID": number, "name": "The student is not in the database"})
60
- except ValueError:
61
- pass
62
- return matched_names
63
-
64
-
65
-
66
- def send_attendance_to_external_api(student_id):
67
- url = 'http://54.242.19.19:3000/api/attendance'
68
- random_id = random.randint(10000, 99999) # Generate random ID
69
-
70
- payload = {
71
- "id": str(random_id), # 👈 Send random ID
72
- "studentId": str(student_id),
73
- "status": "present",
74
- "date": datetime.now().strftime("%m/%d/%Y %I:%M:%S %p +00:00")
75
- }
76
-
77
- print(f"Sending payload: {payload}")
78
- try:
79
- response = requests.post(url, json=payload)
80
- try:
81
- return response.status_code, response.json()
82
- except ValueError:
83
- return response.status_code, {"error": "Response is not valid JSON", "raw_response": response.text}
84
- except Exception as e:
85
- print(f"Failed to send attendance for {student_id}: {e}")
86
- return 500, {"error": str(e)}
87
-
88
-
89
- @app.route('/detect_numbers', methods=['POST'])
90
- def detect_numbers():
91
- if 'file' not in request.files:
92
- return jsonify({"error": "No file part"}), 400
93
-
94
- file = request.files['file']
95
- if file.filename == '':
96
- return jsonify({"error": "No selected file"}), 400
97
-
98
- if file:
99
- filename = file.filename
100
- file_path = os.path.join(app.config['UPLOAD_FOLDER'], filename)
101
- try:
102
- file.save(file_path)
103
- file_path = convert_image_format(file_path, 'PNG')
104
- result = extract_text_with_paddleocr(file_path)
105
- detected_numbers = extract_numbers_from_paddleocr(result)
106
- if detected_numbers:
107
- matched_names = compare_numbers_with_excel(detected_numbers)
108
- for entry in matched_names:
109
- print(f"ID: {entry['ID']}, Name: {entry['name']}")
110
- if entry['name'] != "The student is not in the database":
111
- status_code, response = send_attendance_to_external_api(entry['ID'])
112
- print(f"External API response: {status_code} - {response}")
113
- return jsonify(matched_names)
114
- else:
115
- print("No numbers detected.")
116
- return jsonify({"message": "No numbers detected."})
117
- except Exception as e:
118
- print(f"Error processing the image: {e}")
119
- return jsonify({"error": str(e)}), 500
120
-
121
- if __name__ == "__main__":
122
- app.run(host='0.0.0.0', port=7860)
 
1
+ import os
2
+ import cv2
3
+ from paddleocr import PaddleOCR
4
+ import re
5
+ from flask import Flask, request, jsonify
6
+ from PIL import Image
7
+ import pandas as pd
8
+ import requests
9
+ from datetime import datetime
10
+ import random
11
+
12
+ app = Flask(__name__)
13
+ app.config['UPLOAD_FOLDER'] = 'uploads/'
14
+ os.makedirs(app.config['UPLOAD_FOLDER'], exist_ok=True)
15
+
16
+ def convert_image_format(input_path, output_format='PNG'):
17
+ try:
18
+ image = Image.open(input_path)
19
+ if hasattr(image, '_getexif'):
20
+ exif = image._getexif()
21
+ if exif and 0x112 in exif:
22
+ orientation = exif[0x112]
23
+ rotations = {3: 180, 6: 270, 8: 90}
24
+ if orientation in rotations:
25
+ image = image.rotate(rotations[orientation], expand=True)
26
+ output_path = os.path.splitext(input_path)[0] + '.' + output_format.lower()
27
+ image.convert("RGB").save(output_path, format=output_format)
28
+ return output_path
29
+ except Exception as e:
30
+ return input_path
31
+
32
+ def extract_text_with_paddleocr(file_path):
33
+ ocr = PaddleOCR(use_angle_cls=True, lang='en', show_log=False)
34
+ result = ocr.ocr(file_path, cls=True)
35
+ return result
36
+
37
+ def extract_numbers_from_paddleocr(result):
38
+ detected_numbers = []
39
+ for line in result:
40
+ for res in line:
41
+ text = res[1][0]
42
+ numbers = re.findall(r'\d+', text)
43
+ if numbers:
44
+ number_str = ''.join(numbers)
45
+ detected_numbers.append(number_str)
46
+ return detected_numbers
47
+
48
+ def compare_numbers_with_excel(detected_numbers, excel_path='data/test.xlsx'):
49
+ df = pd.read_excel(excel_path)
50
+ matched_names = []
51
+ for number in detected_numbers:
52
+ try:
53
+ match = df[df['ID'] == int(number)]
54
+ if not match.empty:
55
+ name = match['Name'].values[0]
56
+ matched_names.append({"ID": number, "name": name})
57
+ else:
58
+ matched_names.append({"ID": number, "name": "The student is not in the database"})
59
+ except ValueError:
60
+ pass
61
+ return matched_names
62
+
63
+ def send_attendance_to_external_api(student_id):
64
+ url = 'http://54.242.19.19:3000/api/attendance'
65
+ random_id = random.randint(10000, 99999)
66
+ payload = {
67
+ "id": str(random_id),
68
+ "studentId": str(student_id),
69
+ "status": "present",
70
+ "date": datetime.now().strftime("%m/%d/%Y %I:%M:%S %p +00:00")
71
+ }
72
+ print(f"Sending payload: {payload}")
73
+ try:
74
+ response = requests.post(url, json=payload)
75
+ try:
76
+ return response.status_code, response.json()
77
+ except ValueError:
78
+ return response.status_code, {"error": "Response is not valid JSON", "raw_response": response.text}
79
+ except Exception as e:
80
+ print(f"Failed to send attendance for {student_id}: {e}")
81
+ return 500, {"error": str(e)}
82
+
83
+ @app.route('/detect_numbers', methods=['POST'])
84
+ def detect_numbers():
85
+ if 'file' not in request.files:
86
+ return jsonify({"error": "No file part"}), 400
87
+ file = request.files['file']
88
+ if file.filename == '':
89
+ return jsonify({"error": "No selected file"}), 400
90
+ if file:
91
+ filename = file.filename
92
+ file_path = os.path.join(app.config['UPLOAD_FOLDER'], filename)
93
+ try:
94
+ file.save(file_path)
95
+ file_path = convert_image_format(file_path, 'PNG')
96
+ result = extract_text_with_paddleocr(file_path)
97
+ detected_numbers = extract_numbers_from_paddleocr(result)
98
+ if detected_numbers:
99
+ matched_names = compare_numbers_with_excel(detected_numbers)
100
+ for entry in matched_names:
101
+ print(f"ID: {entry['ID']}, Name: {entry['name']}")
102
+ if entry['name'] != "The student is not in the database":
103
+ status_code, response = send_attendance_to_external_api(entry['ID'])
104
+ print(f"External API response: {status_code} - {response}")
105
+ return jsonify(matched_names)
106
+ else:
107
+ print("No numbers detected.")
108
+ return jsonify({"message": "No numbers detected."})
109
+ except Exception as e:
110
+ print(f"Error processing the image: {e}")
111
+ return jsonify({"error": str(e)}), 500
112
+
113
+ if __name__ == "__main__":
114
+ app.run(host='0.0.0.0', port=7860)