import gradio as gr import pandas as pd import os import csv # Path to the CSV files patients_file_path = "patients.csv" reports_file_path = "reports.csv" def load_patient_data(): """Load patient data from CSV.""" try: patients_df = pd.read_csv(patients_file_path) expected_columns = ["Patient ID", "Patient Name", "Age", "Gender", "Contact Number"] if set(patients_df.columns) != set(expected_columns): raise ValueError("CSV columns do not match expected columns") return patients_df except FileNotFoundError: return pd.DataFrame(columns=["Patient ID", "Patient Name", "Age", "Gender", "Contact Number"]) except pd.errors.EmptyDataError: return pd.DataFrame(columns=["Patient ID", "Patient Name", "Age", "Gender", "Contact Number"]) except pd.errors.ParserError as e: print(f"Error parsing the CSV file: {e}") return pd.DataFrame(columns=["Patient ID", "Patient Name", "Age", "Gender", "Contact Number"]) except ValueError as e: print(f"Error with CSV columns: {e}") return pd.DataFrame(columns=["Patient ID", "Patient Name", "Age", "Gender", "Contact Number"]) def get_patient_details(patient_id): """Retrieve the patient name based on Patient ID.""" if not os.path.exists(patients_file_path): return "Patients file not found." with open(patients_file_path, mode='r') as file: reader = csv.DictReader(file) for row in reader: if str(row["Patient ID"]).strip() == str(patient_id).strip(): return row["Patient Name"] return "Patient ID not found." def autofill_patient_name(patient_id): """Auto-fill the patient Name.""" return get_patient_details(patient_id) def load_reports_data(): """Load report data from CSV.""" try: reports_df = pd.read_csv(reports_file_path) expected_columns = ["Report ID", "Patient ID", "Report File"] if set(reports_df.columns) != set(expected_columns): raise ValueError("CSV columns do not match expected columns") return reports_df except FileNotFoundError: return pd.DataFrame(columns=["Report ID", "Patient ID", "Report File"]) except pd.errors.EmptyDataError: return pd.DataFrame(columns=["Report ID", "Patient ID", "Report File"]) except pd.errors.ParserError as e: print(f"Error parsing the CSV file: {e}") return pd.DataFrame(columns=["Report ID", "Patient ID", "Report File"]) except ValueError as e: print(f"Error with CSV columns: {e}") return pd.DataFrame(columns=["Report ID", "Patient ID", "Report File"]) def handle_file_upload(patient_id, file): """Handle file upload and save report details.""" patient_name = get_patient_details(patient_id) if patient_name == "Patient ID not found": return f"Error: {patient_name}" if file is None: return "Error: No file uploaded" # Use the original file name original_filename = os.path.basename(file) # Get the base name of the uploaded file sanitized_filename = original_filename.replace(" ", "_").lower() # Sanitize file name for file system file_name = f"report_{patient_id}_{sanitized_filename}" file_path = f"reports/{file_name}" os.makedirs(os.path.dirname(file_path), exist_ok=True) # Copy the uploaded file to the destination path os.rename(file, file_path) # Load existing reports data reports_df = load_reports_data() # Add new report details (only the file name, not the full path) new_report = pd.DataFrame({ "Report ID": [reports_df["Report ID"].max() + 1 if not reports_df.empty else 1], "Patient ID": [patient_id], "Report File": [file_name] # Store the file name with the original file name }) # Append new report details to existing data reports_df = pd.concat([reports_df, new_report], ignore_index=True) # Save updated reports data reports_df.to_csv(reports_file_path, index=False) return f"Report uploaded successfully for {patient_name}." def gradio_interface(): """Create Gradio interface for adding reports.""" with gr.Blocks() as demo: with gr.Row(): # Input for patient ID patient_id = gr.Number(label="Patient ID", precision=0) # Output for patient name patient_name = gr.Textbox(label="Patient Name", interactive=False) # Function to update patient name def update_patient_name(id): return autofill_patient_name(str(id)) # Update patient name when Patient ID changes patient_id.change( fn=update_patient_name, inputs=patient_id, outputs=patient_name ) # File upload for report file_upload = gr.File(label="Upload Report (PDF or JPG)", type="filepath") # Button to submit the report submit_button = gr.Button("Submit") # Output for submission result output_text = gr.Textbox(label="Submission Result", interactive=False) # Handle file upload when the button is clicked submit_button.click( fn=handle_file_upload, inputs=[patient_id, file_upload], outputs=output_text ) return demo if __name__ == "__main__": interface = gradio_interface() interface.launch()