File size: 4,363 Bytes
04945ca
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
import os
import cv2
from paddleocr import PaddleOCR
import re
from flask import Flask, request, jsonify
from PIL import Image
import pandas as pd
import requests
from datetime import datetime
import random

app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = 'uploads/'
os.makedirs(app.config['UPLOAD_FOLDER'], exist_ok=True)

def convert_image_format(input_path, output_format='PNG'):
    try:
        image = Image.open(input_path)
        if hasattr(image, '_getexif'):
            exif = image._getexif()
            if exif and 0x112 in exif:
                orientation = exif[0x112]
                rotations = {3: 180, 6: 270, 8: 90}
                if orientation in rotations:
                    image = image.rotate(rotations[orientation], expand=True)
        output_path = os.path.splitext(input_path)[0] + '.' + output_format.lower()
        image.convert("RGB").save(output_path, format=output_format)
        return output_path
    except Exception as e:
        return input_path

def extract_text_with_paddleocr(file_path):
    ocr = PaddleOCR(use_angle_cls=True, lang='en', show_log=False)
    result = ocr.ocr(file_path, cls=True)
    return result

def extract_numbers_from_paddleocr(result):
    detected_numbers = []
    for line in result:
        for res in line:
            text = res[1][0]
            numbers = re.findall(r'\d+', text)
            if numbers:
                number_str = ''.join(numbers)
                detected_numbers.append(number_str)
    return detected_numbers

def compare_numbers_with_excel(detected_numbers, excel_path='data/test.xlsx'):
    df = pd.read_excel(excel_path)
    matched_names = []
    for number in detected_numbers:
        try:
            match = df[df['ID'] == int(number)]
            if not match.empty:
                name = match['Name'].values[0]
                matched_names.append({"ID": number, "name": name})
            else:
                matched_names.append({"ID": number, "name": "The student is not in the database"})
        except ValueError:
            pass
    return matched_names

def send_attendance_to_external_api(student_id):
    url = 'http://54.242.19.19:3000/api/attendance'
    random_id = random.randint(10000, 99999)
    payload = {
        "id": str(random_id),
        "studentId": str(student_id),
        "status": "present",
        "date": datetime.now().strftime("%m/%d/%Y %I:%M:%S %p +00:00")
    }
    print(f"Sending payload: {payload}")
    try:
        response = requests.post(url, json=payload)
        try:
            return response.status_code, response.json()
        except ValueError:
            return response.status_code, {"error": "Response is not valid JSON", "raw_response": response.text}
    except Exception as e:
        print(f"Failed to send attendance for {student_id}: {e}")
        return 500, {"error": str(e)}

@app.route('/detect_numbers', methods=['POST'])
def detect_numbers():
    if 'file' not in request.files:
        return jsonify({"error": "No file part"}), 400
    file = request.files['file']
    if file.filename == '':
        return jsonify({"error": "No selected file"}), 400
    if file:
        filename = file.filename
        file_path = os.path.join(app.config['UPLOAD_FOLDER'], filename)
        try:
            file.save(file_path)
            file_path = convert_image_format(file_path, 'PNG')
            result = extract_text_with_paddleocr(file_path)
            detected_numbers = extract_numbers_from_paddleocr(result)
            if detected_numbers:
                matched_names = compare_numbers_with_excel(detected_numbers)
                for entry in matched_names:
                    print(f"ID: {entry['ID']}, Name: {entry['name']}")
                    if entry['name'] != "The student is not in the database":
                        status_code, response = send_attendance_to_external_api(entry['ID'])
                        print(f"External API response: {status_code} - {response}")
                return jsonify(matched_names)
            else:
                print("No numbers detected.")
                return jsonify({"message": "No numbers detected."})
        except Exception as e:
            print(f"Error processing the image: {e}")
            return jsonify({"error": str(e)}), 500

if __name__ == "__main__":
    app.run(host='0.0.0.0', port=7860)