Spaces:
Sleeping
Sleeping
Download src/services/data_dictionary_service.py from faseehsandhu/Digitalytics: direct link, hf CLI and curl.
- Browser
- Download file 13.3 kB
-
https://huggingface.co/spaces/faseehsandhu/Digitalytics/resolve/main/src/services/data_dictionary_service.py
- Command line
-
hf download hf://spaces/faseehsandhu/Digitalytics/src/services/data_dictionary_service.py
-
curl -L -o data_dictionary_service.py https://huggingface.co/spaces/faseehsandhu/Digitalytics/resolve/main/src/services/data_dictionary_service.py
13.3 kB
| """ | |
| data_dictionary_service.py | |
| This file manages the loading and processing of both default and user-uploaded data dictionaries, | |
| providing methods to retrieve and analyze the data. | |
| """ | |
| import os | |
| import json | |
| from pathlib import Path | |
| import pandas as pd | |
| import PyPDF2 | |
| class DataDictionaryService: | |
| """Service for managing data dictionaries.""" | |
| def __init__(self, default_dict_path: str = "data/default_dictionaries", user_upload_path: str = "data/user_uploads"): | |
| """ | |
| Initialize the DataDictionaryService with paths for default and user-uploaded dictionaries. | |
| Args: | |
| default_dict_path: Path to the default data dictionaries directory. | |
| user_upload_path: Path to the user-uploaded data dictionaries directory. | |
| """ | |
| self.default_dict_path = Path(default_dict_path) | |
| self.user_upload_path = Path(user_upload_path) | |
| self.data_dictionaries = {} | |
| self.active_status = {} # Track which dictionaries are active | |
| # Create directories if they don't exist | |
| self.default_dict_path.mkdir(parents=True, exist_ok=True) | |
| self.user_upload_path.mkdir(parents=True, exist_ok=True) | |
| # Load dictionaries on initialization | |
| self.load_all_dictionaries() | |
| def load_all_dictionaries(self): | |
| """Load both default and user dictionaries.""" | |
| self.load_default_dictionaries() | |
| self.load_user_dictionaries() | |
| def get_all_dictionaries(self): | |
| """ | |
| Get information about all available dictionaries. | |
| Returns: | |
| List of dictionaries with information about each data dictionary | |
| """ | |
| all_dicts = [] | |
| # Add default dictionaries | |
| for name, content in self.data_dictionaries.items(): | |
| dict_info = { | |
| 'name': name, | |
| 'type': 'default' if Path(name).parent == self.default_dict_path else 'user', | |
| 'active': self.active_status.get(name, True), | |
| 'size': len(content) if content else 0 | |
| } | |
| all_dicts.append(dict_info) | |
| return all_dicts | |
| def set_dictionary_active(self, dict_name: str, active: bool): | |
| """ | |
| Set whether a dictionary is active or not. | |
| Args: | |
| dict_name: Name of the dictionary | |
| active: Whether the dictionary should be active | |
| """ | |
| self.active_status[dict_name] = active | |
| def get_active_dictionaries(self): | |
| """ | |
| Get only the active dictionaries. | |
| Returns: | |
| Dictionary containing only active data dictionaries | |
| """ | |
| return {name: content for name, content in self.data_dictionaries.items() | |
| if self.active_status.get(name, True)} | |
| def load_default_dictionaries(self): | |
| """ | |
| Load dictionaries from the default directory. | |
| Returns: | |
| Number of dictionaries loaded | |
| """ | |
| count = 0 | |
| for file_path in self.default_dict_path.glob("*.*"): | |
| if file_path.suffix.lower() in ['.pdf', '.xlsx', '.xls', '.csv']: | |
| content = self._load_file(file_path) | |
| if content: | |
| self.data_dictionaries[str(file_path)] = content | |
| self.active_status[str(file_path)] = True | |
| count += 1 | |
| return count | |
| def load_user_dictionaries(self): | |
| """ | |
| Load dictionaries from the user uploads directory. | |
| Returns: | |
| Number of dictionaries loaded | |
| """ | |
| count = 0 | |
| for file_path in self.user_upload_path.glob("*.*"): | |
| if file_path.suffix.lower() in ['.pdf', '.xlsx', '.xls', '.csv']: | |
| content = self._load_file(file_path) | |
| if content: | |
| self.data_dictionaries[str(file_path)] = content | |
| self.active_status[str(file_path)] = True | |
| count += 1 | |
| return count | |
| def load_session_dictionaries(self, session_dir: str): | |
| """ | |
| Load dictionaries from a specific session directory. | |
| Args: | |
| session_dir: Path to the session-specific upload directory | |
| Returns: | |
| Number of dictionaries loaded | |
| """ | |
| count = 0 | |
| session_path = Path(session_dir) | |
| if session_path.exists(): | |
| for file_path in session_path.glob("*.*"): | |
| if file_path.suffix.lower() in ['.pdf', '.xlsx', '.xls', '.csv']: | |
| content = self._load_file(file_path) | |
| if content: | |
| self.data_dictionaries[str(file_path)] = content | |
| self.active_status[str(file_path)] = True | |
| count += 1 | |
| return count | |
| def _load_file(self, file_path: Path) -> str: | |
| """ | |
| Load content from a file based on its type. | |
| Args: | |
| file_path: Path to the file | |
| Returns: | |
| String content of the file | |
| """ | |
| try: | |
| if file_path.suffix.lower() == '.pdf': | |
| return self._load_pdf(file_path) | |
| elif file_path.suffix.lower() in ['.xlsx', '.xls']: | |
| return self._load_excel(file_path) | |
| elif file_path.suffix.lower() == '.csv': | |
| return self._load_csv(file_path) | |
| except Exception as e: | |
| print(f"Error loading {file_path}: {str(e)}") | |
| return None | |
| def _load_pdf(self, file_path: Path) -> str: | |
| """Load content from a PDF file.""" | |
| with open(file_path, 'rb') as file: | |
| reader = PyPDF2.PdfReader(file) | |
| text = "" | |
| for page in reader.pages: | |
| text += page.extract_text() + "\n" | |
| return text | |
| def _load_excel(self, file_path: Path) -> str: | |
| """Load content from an Excel file.""" | |
| df = pd.read_excel(file_path) | |
| return df.to_string() | |
| def _load_csv(self, file_path: Path) -> str: | |
| """Load content from a CSV file.""" | |
| df = pd.read_csv(file_path) | |
| return df.to_string() | |
| def save_uploaded_file(self, uploaded_file) -> dict: | |
| """ | |
| Save an uploaded file and load it into the service. | |
| Args: | |
| uploaded_file: Streamlit UploadedFile object | |
| Returns: | |
| Dictionary with status information | |
| """ | |
| try: | |
| # Create save path | |
| save_path = self.user_upload_path / uploaded_file.name | |
| # Save file | |
| with open(save_path, "wb") as f: | |
| f.write(uploaded_file.getbuffer()) | |
| # Load the file into the service | |
| content = self._load_file(save_path) | |
| if content: | |
| self.data_dictionaries[str(save_path)] = content | |
| self.active_status[str(save_path)] = True | |
| return { | |
| "success": True, | |
| "message": f"Successfully uploaded and loaded {uploaded_file.name}" | |
| } | |
| else: | |
| return { | |
| "success": False, | |
| "message": f"Failed to load {uploaded_file.name}" | |
| } | |
| except Exception as e: | |
| return { | |
| "success": False, | |
| "message": f"Error saving file: {str(e)}" | |
| } | |
| def delete_dictionary(self, dict_name: str) -> dict: | |
| """ | |
| Delete a dictionary file and remove it from the service. | |
| Args: | |
| dict_name: Name of the dictionary to delete | |
| Returns: | |
| Dictionary with status information | |
| """ | |
| try: | |
| # Find the full path | |
| full_path = None | |
| for path in self.data_dictionaries.keys(): | |
| if dict_name in path: | |
| full_path = Path(path) | |
| break | |
| if not full_path: | |
| return { | |
| "success": False, | |
| "message": f"Dictionary {dict_name} not found" | |
| } | |
| # Only allow deleting user uploads | |
| if self.user_upload_path not in full_path.parents: | |
| return { | |
| "success": False, | |
| "message": "Can only delete user-uploaded dictionaries" | |
| } | |
| # Delete file | |
| if full_path.exists(): | |
| full_path.unlink() | |
| # Remove from service | |
| if str(full_path) in self.data_dictionaries: | |
| del self.data_dictionaries[str(full_path)] | |
| if str(full_path) in self.active_status: | |
| del self.active_status[str(full_path)] | |
| return { | |
| "success": True, | |
| "message": f"Successfully deleted {dict_name}" | |
| } | |
| except Exception as e: | |
| return { | |
| "success": False, | |
| "message": f"Error deleting dictionary: {str(e)}" | |
| } | |
| self.user_upload_path.mkdir(parents=True, exist_ok=True) | |
| def load_default_dictionaries(self): | |
| """Load default data dictionaries from the specified directory.""" | |
| loaded_count = 0 | |
| for file in self.default_dict_path.glob('*'): | |
| if file.suffix in ['.pdf', '.xlsx', '.xls', '.csv']: | |
| content = self.extract_data(file) | |
| if content: | |
| self.data_dictionaries[file.stem] = content | |
| loaded_count += 1 | |
| return loaded_count | |
| def load_user_dictionaries(self): | |
| """Load user-uploaded data dictionaries from the specified directory.""" | |
| loaded_count = 0 | |
| for file in self.user_upload_path.glob('*'): | |
| if file.suffix in ['.pdf', '.xlsx', '.xls', '.csv']: | |
| content = self.extract_data(file) | |
| if content: | |
| self.data_dictionaries[file.stem] = content | |
| loaded_count += 1 | |
| return loaded_count | |
| def extract_data(self, file_path: Path) -> str: | |
| """Extract data from a given file based on its type. | |
| Args: | |
| file_path: Path to the file to extract data from. | |
| Returns: | |
| Extracted data as a string. | |
| """ | |
| if file_path.suffix == '.pdf': | |
| return self.extract_text_from_pdf(file_path) | |
| elif file_path.suffix in ['.xlsx', '.xls']: | |
| return self.extract_data_from_excel(file_path) | |
| elif file_path.suffix == '.csv': | |
| return self.extract_data_from_csv(file_path) | |
| return "" | |
| def extract_text_from_pdf(self, pdf_path: Path) -> str: | |
| """Extract text content from a PDF file. | |
| Args: | |
| pdf_path: Path to the PDF file. | |
| Returns: | |
| Extracted text content. | |
| """ | |
| 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: | |
| print(f"Error reading PDF {pdf_path}: {str(e)}") | |
| return "" | |
| def extract_data_from_excel(self, excel_path: Path) -> str: | |
| """Extract data from an Excel file. | |
| Args: | |
| excel_path: Path to the Excel file. | |
| Returns: | |
| Text representation of the Excel data. | |
| """ | |
| text = "" | |
| 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) | |
| text += f"\n--- Sheet: {sheet_name} ---\n" | |
| text += df.to_string(index=False) + "\n" | |
| return text | |
| except Exception as e: | |
| print(f"Error reading Excel {excel_path}: {str(e)}") | |
| return "" | |
| def extract_data_from_csv(self, csv_path: Path) -> str: | |
| """Extract data from a CSV file. | |
| Args: | |
| csv_path: Path to the CSV file. | |
| Returns: | |
| Text representation of the CSV data. | |
| """ | |
| # Try multiple encodings | |
| encodings = ['utf-8', 'latin-1', 'iso-8859-1', 'cp1252', 'utf-16'] | |
| for encoding in encodings: | |
| try: | |
| df = pd.read_csv(csv_path, encoding=encoding) | |
| return df.to_string(index=False) | |
| except UnicodeDecodeError: | |
| continue | |
| except Exception as e: | |
| if encoding == encodings[-1]: # Last encoding attempt | |
| print(f"Error reading CSV {csv_path}: {str(e)}") | |
| return "" | |
| print(f"Error reading CSV {csv_path}: Unable to decode with any supported encoding") | |
| return "" | |
| def get_data_dictionaries(self) -> dict: | |
| """Return the loaded data dictionaries. | |
| Returns: | |
| A dictionary containing all loaded data dictionaries. | |
| """ | |
| return self.data_dictionaries |