Prathamesh1420 commited on
Commit
970030e
·
verified ·
1 Parent(s): 8500b56

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +76 -130
app.py CHANGED
@@ -1,132 +1,78 @@
1
  import cv2
2
- import os
3
- import logging
4
  import streamlit as st
5
- from sqlalchemy import text
6
- from preprocess import read_image, extract_id_card, save_image
7
- from ocr_engine import extract_text
8
- from postprocess import extract_information
9
- from face_verification import detect_and_extract_face, face_comparison, get_face_embeddings
10
- from mysqldb_operations import insert_records, fetch_records, check_duplicacy
11
-
12
- # {
13
- # "ID": "CCNPA",
14
- # "Name": "BIBEK RAUTH",
15
- # "Father's Name": "AJAY RAUTH",
16
- # "DOB": "14/09/1994",
17
- # "ID Type": "PAN"
18
- # }
19
-
20
-
21
- logging_str = "[%(asctime)s: %(levelname)s: %(module)s]: %(message)s"
22
- log_dir = "logs"
23
- os.makedirs(log_dir, exist_ok=True)
24
- logging.basicConfig(filename=os.path.join(log_dir,"ekyc_logs.log"), level=logging.INFO, format=logging_str, filemode="a")
25
-
26
- # Set wider page layout
27
- def wider_page():
28
- max_width_str = "max-width: 1200px;"
29
- st.markdown(
30
- f"""
31
- <style>
32
- .reportview-container .main .block-container{{ {max_width_str} }}
33
- </style>
34
- """,
35
- unsafe_allow_html=True,
36
- )
37
- logging.info("Page layout set to wider configuration.")
38
-
39
- # Customized Streamlit theme
40
- def set_custom_theme():
41
- st.markdown(
42
- """
43
- <style>
44
- body {
45
- background-color: #f0f2f6; /* Set background color */
46
- color: #333333; /* Set text color */
47
- }
48
- .sidebar .sidebar-content {
49
- background-color: #ffffff; /* Set sidebar background color */
50
- }
51
- </style>
52
- """,
53
- unsafe_allow_html=True,
54
- )
55
- logging.info("Custom theme applied to Streamlit app.")
56
-
57
- # Sidebar
58
- def sidebar_section():
59
- st.sidebar.title("Select ID Card Type")
60
- option = st.sidebar.selectbox("", ("PAN", " "))
61
- logging.info(f"ID card type selected: {option}")
62
- return option
63
-
64
- # Header
65
- def header_section(option):
66
- if option == "Aadhar":
67
- st.title("Registration Using Aadhar Card")
68
- logging.info("Header set for Aadhar Card registration.")
69
- elif option == "PAN":
70
- st.title("Registration Using PAN Card")
71
- logging.info("Header set for PAN Card registration.")
72
-
73
- # Main content
74
- def main_content(image_file, face_image_file, conn):
75
- if image_file is not None:
76
- face_image = read_image(face_image_file, is_uploaded=True)
77
- logging.info("Face image loaded.")
78
- if face_image is not None:
79
- image = read_image(image_file, is_uploaded=True)
80
- logging.info("ID card image loaded.")
81
- image_roi, _ = extract_id_card(image)
82
- logging.info("ID card ROI extracted.")
83
- face_image_path2 = detect_and_extract_face(img=image_roi)
84
- face_image_path1 = save_image(face_image, "face_image.jpg", path="data\\02_intermediate_data")
85
- logging.info("Faces extracted and saved.")
86
- is_face_verified = face_comparison(image1_path=face_image_path1, image2_path=face_image_path2)
87
- logging.info(f"Face verification status: {'successful' if is_face_verified else 'failed'}.")
88
-
89
- if is_face_verified:
90
- extracted_text = extract_text(image_roi)
91
- text_info = extract_information(extracted_text)
92
- logging.info("Text extracted and information parsed from ID card.")
93
- records = fetch_records(text_info)
94
- if records.shape[0] > 0:
95
- st.write(records.shape)
96
- st.write(records)
97
- is_duplicate = check_duplicacy(text_info)
98
- if is_duplicate:
99
- st.write(f"User already present with ID {text_info['ID']}")
100
- else:
101
- st.write(text_info)
102
- text_info['DOB'] = text_info['DOB'].strftime('%Y-%m-%d')
103
- text_info['Embedding'] = get_face_embeddings(face_image_path1)
104
- insert_records(text_info)
105
- logging.info(f"New user record inserted: {text_info['ID']}")
106
-
107
- else:
108
- st.error("Face verification failed. Please try again.")
109
-
110
- else:
111
- st.error("Face image not uploaded. Please upload a face image.")
112
- logging.error("No face image uploaded.")
113
-
114
- else:
115
- st.warning("Please upload an ID card image.")
116
- logging.warning("No ID card image uploaded.")
117
-
118
- # Main function setup as previously provided...
119
- def main():
120
- # Initialize connection.
121
- conn = st.connection('mysql', type='sql')
122
- wider_page()
123
- set_custom_theme()
124
- option = sidebar_section()
125
- header_section(option)
126
- image_file = st.file_uploader("Upload ID Card")
127
- if image_file is not None:
128
- face_image_file = st.file_uploader("Upload Face Image")
129
- main_content(image_file, face_image_file, conn)
130
-
131
- if __name__ == "__main__":
132
- main()
 
