Spaces:
Sleeping
Sleeping
Download src/services/file_parser_service.py from faseehsandhu/Digitalytics: direct link, hf CLI and curl.
- Browser
- Download file 2.02 kB
-
https://huggingface.co/spaces/faseehsandhu/Digitalytics/resolve/main/src/services/file_parser_service.py
- Command line
-
hf download hf://spaces/faseehsandhu/Digitalytics/src/services/file_parser_service.py
-
curl -L -o file_parser_service.py https://huggingface.co/spaces/faseehsandhu/Digitalytics/resolve/main/src/services/file_parser_service.py
2.02 kB
| """ | |
| File Parser Service for Streamlit Data Dictionary Chatbot | |
| This service handles the parsing of uploaded files, extracting relevant information | |
| from various formats (e.g., PDF, Excel) to be used in the application. | |
| """ | |
| import os | |
| import pandas as pd | |
| import PyPDF2 | |
| from typing import Union, Dict, Any | |
| class FileParserService: | |
| """Service for parsing uploaded data dictionary files.""" | |
| def extract_text_from_pdf(pdf_path: str) -> str: | |
| """Extract text content from a PDF file.""" | |
| text = "" | |
| try: | |
| with open(pdf_path, 'rb') as file: | |
| pdf_reader = PyPDF2.PdfReader(file) | |
| for page in pdf_reader.pages: | |
| text += page.extract_text() + "\n" | |
| return text | |
| except Exception as e: | |
| raise ValueError(f"Error reading PDF {pdf_path}: {str(e)}") | |
| def extract_data_from_excel(excel_path: str) -> Dict[str, Any]: | |
| """Extract data from an Excel file and return as a dictionary.""" | |
| data = {} | |
| try: | |
| excel_file = pd.ExcelFile(excel_path) | |
| for sheet_name in excel_file.sheet_names: | |
| df = pd.read_excel(excel_path, sheet_name=sheet_name) | |
| data[sheet_name] = df.to_dict(orient='records') | |
| return data | |
| except Exception as e: | |
| raise ValueError(f"Error reading Excel {excel_path}: {str(e)}") | |
| def parse_file(file_path: str) -> Union[str, Dict[str, Any]]: | |
| """Parse the uploaded file based on its extension.""" | |
| _, file_extension = os.path.splitext(file_path) | |
| file_extension = file_extension.lower() | |
| if file_extension == '.pdf': | |
| return FileParserService.extract_text_from_pdf(file_path) | |
| elif file_extension in ['.xlsx', '.xls']: | |
| return FileParserService.extract_data_from_excel(file_path) | |
| else: | |
| raise ValueError(f"Unsupported file format: {file_extension}") |