import gradio as gr
import joblib
import numpy as np
import pandas as pd
from huggingface_hub import hf_hub_download
from sklearn.preprocessing import StandardScaler, LabelEncoder

REPO_ID = "Hemg/modelxxx"
MoDEL_FILENAME = "studentpredict.joblib"
SCALER_FILENAME = "studentscaler.joblib"

model = joblib.load(hf_hub_download(repo_id=REPO_ID, filename=MoDEL_FILENAME))
scaler = joblib.load(hf_hub_download(repo_id=REPO_ID, filename=SCALER_FILENAME))

def encode_categorical_columns(df):
    label_encoder = LabelEncoder()
    ordinal_columns = df.select_dtypes(include=['object']).columns

    for col in ordinal_columns:
        df[col] = label_encoder.fit_transform(df[col])

    nominal_columns = df.select_dtypes(include=['object']).columns.difference(ordinal_columns)
    df = pd.get_dummies(df, columns=nominal_columns, drop_first=True)

    return df

def predict_performance(Location, College_Fee, College, GPA, Year, Course_Interested, Faculty, Source, 
                       Visited_College_for_Inquiry_Only, Event, Attended_Any_Events, 
                       Presenter, Visited_Parents):
    try:
        input_data = [[Location, College_Fee, College, GPA, Year, Course_Interested, Faculty, Source,
                    Visited_College_for_Inquiry_Only, Event, Attended_Any_Events,
                    Presenter, Visited_Parents]]

        feature_names = ["Location", "College Fee", "College", "GPA", "Year", "Course Interested",
                     "Faculty", "Source", "Visited College for Inquiry Only", "Event",
                     "Attended Any Events", "Presenter", "Visited Parents"]
        
        input_df = pd.DataFrame(input_data, columns=feature_names)
        df = encode_categorical_columns(input_df)
        df = df.reindex(columns=scaler.feature_names_in_, fill_value=0)
        scaled_input = scaler.transform(df)

        # Get probability prediction
        probabilities = model.predict_proba(scaled_input)[0]
        # Take the probability of positive class (usually index 1)
        admission_probability = probabilities[1]
        
        # Ensure the probability is between 0 and 1
        admission_probability = np.clip(admission_probability, 0, 1)
        
        # Convert to percentage
        prediction_percentage = admission_probability * 100

        # Create styled HTML output
        # html_template = """
        # <div style='text-align: center; padding: 20px;'>
        #     <div style='font-family: Arial, sans-serif; font-size: 24px; margin-bottom: 15px;'>
        #         Admission Probability: <span style='font-weight: bold;'>{:.1f}%</span>
        #     </div>
        #     <div style='{style}'>
        #         {message}
        #     </div>
        # </div>
        # """
 # Create styled HTML output
        html_template = """
        <div style='text-align: center; padding: 20px;'>
            <div style='{style}'>
                {message}
            </div>
        </div>
        """


        if prediction_percentage > 50:
            style = "font-family: Arial, sans-serif; font-size: 32px; color: #28a745; font-weight: bold;"
            message = "High chance of admission"
        elif prediction_percentage < 50:
            style = "font-family: Arial, sans-serif; font-size: 32px; color: #dc3545; font-weight: bold; text-transform: uppercase;"
            message = "Lower chance of admission"
        else:  # exactly 50
            style = "font-family: Arial, sans-serif; font-size: 32px; color: #ffc107; font-weight: bold;"
            message = "Moderate chance of admission"

        return html_template.format(prediction_percentage, style=style, message=message)

    except Exception as e:
        return f"<div style='color: red; font-family: Arial, sans-serif;'>Error in prediction: {str(e)}</div>"

# Update the Gradio interface
iface = gr.Interface(
    fn=predict_performance,
   inputs=[
        gr.Radio(["Kathmandu", "Bhaktapur", "Lalitpur", "Kritipur"], label="Location",info="What is your current location?"),
        gr.Slider(minimum=1000000, maximum=1700000,step=100000,label="College Fee", info="What 's the the total bachelor fee for the course you want to enroll?"),
        gr.Radio(["Trinity", "CCRC", "KMC", "SOS", "ISMT", "St. Xavier's", "Everest", "Prime"], label="College", info="What is the name of the last college you attended?"),
        gr.Slider(minimum=2, maximum=3, label="GPA", info="What is your GPA (Grade Point Average) of +2 ?"),
        gr.Slider(minimum=2024, maximum=2026, step=1, label="Year", info="What is your intended year of admission?"),
        #gr.Radio([2024, 2025, 2026], label="Year", info="What is your intended year of admission?")
        gr.Radio(["MSc IT & Applied Security", "BSc (Hons) Computing", "BSc (Hons) Computing with Artificial Intelligence", 
                 "BSc (Hons) Computer Networking & IT Security", "BSc (Hons) Multimedia Technologies", "MBA", 
                 "BA (Hons) Accounting &  Finance", "BA (Hons) Business Administration"], label="Course_Interested", info="Which course are you most interested in?"),
        gr.Radio(["Science", "Management", "Humanities"], label="Faculty", info="what is your last stream ?"),
        gr.Radio(["Event", "Facebook", "Instagram", "Offline", "Recommendation"], label="Source",info="How did you first hear about this college?"),
        gr.Radio(["Yes", "No"], label="visited_college_for_inquery_only", info="Have you visited the college you're interested in for an inquiry or consultation?"),
        gr.Radio(["Yes", "No"], label="attended_any_event", info="Have you attended any events organized by the college you're interested in?"),
        gr.Radio(["New Year", "Dashain", "Orientation", "Fresher's Party", "Holi Festival", "Welcome Ceremony"], 
                label="attended_event_name", info="If yes, which events did you attend?" ),
        gr.Radio(["Ram", "Gita", "Manish", "Shyam", "Raj", "Hari", "Rina", "Shree"], label="Presenter", info="who is the counser that help you while in counseling?"),
        gr.Radio(["Yes", "No"], label="visited_with_parents", info="Did you visit the college with your parents?")
    ],


    
    outputs=gr.HTML(),  # Changed to HTML output
    title="Student Admission Prediction",
    description="Predict the probability of student admission",
    css="body { font-family: Arial, sans-serif; }"
)

if __name__ == "__main__":
    iface.launch(share=True)