Spaces:
Running
Running
| """ | |
| GitHub-enabled side effects handler | |
| This module provides GitHub storage functionality for side effects reporting | |
| """ | |
| import os | |
| import csv | |
| from datetime import datetime | |
| from typing import Dict, Any | |
| import pytz | |
| from .github_storage import get_github_storage | |
| from .config import logger | |
| def save_side_effect_report_to_github(extracted_data: Dict[str, Any]) -> str: | |
| """ | |
| Save the side effect report to GitHub repository with fallback to local storage. | |
| Args: | |
| extracted_data: Dictionary containing side effects report data | |
| Returns: | |
| Confirmation message string | |
| """ | |
| try: | |
| # Ensure all fields have values (use 'NaN' for empty fields) | |
| fieldnames = [ | |
| 'timestamp', 'drug_name', 'side_effects', 'patient_age', | |
| 'patient_gender', 'dosage', 'duration', 'severity', | |
| 'outcome', 'additional_details', 'reporter_info', 'raw_input' | |
| ] | |
| # Fill missing fields with 'NaN' and ensure proper data types | |
| for field in fieldnames: | |
| value = extracted_data.get(field, '') | |
| if not value or value == '' or not str(value).strip(): | |
| extracted_data[field] = 'NaN' | |
| else: | |
| # Ensure the value is properly formatted | |
| extracted_data[field] = str(value).strip() | |
| # Save to GitHub repository | |
| github_storage = get_github_storage() | |
| success = github_storage.save_side_effects_report(extracted_data) | |
| if not success: | |
| # Fallback to local storage if GitHub fails | |
| csv_filename = "side_effects_reports.csv" | |
| csv_path = os.path.join(os.getcwd(), csv_filename) | |
| file_exists = os.path.exists(csv_path) | |
| with open(csv_path, 'a', newline='', encoding='utf-8') as csvfile: | |
| writer = csv.DictWriter(csvfile, fieldnames=fieldnames) | |
| if not file_exists: | |
| writer.writeheader() | |
| writer.writerow(extracted_data) | |
| storage_location = f"locally to {csv_filename} (GitHub upload failed)" | |
| logger.warning("GitHub upload failed, saved locally as fallback") | |
| else: | |
| storage_location = "to GitHub cloud repository" | |
| logger.info("Successfully saved side effects report to GitHub") | |
| # Generate confirmation message | |
| drug_name = extracted_data.get('drug_name', 'NaN') | |
| side_effects = extracted_data.get('side_effects', 'NaN') | |
| report_id = extracted_data['timestamp'].replace(':', '').replace('-', '').replace(' ', '_') | |
| # Create a summary of provided vs missing information | |
| provided_info = [] | |
| missing_info = [] | |
| info_fields = { | |
| 'drug_name': 'Drug/Medication', | |
| 'side_effects': 'Side Effects', | |
| 'patient_age': 'Patient Age', | |
| 'patient_gender': 'Patient Gender', | |
| 'dosage': 'Dosage', | |
| 'duration': 'Duration', | |
| 'severity': 'Severity', | |
| 'outcome': 'Outcome' | |
| } | |
| for field, display_name in info_fields.items(): | |
| value = extracted_data.get(field, 'NaN') | |
| if value and value != 'NaN': | |
| provided_info.append(f"- **{display_name}:** {value}") | |
| else: | |
| missing_info.append(display_name) | |
| confirmation = f""" | |
| **✅ Adverse Drug Reaction Report Saved** | |
| **Report ID:** {report_id} | |
| **Documented Information:** | |
| {chr(10).join(provided_info) if provided_info else '- Basic side effect report recorded'} | |
| **Pharmacovigilance Status:** Report successfully saved {storage_location} for regulatory review. | |
| **Clinical Recommendations:** | |
| - Monitor patient for symptom progression | |
| - Consider dose adjustment or alternative therapy if appropriate | |
| - Document in patient medical record | |
| - Report serious reactions to pharmacovigilance authorities | |
| How can I assist you further with clinical guidance for this case? | |
| """ | |
| return confirmation.strip() | |
| except Exception as e: | |
| logger.error(f"Error saving side effect report: {e}") | |
| return f"Error saving side effect report: {str(e)}" | |
| def get_side_effects_reports_from_github(): | |
| """ | |
| Get all side effects reports from GitHub repository with local fallback. | |
| Returns: | |
| List of side effects reports | |
| """ | |
| try: | |
| github_storage = get_github_storage() | |
| reports = github_storage.get_side_effects_reports() | |
| if reports: | |
| logger.info(f"Retrieved {len(reports)} side effects reports from GitHub") | |
| return reports | |
| # Fallback to local file | |
| csv_path = "side_effects_reports.csv" | |
| if os.path.exists(csv_path): | |
| import pandas as pd | |
| df = pd.read_csv(csv_path) | |
| reports = df.to_dict('records') | |
| logger.info(f"Retrieved {len(reports)} side effects reports from local file (GitHub fallback)") | |
| return reports | |
| logger.info("No side effects reports found in GitHub or local storage") | |
| return [] | |
| except Exception as e: | |
| logger.error(f"Error retrieving side effects reports: {e}") | |
| return [] | |
| def get_drug_reports_from_github(drug_name: str): | |
| """ | |
| Get side effects reports for a specific drug from GitHub repository. | |
| Args: | |
| drug_name: Name of the drug to filter reports | |
| Returns: | |
| List of reports for the specified drug | |
| """ | |
| try: | |
| github_storage = get_github_storage() | |
| reports = github_storage.get_drug_reports(drug_name) | |
| if reports: | |
| logger.info(f"Retrieved {len(reports)} reports for {drug_name} from GitHub") | |
| return reports | |
| # Fallback to local file | |
| csv_path = "side_effects_reports.csv" | |
| if os.path.exists(csv_path): | |
| import pandas as pd | |
| df = pd.read_csv(csv_path) | |
| drug_reports = df[df['drug_name'].str.lower() == drug_name.lower()] | |
| reports = drug_reports.to_dict('records') | |
| logger.info(f"Retrieved {len(reports)} reports for {drug_name} from local file (GitHub fallback)") | |
| return reports | |
| logger.info(f"No reports found for {drug_name} in GitHub or local storage") | |
| return [] | |
| except Exception as e: | |
| logger.error(f"Error retrieving drug reports for {drug_name}: {e}") | |
| return [] | |