ssh-AI commited on
Commit
6a375fe
·
verified ·
1 Parent(s): ee85e55

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +145 -116
app.py CHANGED
@@ -1,140 +1,169 @@
1
  # app.py
2
 
3
  import streamlit as st
4
- import numpy as np
5
  import cv2
 
6
  from PIL import Image, ImageEnhance
7
- from fpdf import FPDF
8
  import io
9
- import base64
10
- import os
11
-
12
- # Function to detect and crop the document
13
- def detect_and_crop(img):
14
- gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
15
- blur = cv2.GaussianBlur(gray, (5,5), 0)
16
- edged = cv2.Canny(blur, 50, 200)
17
-
18
- contours, _ = cv2.findContours(edged.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
19
- if len(contours) == 0:
20
- return img # Return original if nothing found
21
-
22
- c = max(contours, key=cv2.contourArea)
23
- peri = cv2.arcLength(c, True)
24
- approx = cv2.approxPolyDP(c, 0.02 * peri, True)
25
-
26
- if len(approx) == 4:
27
- pts = approx.reshape(4, 2)
28
- rect = order_points(pts)
29
- (tl, tr, br, bl) = rect
30
-
31
- widthA = np.linalg.norm(br - bl)
32
- widthB = np.linalg.norm(tr - tl)
33
- maxWidth = max(int(widthA), int(widthB))
34
-
35
- heightA = np.linalg.norm(tr - br)
36
- heightB = np.linalg.norm(tl - bl)
37
- maxHeight = max(int(heightA), int(heightB))
38
-
39
- dst = np.array([
40
- [0, 0],
41
- [maxWidth - 1, 0],
42
- [maxWidth - 1, maxHeight - 1],
43
- [0, maxHeight - 1]
44
- ], dtype="float32")
45
-
46
- M = cv2.getPerspectiveTransform(rect, dst)
47
- warped = cv2.warpPerspective(img, M, (maxWidth, maxHeight))
48
-
49
- return warped
50
  else:
51
- return img
52
 
53
- # Helper to order contour points
54
- def order_points(pts):
55
  rect = np.zeros((4, 2), dtype="float32")
 
56
  s = pts.sum(axis=1)
57
- rect[0] = pts[np.argmin(s)]
58
- rect[2] = pts[np.argmax(s)]
59
 
60
  diff = np.diff(pts, axis=1)
61
- rect[1] = pts[np.argmin(diff)]
62
- rect[3] = pts[np.argmax(diff)]
63
 
64
- return rect
65
 
66
- # Enhance image lightly
67
- def enhance_image(img_pil):
68
- enhancer = ImageEnhance.Contrast(img_pil)
69
- img_pil = enhancer.enhance(1.2)
70
- enhancer = ImageEnhance.Sharpness(img_pil)
71
- img_pil = enhancer.enhance(1.3)
72
- return img_pil
73
-
74
- # Save images to a PDF
75
- def images_to_pdf(images):
76
- pdf = FPDF()
77
- for img in images:
78
- temp_path = "/tmp/temp_img.jpg"
79
- img.save(temp_path, "JPEG")
80
- width, height = img.size
81
- orientation = 'P' if height > width else 'L'
82
- pdf.add_page(orientation=orientation)
83
- pdf.image(temp_path, x=10, y=10, w=pdf.w-20)
84
- pdf_output = "/tmp/cleaned_images.pdf"
85
- pdf.output(pdf_output)
86
- return pdf_output
87
-
88
- # Encode file for download
89
- def download_link(file_path, file_label):
90
- with open(file_path, "rb") as f:
91
- base64_pdf = base64.b64encode(f.read()).decode('utf-8')
92
- href = f'<a href="data:application/octet-stream;base64,{base64_pdf}" download="{file_label}">📄 Download your scanned PDF</a>'
93
- return href
94
-
95
- # App Layout
96
- page_bg_img = '''
97
- <style>
98
- .stApp {
99
- background-image: url("https://images.unsplash.com/photo-1581090700227-1c065c769e3a");
100
- background-size: cover;
101
- background-position: top left;
102
- background-repeat: no-repeat;
103
- background-attachment: fixed;
104
- }
105
- .title {
106
- color: white;
107
- text-align: center;
108
- font-size: 40px;
109
- font-weight: bold;
110
- }
111
- </style>
112
- '''
113
 
114
- st.markdown(page_bg_img, unsafe_allow_html=True)
115
- st.markdown('<div class="title">📄 Auto ID Card / Document Scanner</div>', unsafe_allow_html=True)
 
116
 
117
- st.write("### Upload your document or ID card photos 📷")
118
- uploaded_files = st.file_uploader("Upload multiple files", accept_multiple_files=True, type=["png", "jpg", "jpeg"])
 
 
 
 
119
 
120
- if uploaded_files:
121
- cleaned_images = []
122
- for uploaded_file in uploaded_files:
123
- file_bytes = np.asarray(bytearray(uploaded_file.read()), dtype=np.uint8)
124
- img = cv2.imdecode(file_bytes, 1)
125
 
126
- cropped = detect_and_crop(img)
127
- cropped_rgb = cv2.cvtColor(cropped, cv2.COLOR_BGR2RGB)
128
- img_pil = Image.fromarray(cropped_rgb)
129
 
130
- # Optional light enhancement
131
- enhanced_img = enhance_image(img_pil)
 
 
132
 
133
- cleaned_images.append(enhanced_img)
 
134
 
135
- st.success(f"✅ Processed {len(cleaned_images)} documents successfully!")
136
 
137
- pdf_file = images_to_pdf(cleaned_images)
 
 
138
 
139
- st.markdown(download_link(pdf_file, "scanned_documents.pdf"), unsafe_allow_html=True)
 
 
140
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  # app.py
2
 
3
  import streamlit as st
 
4
  import cv2
5
+ import numpy as np
6
  from PIL import Image, ImageEnhance
 
7
  import io
8
+ from fpdf import FPDF
9
+ import datetime
10
+
11
+ # -----------------------
12
+ # Helper Functions
13
+ # -----------------------
14
+
15
+ def auto_crop_document(image):
16
+ """Auto-detect document and crop it."""
17
+ img = np.array(image)
18
+ gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
19
+ blurred = cv2.GaussianBlur(gray, (5, 5), 0)
20
+ edged = cv2.Canny(blurred, 75, 200)
21
+
22
+ contours, _ = cv2.findContours(edged.copy(), cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)
23
+ contours = sorted(contours, key=cv2.contourArea, reverse=True)[:5]
24
+
25
+ for c in contours:
26
+ peri = cv2.arcLength(c, True)
27
+ approx = cv2.approxPolyDP(c, 0.02 * peri, True)
28
+
29
+ if len(approx) == 4:
30
+ doc_cnt = approx
31
+ break
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
32
  else:
33
+ return image # Return original if no contour found
34
 
35
+ pts = doc_cnt.reshape(4, 2)
 
36
  rect = np.zeros((4, 2), dtype="float32")
37
+
38
  s = pts.sum(axis=1)
39
+ rect[0] = pts[np.argmin(s)] # Top-left
40
+ rect[2] = pts[np.argmax(s)] # Bottom-right
41
 
42
  diff = np.diff(pts, axis=1)
43
+ rect[1] = pts[np.argmin(diff)] # Top-right
44
+ rect[3] = pts[np.argmax(diff)] # Bottom-left
45
 
46
+ (tl, tr, br, bl) = rect
47
 
48
+ widthA = np.linalg.norm(br - bl)
49
+ widthB = np.linalg.norm(tr - tl)
50
+ maxWidth = max(int(widthA), int(widthB))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
51
 
52
+ heightA = np.linalg.norm(tr - br)
53
+ heightB = np.linalg.norm(tl - bl)
54
+ maxHeight = max(int(heightA), int(heightB))
55
 
56
+ dst = np.array([
57
+ [0, 0],
58
+ [maxWidth-1, 0],
59
+ [maxWidth-1, maxHeight-1],
60
+ [0, maxHeight-1]
61
+ ], dtype="float32")
62
 
63
+ M = cv2.getPerspectiveTransform(rect, dst)
64
+ warped = cv2.warpPerspective(img, M, (maxWidth, maxHeight))
 
 
 
65
 
66
+ return Image.fromarray(warped)
 
 
67
 
68
+ def enhance_image(img_pil):
69
+ """Enhance the image (brightness and contrast)."""
70
+ enhancer_brightness = ImageEnhance.Brightness(img_pil)
71
+ img_bright = enhancer_brightness.enhance(1.2)
72
 
73
+ enhancer_contrast = ImageEnhance.Contrast(img_bright)
74
+ img_contrast = enhancer_contrast.enhance(1.3)
75
 
76
+ return img_contrast
77
 
78
+ def rotate_image(img_pil, angle):
79
+ """Rotate image."""
80
+ return img_pil.rotate(angle, expand=True)
81
 
82
+ # -----------------------
83
+ # Streamlit App
84
+ # -----------------------
85
 
86
+ # Set app background and style
87
+ page_bg_img = f"""
88
+ <style>
89
+ .stApp {{
90
+ background-image: url("https://images.unsplash.com/photo-1581090700227-1c065c585ab3?ixlib=rb-4.0.3&auto=format&fit=crop&w=1470&q=80");
91
+ background-size: cover;
92
+ background-position: center;
93
+ }}
94
+ h1, h2, h3, h4, h5 {{
95
+ color: white;
96
+ }}
97
+ </style>
98
+ """
99
+ st.markdown(page_bg_img, unsafe_allow_html=True)
100
+
101
+ # App Title
102
+ st.title("📄 Smart Document Scanner App")
103
+
104
+ st.write("Upload your **ID cards or documents**. We'll detect, crop, enhance and generate a clean PDF!")
105
+
106
+ uploaded_files = st.file_uploader(
107
+ "Upload Images (JPG, JPEG, PNG supported)",
108
+ type=["jpg", "jpeg", "png"],
109
+ accept_multiple_files=True
110
+ )
111
+
112
+ if uploaded_files:
113
+ final_images = []
114
+
115
+ for file in uploaded_files:
116
+ image = Image.open(file)
117
+ st.subheader(f"Original Uploaded Image: {file.name}")
118
+ st.image(image, caption="Original Image", use_column_width=True)
119
+
120
+ # Auto crop
121
+ cropped_img = auto_crop_document(image)
122
+ st.image(cropped_img, caption="Auto Cropped", use_column_width=True)
123
+
124
+ # Rotate option
125
+ rotate_angle = st.selectbox(f"Rotate {file.name}?", [0, 90, 180, 270], key=f"rotate_{file.name}")
126
+ if rotate_angle != 0:
127
+ cropped_img = rotate_image(cropped_img, rotate_angle)
128
+ st.image(cropped_img, caption=f"Rotated by {rotate_angle}°", use_column_width=True)
129
+
130
+ # Enhance option
131
+ if st.button(f"Enhance {file.name}", key=f"enhance_{file.name}"):
132
+ enhanced_img = enhance_image(cropped_img)
133
+ st.image(enhanced_img, caption="Enhanced Image (After)", use_column_width=True)
134
+ final_images.append(enhanced_img)
135
+ else:
136
+ final_images.append(cropped_img)
137
+
138
+ # Generate PDF
139
+ if st.button("📥 Generate PDF"):
140
+ pdf = FPDF()
141
+ pdf.set_auto_page_break(0)
142
+
143
+ for img in final_images:
144
+ img_temp = io.BytesIO()
145
+ img.save(img_temp, format='JPEG')
146
+ img_temp.seek(0)
147
+
148
+ cover = Image.open(img_temp)
149
+ width, height = cover.size
150
+
151
+ # Convert pixel in mm (1px = 0.264583 mm)
152
+ width, height = float(width * 0.264583), float(height * 0.264583)
153
+
154
+ pdf.add_page()
155
+ pdf.image(img_temp, 0, 0, width, height)
156
+
157
+ pdf_output = io.BytesIO()
158
+ pdf.output(pdf_output)
159
+ pdf_output.seek(0)
160
+
161
+ timestamp = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
162
+ filename = f"scanned_document_{timestamp}.pdf"
163
+
164
+ st.download_button(
165
+ label="📄 Download Your PDF",
166
+ data=pdf_output,
167
+ file_name=filename,
168
+ mime="application/pdf"
169
+ )