Gopikanth123 commited on
Commit
2480ec8
·
verified ·
1 Parent(s): 4691c6b

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +341 -0
app.py ADDED
@@ -0,0 +1,341 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # main program
2
+ import gradio as gr
3
+ import openpyxl
4
+ from openpyxl.styles import Font, Alignment
5
+ import tempfile
6
+ from roboflow import Roboflow
7
+ from PIL import Image
8
+ import cv2
9
+ import numpy as np
10
+ import os
11
+
12
+ excel_tempfile_state = gr.State()
13
+ roll_number_state = gr.State()
14
+ sno_state = gr.State()
15
+ roll_number_state.value=1
16
+ sno_state.value=1
17
+
18
+ str_nums = {"zero":0,"one":1,"two":2,"three":3,"four":4,"five":5,"six":6,"seven":7,"eight":8,"nine":9}
19
+
20
+ def task1(Examination, Date_Of_Exam, Program, Branch, Course, Name_Of_Faculty, Academic_Year):
21
+ with tempfile.NamedTemporaryFile(suffix=".xlsx", delete=False) as temp_file:
22
+ workbook = openpyxl.Workbook()
23
+ sheet = workbook.active
24
+ # Define font styles
25
+ font_size_20 = Font(name="Times New Roman", size=20, bold=True)
26
+ font_size_18 = Font(name="Times New Roman", size=18, bold=True)
27
+ font_size_16 = Font(name="Times New Roman", size=16, bold=True)
28
+ font_size_12_bold = Font(name="Times New Roman", size=12, bold=True)
29
+
30
+ # Define alignment
31
+ alignment_center = Alignment(horizontal="center")
32
+
33
+ # Merge cells for first two rows
34
+ sheet.merge_cells('A1:P1')
35
+ sheet.merge_cells('A2:P2')
36
+ sheet['A1'].value = "LAKIREDDY BALI REDDY COLLEGE OF ENGINEERING"
37
+ sheet['A2'].value = "(AUTONOMOUS)"
38
+ sheet['A1'].font = font_size_20
39
+ sheet['A2'].font = font_size_20
40
+ sheet['A1'].alignment = alignment_center
41
+ sheet['A2'].alignment = alignment_center
42
+
43
+ # Merge cells for third row
44
+ sheet.merge_cells('A3:P3')
45
+ sheet['A3'].value = "DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING"
46
+ sheet['A3'].font = font_size_18
47
+ sheet['A3'].alignment = alignment_center
48
+
49
+ # Merge cells for fourth row
50
+ sheet.merge_cells('A4:P4')
51
+ sheet['A4'].value = "MID DESCRIPTIVE MARKS LIST"
52
+ sheet['A4'].font = font_size_16
53
+ sheet['A4'].alignment = alignment_center
54
+
55
+ # Merge cells for fifth row
56
+ sheet.merge_cells('A5:H5')
57
+ sheet.merge_cells('I5:P5')
58
+ sheet['A5'].value = f"Examination : {Examination}"
59
+ sheet['I5'].value = f"Date of Exam : {Date_Of_Exam}"
60
+ sheet['A5'].font = font_size_12_bold
61
+ sheet['I5'].font = font_size_12_bold
62
+
63
+ # Merge cells for sixth row
64
+ sheet.merge_cells('A6:H6')
65
+ sheet.merge_cells('I6:P6')
66
+ sheet['A6'].value = f"Program : {Program}"
67
+ sheet['I6'].value = f"Branch : {Branch}"
68
+ sheet['A6'].font = font_size_12_bold
69
+ sheet['I6'].font = font_size_12_bold
70
+
71
+ # Merge cells for seventh row
72
+ sheet.merge_cells('A7:H7')
73
+ sheet.merge_cells('I7:P7')
74
+ sheet['A7'].value = f"Course : {Course}"
75
+ sheet['I7'].value = "Maximum Marks : 15"
76
+ sheet['A7'].font = font_size_12_bold
77
+ sheet['I7'].font = font_size_12_bold
78
+
79
+ # Merge cells for eighth row
80
+ sheet.merge_cells('A8:H8')
81
+ sheet.merge_cells('I8:P8')
82
+ sheet['A8'].value = f"Name of the Faculty: {Name_Of_Faculty}"
83
+ sheet['I8'].value = f"Academic Year : {Academic_Year}"
84
+ sheet['A8'].font = font_size_12_bold
85
+ sheet['I8'].font = font_size_12_bold
86
+
87
+
88
+ ##part two
89
+
90
+
91
+ # Merge cells for SNo
92
+ sheet.merge_cells('A9:A10')
93
+ sheet['A9'] = "SNo"
94
+ sheet['A9'].font = font_size_12_bold
95
+ sheet['A9'].alignment = alignment_center
96
+
97
+ # Add data for Regd Num
98
+ sheet.merge_cells('B9:B10')
99
+ sheet['B9'] = "Regd Num"
100
+ sheet['B9'].font = font_size_12_bold
101
+ sheet['B9'].alignment = alignment_center
102
+
103
+ # Add data for Q. No 1
104
+ sheet.merge_cells('C9:F9')
105
+ sheet['C9'] = "Q. No 1"
106
+ sheet['C9'].font = font_size_12_bold
107
+ sheet['C9'].alignment = alignment_center
108
+ sheet['C10'] = "A"
109
+ sheet['C10'].font = font_size_12_bold
110
+ sheet['C10'].alignment = alignment_center
111
+ sheet['D10'] = "B"
112
+ sheet['D10'].font = font_size_12_bold
113
+ sheet['D10'].alignment = alignment_center
114
+ sheet['E10'] = "C"
115
+ sheet['E10'].font = font_size_12_bold
116
+ sheet['E10'].alignment = alignment_center
117
+ sheet['F10'] = "D"
118
+ sheet['F10'].font = font_size_12_bold
119
+ sheet['F10'].alignment = alignment_center
120
+
121
+ # Add data for Q. No 2
122
+ sheet.merge_cells('G9:J9')
123
+ sheet['G9'] = "Q. No 2"
124
+ sheet['G9'].font = font_size_12_bold
125
+ sheet['G9'].alignment = alignment_center
126
+ sheet['G10'] = "A"
127
+ sheet['G10'].font = font_size_12_bold
128
+ sheet['G10'].alignment = alignment_center
129
+ sheet['H10'] = "B"
130
+ sheet['H10'].font = font_size_12_bold
131
+ sheet['H10'].alignment = alignment_center
132
+ sheet['I10'] = "C"
133
+ sheet['I10'].font = font_size_12_bold
134
+ sheet['I10'].alignment = alignment_center
135
+ sheet['J10'] = "D"
136
+ sheet['J10'].font = font_size_12_bold
137
+ sheet['J10'].alignment = alignment_center
138
+
139
+ # Add data for Q. No 3
140
+ sheet.merge_cells('K9:N9')
141
+ sheet['K9'] = "Q. No 3"
142
+ sheet['K9'].font = font_size_12_bold
143
+ sheet['K9'].alignment = alignment_center
144
+ sheet['K10'] = "A"
145
+ sheet['K10'].font = font_size_12_bold
146
+ sheet['K10'].alignment = alignment_center
147
+ sheet['L10'] = "B"
148
+ sheet['L10'].font = font_size_12_bold
149
+ sheet['L10'].alignment = alignment_center
150
+ sheet['M10'] = "C"
151
+ sheet['M10'].font = font_size_12_bold
152
+ sheet['M10'].alignment = alignment_center
153
+ sheet['N10'] = "D"
154
+ sheet['N10'].font = font_size_12_bold
155
+ sheet['N10'].alignment = alignment_center
156
+
157
+ # Add data for Total(30M)
158
+ sheet.merge_cells('O9:O10')
159
+ sheet['O9'] = "Total(30M)"
160
+ sheet['O9'].font = font_size_12_bold
161
+ sheet['O9'].alignment = alignment_center
162
+
163
+ # Add data for (Total 15 M)
164
+ sheet.merge_cells('P9:P10')
165
+ sheet['P9'] = "(Total 15 M)"
166
+ sheet['P9'].font = font_size_12_bold
167
+ sheet['P9'].alignment = alignment_center
168
+ workbook.save(temp_file.name)
169
+ excel_tempfile_state.value = temp_file.name
170
+ print(excel_tempfile_state.value)
171
+ return temp_file.name
172
+
173
+
174
+
175
+
176
+ #configuring interface 1
177
+ inputs = [
178
+ gr.components.Textbox(label="Examination"),
179
+ gr.components.Textbox(label="Date Of Exam"),
180
+ gr.components.Textbox(label="Program"),
181
+ gr.components.Textbox(label="Branch"),
182
+ gr.components.Textbox(label="Course"),
183
+ gr.components.Textbox(label="Name Of Faculty"),
184
+ gr.components.Textbox(label="Academic Year"),
185
+ ]
186
+ # interface one
187
+ iface1 = gr.Interface(
188
+ fn=task1,
189
+ inputs=inputs,
190
+ outputs="file",
191
+ title="Automating Examination Mark Entry with Deep Learning"
192
+ )
193
+
194
+
195
+ def predict_and_crop(image_np, api_key, project_name, model_version, confidence=40, overlap=30):
196
+ img = Image.fromarray(image_np)
197
+ rf = Roboflow(api_key=api_key)
198
+ project = rf.workspace().project(project_name)
199
+ model = project.version(model_version).model
200
+ corners = model.predict(image_np, confidence=confidence, overlap=overlap).json()
201
+ predictions = corners["predictions"][0]
202
+ prediction = {key: int(value) for key, value in predictions.items() if key in ['x', 'y', 'width', 'height']}
203
+ x1 = int(prediction['x'] - prediction['width'] / 2)
204
+ y1 = int(prediction['y'] - prediction['height'] / 2)
205
+ x2 = int(prediction['x'] + prediction['width'] / 2)
206
+ y2 = int(prediction['y'] + prediction['height'] / 2)
207
+ cropped_img = img.crop((x1, y1, x2, y2))
208
+ cropped_img_np = np.array(cropped_img)
209
+ h, w, c = cropped_img_np.shape
210
+ if h > w:
211
+ cropped_img_np = cv2.rotate(cropped_img_np, cv2.ROTATE_90_CLOCKWISE)
212
+ return cropped_img_np, img # Return both cropped image and original image
213
+
214
+ # Function to resize and insert cropped image
215
+ def resize_and_insert(cropped_image, base_image_path, output_image_path):
216
+ base_image = cv2.imread(base_image_path)
217
+ base_height, base_width = base_image.shape[:2]
218
+ base_aspect_ratio = base_width / base_height
219
+ new_width = int(base_height * base_aspect_ratio)
220
+ resized_cropped_img = cv2.resize(cropped_image, (new_width, base_height))
221
+ base_image[0:base_height, 0:new_width] = resized_cropped_img
222
+ # cv2.imwrite(output_image_path, base_image)
223
+ return base_image
224
+
225
+ # Function to convert string to integer based on confidence level
226
+ def convert_str_int(var, conf):
227
+ if conf < 0.5:
228
+ return " "
229
+ else:
230
+ return str_nums[var]
231
+
232
+ def append_to_workbook(cells_data, excel_file_path):
233
+ workbook = openpyxl.load_workbook(excel_file_path)
234
+ sheet = workbook.active
235
+
236
+ # Retrieve current SNo and roll number from state
237
+ sno = sno_state.value
238
+ rno = roll_number_state.value
239
+ if rno<10:
240
+ rno_str = "21761A420"+str(rno)
241
+ else:
242
+ rno_str = "21761A42"+str(rno)
243
+ # Increment SNo and roll number
244
+ sno_state.value = sno + 1
245
+ roll_number_state.value = rno + 1
246
+
247
+ next_row = sheet.max_row + 1
248
+
249
+ # Insert roll number and SNo
250
+ sheet.cell(row=next_row, column=1, value=sno)
251
+ sheet.cell(row=next_row, column=2, value=rno_str)
252
+ for col, value in enumerate(cells_data, start=3):
253
+ sheet.cell(row=next_row, column=col, value=value)
254
+ marks=[]
255
+ for i in cells_data:
256
+ if str(i).isdigit():
257
+ marks.append(int(i))
258
+ else:
259
+ marks.append(0)
260
+ total_30_marks = max(sum(marks[0:2]),sum(marks[2:4]))+max(sum(marks[4:6]),sum(marks[6:8]))+max(sum(marks[8:10]),sum(marks[10:12]))
261
+ total_15_marks = round(total_30_marks / 2, 2)
262
+ sheet.cell(row=next_row, column=15, value=total_30_marks)
263
+ sheet.cell(row=next_row, column=16, value=total_15_marks)
264
+ # Save the workbook
265
+ workbook.save(excel_file_path)
266
+
267
+
268
+
269
+
270
+
271
+
272
+
273
+ #All Functions for interface 2
274
+ def task2(image_np):
275
+ api_key = "LimDLja7HF1Asuk3vfSd"
276
+ project_name = "marks_table_detection_lbrce"
277
+ model_version = 1
278
+ base_image_path = "/content/drive/MyDrive/base_img.jpg"
279
+ temp_image_path = "temp_image.jpg"
280
+ output_image_path = "merged_image.jpg"
281
+
282
+ #API and requirements for OCR Model
283
+ rf = Roboflow(api_key="XsMt3y86MNDGihOYcWDY")
284
+ project = rf.workspace().project("mnist-cjkff")
285
+ model = project.version(2).model
286
+
287
+ # Predict and crop
288
+ cropped_image, original_image = predict_and_crop(image_np, api_key, project_name, model_version)
289
+
290
+ # Resize and insert
291
+ result_image = resize_and_insert(cropped_image, base_image_path, output_image_path)
292
+
293
+ # Cell coordinates
294
+ cell_coordinates = cell_coordinates = [(235, 129), (475, 223), (496, 125), (685, 225), (708, 127), (896, 225), (919, 125), (1140, 217), (232, 253), (473, 346), (500, 249), (687, 347), (708, 250), (896, 346), (920, 249), (1142, 345), (232, 375), (474, 442), (496, 371), (686, 442), (708, 373), (897, 444), (922, 373), (1147, 443)]
295
+ cells_data = []
296
+ qno = 0
297
+
298
+ for i in range(0, len(cell_coordinates), 2):
299
+ top_left = cell_coordinates[i]
300
+ bottom_right = cell_coordinates[i + 1]
301
+ cell = result_image[top_left[1]:bottom_right[1], top_left[0]:bottom_right[0]]
302
+ cell_gray = cv2.cvtColor(cell, cv2.COLOR_BGR2GRAY)
303
+ _, thresholded_cell = cv2.threshold(cell_gray, 127, 255, cv2.THRESH_BINARY_INV)
304
+
305
+ _, temp_thresholded_path = tempfile.mkstemp(suffix=".jpg")
306
+ cv2.imwrite(temp_thresholded_path, thresholded_cell)
307
+
308
+ res = model.predict(temp_thresholded_path).json()
309
+ var = res["predictions"][0]["predictions"][0]["class"]
310
+ conf = res["predictions"][0]["predictions"][0]["confidence"]
311
+ cells_data.append(convert_str_int(var, conf))
312
+ qno += 1
313
+ excel_file_path = excel_tempfile_state.value
314
+ append_to_workbook(cells_data,excel_file_path)
315
+ print(cells_data)
316
+ return cropped_image, cells_data, excel_file_path
317
+
318
+ # # interface two
319
+ # iface2 = gr.Interface(
320
+ # fn=task2,
321
+ # inputs="image",
322
+ # outputs="text",
323
+ # title="Automating Examination Mark Entry with Deep Learning"
324
+ # )
325
+ iface2 = gr.Interface(
326
+ fn=task2,
327
+ elem_id="my-interface",
328
+ inputs=gr.components.Image(type="numpy", label="Upload Image"),
329
+ outputs=[
330
+ gr.components.Image(type="numpy", label="Cropped Image"),
331
+ gr.components.Textbox(label="Detected Marks"),
332
+ gr.components.File(label="marks_sheet")
333
+ ],
334
+ title="Automating Examination Mark Entry with Deep Learning",
335
+ theme="huggingface"
336
+ )
337
+
338
+ demo = gr.TabbedInterface([iface1, iface2], ["Configure Excel Sheet Data", "Extract marks from Answer Sheets"])
339
+
340
+ # Run the interface
341
+ demo.launch(share=True,debug=True)