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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
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'.")