Lazabriellholland commited on
Commit
7b0104d
·
verified ·
1 Parent(s): 31e87eb

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +126 -0
app.py ADDED
@@ -0,0 +1,126 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os, io, re, json
2
+ import streamlit as st
3
+ from PIL import Image
4
+
5
+ import pdfplumber # text layer for PDFs
6
+ from pdf2image import convert_from_bytes # render image-only PDFs
7
+ import pytesseract # OCR
8
+
9
+ APP_TITLE = "Flyer → Image-to-Text (Where & When)"
10
+ st.set_page_config(page_title=APP_TITLE, page_icon="📰", layout="centered")
11
+ st.title("📰 Flyer → Where & When")
12
+ st.caption("Upload a flyer (PDF/JPG/PNG). I’ll read it and pull out the date, time, and location.")
13
+
14
+ # ----------- helpers -----------
15
+
16
+ DATE_PAT = r"(\b\w{3,9}\b\s+\d{1,2}(?:,\s*\d{4})?)|\b\d{1,2}/\d{1,2}/\d{2,4}\b"
17
+ TIME_PAT = r"\b(\d{1,2}:\d{2}\s*[AP]M|\d{1,2}\s*[AP]M)\b"
18
+ LOC_HINTS = r"(Location|Where|Address|Venue|At)[:\-\s]+(.+)"
19
+
20
+ def pdf_bytes_to_text(pdf_bytes: bytes) -> str:
21
+ # Try selectable text first
22
+ parts = []
23
+ try:
24
+ with pdfplumber.open(io.BytesIO(pdf_bytes)) as pdf:
25
+ for page in pdf.pages:
26
+ t = page.extract_text() or ""
27
+ if t.strip():
28
+ parts.append(t)
29
+ except Exception:
30
+ pass
31
+ if parts:
32
+ return "\n\n".join(parts)
33
+
34
+ # Fallback to OCR (image-only PDFs)
35
+ txts = []
36
+ images = convert_from_bytes(pdf_bytes, fmt="png", dpi=200)
37
+ for img in images:
38
+ txts.append(pytesseract.image_to_string(img))
39
+ return "\n".join(txts)
40
+
41
+ def image_bytes_to_text(img_bytes: bytes) -> str:
42
+ img = Image.open(io.BytesIO(img_bytes)).convert("RGB")
43
+ return pytesseract.image_to_string(img)
44
+
45
+ def extract_where_when(text: str):
46
+ # Date(s)
47
+ dates = re.findall(DATE_PAT, text, flags=re.I)
48
+ # re.findall returns tuples from the alternation; flatten/clean:
49
+ clean_dates = []
50
+ for tup in dates:
51
+ s = [t for t in tup if t]
52
+ if s: clean_dates.append(s[0])
53
+
54
+ # Time(s)
55
+ times = re.findall(TIME_PAT, text, flags=re.I)
56
+
57
+ # Location (first good hint line)
58
+ loc_match = re.search(LOC_HINTS, text, flags=re.I)
59
+ location = loc_match.group(2).strip() if loc_match else ""
60
+
61
+ return {
62
+ "dates_found": clean_dates,
63
+ "times_found": times,
64
+ "location": location
65
+ }
66
+
67
+ # ----------- UI -----------
68
+
69
+ uploaded = st.file_uploader("Upload flyer", type=["pdf", "png", "jpg", "jpeg"])
70
+
71
+ manual_text = st.text_area(
72
+ "Or paste text manually (optional)",
73
+ height=160,
74
+ placeholder="If OCR struggles, paste the flyer words here…"
75
+ )
76
+
77
+ if st.button("Read flyer"):
78
+ if not uploaded and not manual_text.strip():
79
+ st.warning("Please upload a file or paste some text.")
80
+ st.stop()
81
+
82
+ raw_text = ""
83
+ if uploaded:
84
+ if uploaded.type == "application/pdf":
85
+ raw_text = pdf_bytes_to_text(uploaded.read())
86
+ else:
87
+ raw_text = image_bytes_to_text(uploaded.read())
88
+
89
+ # If user pasted text, prefer that (it may be cleaner than OCR)
90
+ combined_text = manual_text.strip() or raw_text
91
+
92
+ if not combined_text.strip():
93
+ st.error("I couldn’t read any text. Try exporting your Canva flyer as a higher-resolution PNG or a text-based PDF.")
94
+ st.stop()
95
+
96
+ results = extract_where_when(combined_text)
97
+
98
+ st.success("Done! Here’s what I found:")
99
+ col1, col2 = st.columns(2)
100
+ with col1:
101
+ st.markdown("**Date(s) detected:**")
102
+ if results["dates_found"]:
103
+ st.write(", ".join(results["dates_found"]))
104
+ else:
105
+ st.write("—")
106
+
107
+ st.markdown("**Time(s) detected:**")
108
+ if results["times_found"]:
109
+ st.write(", ".join(results["times_found"]))
110
+ else:
111
+ st.write("—")
112
+
113
+ with col2:
114
+ st.markdown("**Location detected:**")
115
+ st.write(results["location"] or "—")
116
+
117
+ st.markdown("---")
118
+ st.markdown("**All extracted text (for reference):**")
119
+ st.code(combined_text[:3000]) # avoid huge pastes
120
+
121
+ st.download_button(
122
+ "Download JSON",
123
+ data=json.dumps(results, indent=2),
124
+ file_name="where_when.json",
125
+ mime="application/json"
126
+ )