1
  import cv2
2
+ import numpy as np
 
3
  import streamlit as st
4
+ from PIL import Image
5
+
6
+ # Function to display an image using Streamlit
7
+ def show_img(img, caption=""):
8
+ st.image(img, caption=caption, use_column_width=True)
9
+
10
+ # Function to sort points for perspective transform
11
+ def sort_points(pts):
12
+ pts = pts.reshape((4, 2))
13
+ rect = np.zeros((4, 2), dtype="float32")
14
+
15
+ s = pts.sum(axis=1)
16
+ rect[0] = pts[np.argmin(s)]
17
+ rect[2] = pts[np.argmax(s)]
18
+
19
+ diff = np.diff(pts, axis=1)
20
+ rect[1] = pts[np.argmin(diff)]
21
+ rect[3] = pts[np.argmax(diff)]
22
+
23
+ return rect
24
+
25
+ # Function to find contours
26
+ def find_contours(edged):
27
+ conts, _ = cv2.findContours(edged, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)
28
+ conts = sorted(conts, key=cv2.contourArea, reverse=True)[:5]
29
+ return conts
30
+
31
+ # Function to transform the image
32
+ def transform_image(image_file):
33
+ img = cv2.imdecode(np.fromstring(image_file.read(), np.uint8), 1)
34
+ original = img.copy()
35
+ show_img(original, caption="Original Image")
36
+
37
+ (H, W) = img.shape[:2]
38
+
39
+ gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
40
+ blur = cv2.GaussianBlur(gray, (7, 7), 0)
41
+ edged = cv2.Canny(blur, 60, 160)
42
+ show_img(edged, caption="Edge Detection")
43
+
44
+ conts = find_contours(edged.copy())
45
+ for c in conts:
46
+ peri = cv2.arcLength(c, True)
47
+ aprox = cv2.approxPolyDP(c, 0.02 * peri, True)
48
+
49
+ if len(aprox) == 4:
50
+ larger = aprox
51
+ break
52
+
53
+ cv2.drawContours(img, [larger], -1, (120, 255, 0), 2)
54
+ show_img(img, caption="Detected Contours")
55
+
56
+ points_larger = sort_points(larger)
57
+ pts1 = np.float32(points_larger)
58
+ pts2 = np.float32([[0, 0], [W, 0], [W, H], [0, H]])
59
+
60
+ matrix = cv2.getPerspectiveTransform(pts1, pts2)
61
+ transform = cv2.warpPerspective(original, matrix, (W, H))
62
+
63
+ show_img(transform, caption="Transformed Image")
64
+ return transform
65
+
66
+ # Streamlit app layout
67
+ st.set_page_config(page_title="Image Scanner", page_icon="📄")
68
+
69
+ st.title("Document Scanner using Computer Vision")
70
+ st.write("Upload an image to transform it into a scanned document format.")
71
+
72
+ uploaded_file = st.file_uploader("Choose an image...", type=["jpg", "jpeg", "png"])
73
+
74
+ if uploaded_file is not None:
75
+ st.write("Original Image:")
76
+ transformed_image = transform_image(uploaded_file)
77
+ st.write("Transformed Image:")
78
+ st.image(transformed_image, caption="Scanned Image", use_column_width=True)