Spaces:
Sleeping
Sleeping
| import os | |
| import re | |
| import tempfile | |
| import pandas as pd | |
| import fitz # PyMuPDF | |
| from docx import Document | |
| from fastapi import UploadFile | |
| def extract_phone_numbers(text: str) -> list: | |
| phone_pattern = re.compile(r'\b\d{10}\b') | |
| matches = phone_pattern.findall(text) | |
| return [f'+91{number}' for number in matches] | |
| def extract_text_from_pdf(file_path: str) -> str: | |
| doc = fitz.open(file_path) | |
| text = "" | |
| for page in doc: | |
| text += page.get_text() | |
| return text | |
| def extract_text_from_docx(file_path: str) -> str: | |
| doc = Document(file_path) | |
| return "\n".join([para.text for para in doc.paragraphs]) | |
| def extract_text_from_file(file: UploadFile) -> str: | |
| suffix = os.path.splitext(file.filename)[-1].lower() | |
| print("File suffix:", suffix) | |
| with tempfile.NamedTemporaryFile(delete=False, suffix=suffix) as tmp: | |
| tmp.write(file.file.read()) | |
| tmp_path = tmp.name | |
| try: | |
| if suffix == ".pdf": | |
| return extract_text_from_pdf(tmp_path) | |
| elif suffix == ".docx": | |
| return extract_text_from_docx(tmp_path) | |
| elif suffix in [".txt"]: | |
| with open(tmp_path, "r", encoding="utf-8") as f: | |
| return f.read() | |
| elif suffix == ".csv": | |
| df = pd.read_csv(tmp_path) | |
| return " ".join(df.astype(str).values.flatten()) | |
| elif suffix in [".xlsx", ".xls"]: | |
| df = pd.read_excel(tmp_path) | |
| return " ".join(df.astype(str).values.flatten()) | |
| else: | |
| print("Unsupported file type, fallback to manual read") | |
| return file.file.read().decode("utf-8", errors="ignore") | |
| except Exception as e: | |
| print("Error while parsing file:", e) | |
| return "" | |