Spaces:
Runtime error

dataentryai / src /streamlit_app.py
Selva1103's picture
Update src/streamlit_app.py
354caf1 verified
Raw History Blame Contribute Delete
13.2 kB
import streamlit as st
import pandas as pd
import pytesseract
import cv2
import numpy as np
import re
from PIL import Image
# ---------------------------------------------------
# IMPORTANT FOR WINDOWS:
# Uncomment and update this path if Tesseract is installed here
# ---------------------------------------------------
# pytesseract.pytesseract.tesseract_cmd = r"C:\Program Files\Tesseract-OCR\tesseract.exe"
# ---------------------------------------------------
# Streamlit page config
# ---------------------------------------------------
st.set_page_config(
page_title="Visiting Card to CSV",
page_icon="πŸ“‡",
layout="centered"
)
st.title("πŸ“‡ Visiting Card β†’ CSV")
st.caption("Capture or upload visiting cards from your phone, extract contact details, and download CSV.")
# ---------------------------------------------------
# Session state
# ---------------------------------------------------
if "records" not in st.session_state:
st.session_state.records = []
if "current_data" not in st.session_state:
st.session_state.current_data = {
"full_name": "",
"role": "",
"company_name": "",
"email": "",
"phone": "",
"website": "",
"address": "",
"source_file": ""
}
if "ocr_text" not in st.session_state:
st.session_state.ocr_text = ""
# ---------------------------------------------------
# Helper functions
# ---------------------------------------------------
def preprocess_image(pil_image):
"""
Preprocess uploaded image for better OCR:
- Convert PIL to OpenCV
- Resize if too large/small
- Grayscale
- Sharpen
- Threshold
"""
img = np.array(pil_image)
img = cv2.cvtColor(img, cv2.COLOR_RGB2BGR)
h, w = img.shape[:2]
# Resize for better OCR
target_width = 1400
if w < target_width:
scale = target_width / w
img = cv2.resize(img, (int(w * scale), int(h * scale)), interpolation=cv2.INTER_CUBIC)
elif w > 2200:
scale = 2200 / w
img = cv2.resize(img, (int(w * scale), int(h * scale)), interpolation=cv2.INTER_AREA)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# Slight blur to reduce noise
gray = cv2.GaussianBlur(gray, (3, 3), 0)
# Sharpen
kernel = np.array([[0, -1, 0],
[-1, 5, -1],
[0, -1, 0]])
sharp = cv2.filter2D(gray, -1, kernel)
# Adaptive threshold for card text
processed = cv2.adaptiveThreshold(
sharp,
255,
cv2.ADAPTIVE_THRESH_GAUSSIAN_C,
cv2.THRESH_BINARY,
31,
11
)
return processed
def extract_text_from_image(processed_img):
"""
OCR using Tesseract
"""
config = r'--oem 3 --psm 6'
text = pytesseract.image_to_string(processed_img, config=config)
return text
def clean_email(email):
return email.strip().lower() if email else ""
def clean_phone(phone):
if not phone:
return ""
# Keep digits and plus only
phone = re.sub(r"[^\d+]", "", phone)
digits_only = re.sub(r"\D", "", phone)
# Indian 10-digit mobile
if len(digits_only) == 10:
return "+91" + digits_only
# Already includes 91 but no +
if len(digits_only) == 12 and digits_only.startswith("91"):
return "+" + digits_only
# Keep original cleaned if something else
return phone
def clean_website(website):
if not website:
return ""
website = website.strip()
if website and not website.startswith(("http://", "https://")):
website = "https://" + website
return website
def is_role_line(line):
role_keywords = [
"manager", "director", "ceo", "cto", "cfo", "coo", "founder",
"partner", "proprietor", "owner", "executive", "officer", "lead",
"head", "engineer", "developer", "consultant", "specialist",
"sales", "marketing", "business", "hr", "accounts", "finance",
"admin", "operations", "purchase", "procurement", "advisor",
"president", "chairman", "analyst", "associate"
]
line_lower = line.lower()
return any(keyword in line_lower for keyword in role_keywords)
def looks_like_company(line):
company_keywords = [
"pvt", "private", "ltd", "limited", "llp", "inc", "corp",
"corporation", "technologies", "solutions", "systems", "industries",
"enterprises", "group", "company", "co.", "agency", "services"
]
line_lower = line.lower()
return any(keyword in line_lower for keyword in company_keywords)
def extract_fields_from_text(text):
"""
Rule-based extraction from OCR text
"""
lines = [line.strip() for line in text.splitlines() if line.strip()]
joined_text = " ".join(lines)
# -------------------------
# Email
# -------------------------
email_match = re.search(r"[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}", joined_text)
email = clean_email(email_match.group(0)) if email_match else ""
# -------------------------
# Phone
# -------------------------
phone_candidates = re.findall(r"(?:\+?\d[\d\s\-\(\)]{8,}\d)", joined_text)
phone = clean_phone(phone_candidates[0]) if phone_candidates else ""
# -------------------------
# Website
# -------------------------
website_match = re.search(
r"(?:(?:https?://)?(?:www\.)?[A-Za-z0-9.-]+\.[A-Za-z]{2,}(?:/[^\s]*)?)",
joined_text
)
website = ""
if website_match:
candidate = website_match.group(0)
# Avoid using email domain as website if possible
if "@" not in candidate and not re.match(r"^\+?\d+$", candidate):
website = clean_website(candidate)
# -------------------------
# Name / Role / Company
# -------------------------
full_name = ""
role = ""
company_name = ""
# Clean obvious contact lines
filtered_lines = []
for line in lines:
lower = line.lower()
if (
"@" in line
or re.search(r"\+?\d", line)
or lower.startswith(("m:", "mob:", "mobile:", "t:", "tel:", "ph:", "phone:"))
or lower.startswith(("e:", "email:"))
or lower.startswith(("w:", "web:", "website:"))
):
continue
filtered_lines.append(line)
# Guess company
for line in filtered_lines:
if looks_like_company(line):
company_name = line
break
# Guess role
for line in filtered_lines:
if is_role_line(line):
role = line
break
# Guess full name
for line in filtered_lines[:5]:
# Skip if looks like company or role
if line == company_name or line == role:
continue
# Basic name-like pattern: 2-4 words, mostly alphabetic
words = line.split()
if 2 <= len(words) <= 4:
alpha_ratio = sum(1 for ch in line if ch.isalpha()) / max(len(line), 1)
if alpha_ratio > 0.65:
full_name = line
break
# Fallbacks
if not full_name and len(filtered_lines) > 0:
full_name = filtered_lines[0]
if not role and len(filtered_lines) > 1:
role = filtered_lines[1]
if not company_name and len(filtered_lines) > 2:
company_name = filtered_lines[2]
# -------------------------
# Address
# -------------------------
address_parts = []
for line in filtered_lines:
if line in [full_name, role, company_name]:
continue
lower = line.lower()
if any(x in lower for x in ["road", "rd", "street", "st", "nagar", "city", "district", "state", "india", "pin", "zip"]):
address_parts.append(line)
elif re.search(r"\d{5,6}", line):
address_parts.append(line)
elif len(line.split()) >= 4:
address_parts.append(line)
address = ", ".join(address_parts[:4])
return {
"full_name": full_name,
"role": role,
"company_name": company_name,
"email": email,
"phone": phone,
"website": website,
"address": address
}
def process_uploaded_card(uploaded_file):
"""
Full pipeline:
PIL image -> preprocess -> OCR -> field extraction
"""
image = Image.open(uploaded_file).convert("RGB")
processed = preprocess_image(image)
ocr_text = extract_text_from_image(processed)
extracted = extract_fields_from_text(ocr_text)
extracted["source_file"] = uploaded_file.name
return image, processed, ocr_text, extracted
def reset_current_form():
st.session_state.current_data = {
"full_name": "",
"role": "",
"company_name": "",
"email": "",
"phone": "",
"website": "",
"address": "",
"source_file": ""
}
st.session_state.ocr_text = ""
# ---------------------------------------------------
# Instructions
# ---------------------------------------------------
with st.expander("πŸ“Έ Tips for better results", expanded=False):
st.markdown("""
**Best results from phone:**
- Keep the card flat
- Fill most of the frame
- Use good lighting
- Avoid shadows and reflections
- Do not tilt too much
- Keep text clear and sharp
""")
# ---------------------------------------------------
# Upload section
# ---------------------------------------------------
st.subheader("1) Upload Visiting Card")
uploaded_file = st.file_uploader(
"Take or upload one visiting card",
type=["png", "jpg", "jpeg", "webp"]
)
if uploaded_file is not None:
st.image(uploaded_file, caption="Uploaded Card", use_container_width=True)
if st.button("⚑ Extract Details", use_container_width=True):
try:
with st.spinner("Reading card..."):
original_img, processed_img, ocr_text, extracted = process_uploaded_card(uploaded_file)
st.session_state.current_data = extracted
st.session_state.ocr_text = ocr_text
st.success("Card processed successfully.")
except Exception as e:
st.error(f"Error while processing card: {e}")
# ---------------------------------------------------
# Editable extracted form
# ---------------------------------------------------
st.subheader("2) Review & Edit")
with st.form("card_form"):
full_name = st.text_input("Full Name", value=st.session_state.current_data["full_name"])
role = st.text_input("Role / Designation", value=st.session_state.current_data["role"])
company_name = st.text_input("Company Name", value=st.session_state.current_data["company_name"])
email = st.text_input("Email", value=st.session_state.current_data["email"])
phone = st.text_input("Phone", value=st.session_state.current_data["phone"])
website = st.text_input("Website", value=st.session_state.current_data["website"])
address = st.text_area("Address", value=st.session_state.current_data["address"], height=100)
col1, col2 = st.columns(2)
with col1:
add_record = st.form_submit_button("βž• Add to CSV", use_container_width=True)
with col2:
clear_form = st.form_submit_button("🧹 Clear Form", use_container_width=True)
if add_record:
record = {
"full_name": full_name.strip(),
"role": role.strip(),
"company_name": company_name.strip(),
"email": clean_email(email),
"phone": clean_phone(phone),
"website": clean_website(website),
"address": address.strip(),
"source_file": st.session_state.current_data.get("source_file", "")
}
# Avoid adding completely empty rows
if any(record[k] for k in ["full_name", "role", "company_name", "email", "phone", "website", "address"]):
st.session_state.records.append(record)
st.success("Added to CSV list.")
reset_current_form()
st.rerun()
else:
st.warning("No usable data to add.")
if clear_form:
reset_current_form()
st.rerun()
# ---------------------------------------------------
# OCR text section
# ---------------------------------------------------
if st.session_state.ocr_text:
with st.expander("πŸ“ Show OCR Text", expanded=False):
st.code(st.session_state.ocr_text)
# ---------------------------------------------------
# Records table
# ---------------------------------------------------
st.subheader("3) Added Contacts")
if st.session_state.records:
df = pd.DataFrame(st.session_state.records)
edited_df = st.data_editor(
df,
use_container_width=True,
num_rows="dynamic",
key="records_editor"
)
csv_data = edited_df.to_csv(index=False).encode("utf-8")
col1, col2 = st.columns(2)
with col1:
st.download_button(
label="⬇ Download CSV",
data=csv_data,
file_name="visiting_cards.csv",
mime="text/csv",
use_container_width=True
)
with col2:
if st.button("πŸ—‘ Clear All Records", use_container_width=True):
st.session_state.records = []
st.rerun()
else:
st.info("No contacts added yet. Upload a card and click 'Add to CSV'.")