Spaces:
Sleeping

Digitalytics / src /services /file_parser_service.py
faseehsandhu's picture
codebase
31b5ed7
Raw History Blame Contribute Delete
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."""
@staticmethod
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)}")
@staticmethod
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)}")
@staticmethod
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}")