sample / app.py
yougandar's picture
Update app.py
f98fda7 verified
import gradio as gr
import pandas as pd
import os
import logging
# Set up logging
logging.basicConfig(level=logging.DEBUG, format='%(asctime)s - %(levelname)s - %(message)s')
# Ensure the "files" directory exists
FILES_DIR = "files"
os.makedirs(FILES_DIR, exist_ok=True)
# Path to CSV file in the "files" directory of your project
CSV_FILE = os.path.join(FILES_DIR, "patients.csv")
# Initialize the CSV file if it does not exist
if not os.path.exists(CSV_FILE):
df = pd.DataFrame(columns=["Patient ID", "Patient Name", "Age", "Phone Number"])
try:
df.to_csv(CSV_FILE, index=False)
logging.info(f"Created new CSV file at {CSV_FILE}")
except Exception as e:
logging.error(f"Failed to create CSV file: {e}")
# Function to handle registration
def register_patient(name, age, phone):
try:
logging.info(f"Starting registration for {name}, Age: {age}, Phone: {phone}")
# Load existing data
df = pd.read_csv(CSV_FILE)
logging.debug(f"Loaded existing data: {df}")
# Generate new patient ID
new_id = len(df) + 1
# Append new patient data
new_data = pd.DataFrame({
"Patient ID": [new_id],
"Patient Name": [name],
"Age": [age],
"Phone Number": [phone]
})
logging.info(f"New patient data: {new_data}")
df = pd.concat([df, new_data], ignore_index=True)
logging.debug(f"Updated DataFrame: {df}")
# Save updated data
df.to_csv(CSV_FILE, index=False)
logging.info(f"Data saved to CSV file successfully at {CSV_FILE}.")
return f"Patient {name} with ID {new_id} registered successfully!", CSV_FILE
except Exception as e:
logging.error(f"An error occurred while registering patient: {e}")
return f"An error occurred: {e}", None
# Define Gradio interface
with gr.Blocks() as demo:
gr.Markdown("## Patient Registration")
with gr.Row():
patient_name = gr.Textbox(label="Patient Name", placeholder="Enter patient name")
age = gr.Number(label="Age", precision=0)
phone_number = gr.Textbox(label="Phone Number", placeholder="Enter phone number")
register_button = gr.Button("Register")
status = gr.Textbox(label="Status", interactive=False)
download_button = gr.File(label="Download CSV")
def update_status_and_file(*inputs):
message, file_path = register_patient(*inputs)
return message, file_path
register_button.click(fn=update_status_and_file, inputs=[patient_name, age, phone_number], outputs=[status, download_button])
# Launch the app
if __name__ == "__main__":
demo.launch()