Spaces:
Runtime error
Runtime error
Update app.py
Browse files
app.py
CHANGED
@@ -8,68 +8,22 @@ import uuid
|
|
8 |
import os
|
9 |
|
10 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
11 |
-
# 1.
|
12 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
13 |
-
def
|
14 |
"""
|
15 |
-
|
16 |
-
Returns a list of bounding boxes: (x, y, w, h).
|
17 |
-
"""
|
18 |
-
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
|
19 |
-
blurred = cv2.GaussianBlur(gray, (5, 5), 0)
|
20 |
-
edges = cv2.Canny(blurred, 50, 150)
|
21 |
-
|
22 |
-
# Dilate + erode to close gaps
|
23 |
-
kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (5, 5))
|
24 |
-
closed = cv2.morphologyEx(edges, cv2.MORPH_CLOSE, kernel)
|
25 |
-
|
26 |
-
contours, _ = cv2.findContours(
|
27 |
-
closed.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE
|
28 |
-
)
|
29 |
-
boxes = []
|
30 |
-
|
31 |
-
for cnt in contours:
|
32 |
-
area = cv2.contourArea(cnt)
|
33 |
-
if area < min_area:
|
34 |
-
continue
|
35 |
-
|
36 |
-
peri = cv2.arcLength(cnt, True)
|
37 |
-
approx = cv2.approxPolyDP(cnt, eps_coef * peri, True)
|
38 |
-
|
39 |
-
# Keep only quadrilaterals
|
40 |
-
if len(approx) == 4:
|
41 |
-
x, y, w, h = cv2.boundingRect(approx)
|
42 |
-
ar = w / float(h)
|
43 |
-
# Filter by typical book-cover aspect ratios
|
44 |
-
if 0.4 < ar < 0.9 or 1.0 < ar < 1.6:
|
45 |
-
boxes.append((x, y, w, h))
|
46 |
-
|
47 |
-
# Sort leftβright, topβbottom
|
48 |
-
boxes = sorted(boxes, key=lambda b: (b[1], b[0]))
|
49 |
-
return boxes
|
50 |
-
|
51 |
-
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
52 |
-
# 2. OCR on a cropped region
|
53 |
-
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
54 |
-
def ocr_on_region(image: np.ndarray, box: tuple):
|
55 |
-
"""
|
56 |
-
Crop the image to the given box and run Tesseract OCR.
|
57 |
Return the raw OCR text.
|
58 |
"""
|
59 |
-
|
60 |
-
|
61 |
-
|
62 |
-
_, thresh_crop = cv2.threshold(
|
63 |
-
gray_crop, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU
|
64 |
-
)
|
65 |
-
custom_config = r"--oem 3 --psm 6"
|
66 |
-
text = pytesseract.image_to_string(thresh_crop, config=custom_config)
|
67 |
return text.strip()
|
68 |
|
69 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
70 |
-
#
|
71 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
72 |
-
def query_openlibrary(title_text: str, author_text: str = None):
|
73 |
"""
|
74 |
Search OpenLibrary by title (and optional author).
|
75 |
Return a dict with title, author_name, publisher, first_publish_year, or None.
|
@@ -97,23 +51,24 @@ def query_openlibrary(title_text: str, author_text: str = None):
|
|
97 |
return None
|
98 |
|
99 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
100 |
-
#
|
101 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
102 |
def process_image(image_file):
|
103 |
"""
|
104 |
-
Gradio passes a PIL image or numpy array. Convert to OpenCV BGR,
|
105 |
-
|
|
|
106 |
"""
|
107 |
-
|
108 |
-
|
109 |
-
records = []
|
110 |
|
111 |
-
|
112 |
-
|
113 |
-
|
114 |
-
if not lines:
|
115 |
-
continue
|
116 |
|
|
|
|
|
|
|
117 |
title_guess = lines[0]
|
118 |
author_guess = lines[1] if len(lines) > 1 else None
|
119 |
meta = query_openlibrary(title_guess, author_guess)
|
@@ -121,20 +76,19 @@ def process_image(image_file):
|
|
121 |
if meta:
|
122 |
records.append(meta)
|
123 |
else:
|
124 |
-
|
125 |
-
|
126 |
-
|
127 |
-
|
128 |
-
|
129 |
-
|
130 |
-
|
131 |
-
)
|
132 |
|
133 |
# Build DataFrame (even if empty)
|
134 |
df = pd.DataFrame(records, columns=["title", "author_name", "publisher", "first_publish_year"])
|
135 |
csv_bytes = df.to_csv(index=False).encode()
|
136 |
|
137 |
-
# Write to a unique temporary file
|
138 |
unique_name = f"books_{uuid.uuid4().hex}.csv"
|
139 |
temp_path = os.path.join("/tmp", unique_name)
|
140 |
with open(temp_path, "wb") as f:
|
@@ -143,26 +97,34 @@ def process_image(image_file):
|
|
143 |
return df, temp_path
|
144 |
|
145 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
146 |
-
#
|
147 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
148 |
def build_interface():
|
149 |
-
with gr.Blocks(title="Book Cover
|
150 |
gr.Markdown(
|
151 |
"""
|
152 |
-
## Book Cover
|
153 |
-
|
154 |
-
|
155 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
156 |
"""
|
157 |
)
|
158 |
|
159 |
with gr.Row():
|
160 |
-
img_in = gr.Image(type="pil", label="Upload
|
161 |
run_button = gr.Button("Scan & Lookup")
|
162 |
|
163 |
output_table = gr.Dataframe(
|
164 |
headers=["title", "author_name", "publisher", "first_publish_year"],
|
165 |
-
label="Detected
|
166 |
datatype="pandas",
|
167 |
)
|
168 |
download_file = gr.File(label="Download CSV")
|
|
|
8 |
import os
|
9 |
|
10 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
11 |
+
# 1. OCR on the full image (always)
|
12 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
13 |
+
def ocr_full_image(image: np.ndarray) -> str:
|
14 |
"""
|
15 |
+
Run Tesseract OCR on the entire image (no thresholding).
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
16 |
Return the raw OCR text.
|
17 |
"""
|
18 |
+
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
|
19 |
+
# Note: weβre NOT thresholding hereβsometimes stylized covers lose detail under THRESH_OTSU.
|
20 |
+
text = pytesseract.image_to_string(gray, config="--oem 3 --psm 6")
|
|
|
|
|
|
|
|
|
|
|
21 |
return text.strip()
|
22 |
|
23 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
24 |
+
# 2. Query OpenLibrary API
|
25 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
26 |
+
def query_openlibrary(title_text: str, author_text: str = None) -> dict | None:
|
27 |
"""
|
28 |
Search OpenLibrary by title (and optional author).
|
29 |
Return a dict with title, author_name, publisher, first_publish_year, or None.
|
|
|
51 |
return None
|
52 |
|
53 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
54 |
+
# 3. Process one uploaded image (single OCR pass)
|
55 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
56 |
def process_image(image_file):
|
57 |
"""
|
58 |
+
Gradio passes a PIL image or numpy array. Convert to OpenCV BGR,
|
59 |
+
OCR the entire image, parse first two lines for title/author,
|
60 |
+
query OpenLibrary once, and return a DataFrame + CSV file path.
|
61 |
"""
|
62 |
+
# Convert PIL to OpenCV BGR
|
63 |
+
img = np.array(image_file)[:, :, ::-1].copy()
|
|
|
64 |
|
65 |
+
# 1) Run OCR on full image
|
66 |
+
full_text = ocr_full_image(img)
|
67 |
+
lines = [line.strip() for line in full_text.splitlines() if line.strip()]
|
|
|
|
|
68 |
|
69 |
+
records = []
|
70 |
+
if lines:
|
71 |
+
# Use first line as title, second (if exists) as author
|
72 |
title_guess = lines[0]
|
73 |
author_guess = lines[1] if len(lines) > 1 else None
|
74 |
meta = query_openlibrary(title_guess, author_guess)
|
|
|
76 |
if meta:
|
77 |
records.append(meta)
|
78 |
else:
|
79 |
+
# No match β still include OCR guesses
|
80 |
+
records.append({
|
81 |
+
"title": title_guess,
|
82 |
+
"author_name": author_guess or "",
|
83 |
+
"publisher": "",
|
84 |
+
"first_publish_year": "",
|
85 |
+
})
|
|
|
86 |
|
87 |
# Build DataFrame (even if empty)
|
88 |
df = pd.DataFrame(records, columns=["title", "author_name", "publisher", "first_publish_year"])
|
89 |
csv_bytes = df.to_csv(index=False).encode()
|
90 |
|
91 |
+
# Write CSV to a unique temporary file
|
92 |
unique_name = f"books_{uuid.uuid4().hex}.csv"
|
93 |
temp_path = os.path.join("/tmp", unique_name)
|
94 |
with open(temp_path, "wb") as f:
|
|
|
97 |
return df, temp_path
|
98 |
|
99 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
100 |
+
# 4. Build the Gradio Interface
|
101 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
102 |
def build_interface():
|
103 |
+
with gr.Blocks(title="Book Cover OCR + Lookup (SingleβCover Mode)") as demo:
|
104 |
gr.Markdown(
|
105 |
"""
|
106 |
+
## Book Cover OCR + OpenLibrary Lookup
|
107 |
+
|
108 |
+
1. Upload a photo of a single book cover (or any coverβstyle image).
|
109 |
+
2. The app will run OCR on the full image, take:
|
110 |
+
- the **first line** as a βtitleβ guess, and
|
111 |
+
- the **second line** (if any) as an βauthorβ guess, then
|
112 |
+
- query OpenLibrary once for metadata.
|
113 |
+
3. Youβll see the result in a table and can download a CSV.
|
114 |
+
|
115 |
+
> **Note:**
|
116 |
+
> β’ Because we skip rectangle detection, any visible text on your cover (large, legible fonts) should be picked up.
|
117 |
+
> β’ If you have multiple covers in one photo, only the first βtitle/authorβ will be used.
|
118 |
"""
|
119 |
)
|
120 |
|
121 |
with gr.Row():
|
122 |
+
img_in = gr.Image(type="pil", label="Upload Single Book Cover")
|
123 |
run_button = gr.Button("Scan & Lookup")
|
124 |
|
125 |
output_table = gr.Dataframe(
|
126 |
headers=["title", "author_name", "publisher", "first_publish_year"],
|
127 |
+
label="Detected Book Metadata",
|
128 |
datatype="pandas",
|
129 |
)
|
130 |
download_file = gr.File(label="Download CSV")
|