Update app.py
Browse files
app.py
CHANGED
|
@@ -1,20 +1,112 @@
|
|
| 1 |
-
|
| 2 |
-
|
| 3 |
-
|
| 4 |
-
|
| 5 |
-
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from fastapi import FastAPI
|
| 2 |
+
import pandas as pd
|
| 3 |
+
import uvicorn
|
| 4 |
+
import joblib
|
| 5 |
+
from sklearn.model_selection import train_test_split
|
| 6 |
+
from sklearn.ensemble import RandomForestClassifier
|
| 7 |
+
from sklearn.preprocessing import LabelEncoder
|
| 8 |
+
from pydantic import BaseModel
|
| 9 |
+
import gradio as gr
|
| 10 |
+
import os
|
| 11 |
+
import requests
|
| 12 |
+
|
| 13 |
+
app = FastAPI()
|
| 14 |
+
|
| 15 |
+
# β
Correct Hugging Face Dataset URL
|
| 16 |
+
DATASET_URL = "https://huggingface.co/datasets/SailajaS/CDART/resolve/main/train.csv"
|
| 17 |
+
|
| 18 |
+
# File path for saving dataset
|
| 19 |
+
DATASET_PATH = "dataset.csv"
|
| 20 |
+
|
| 21 |
+
# Function to download dataset
|
| 22 |
+
def download_dataset():
|
| 23 |
+
print("π₯ Downloading dataset from Hugging Face...")
|
| 24 |
+
|
| 25 |
+
try:
|
| 26 |
+
response = requests.get(DATASET_URL, timeout=10)
|
| 27 |
+
|
| 28 |
+
if response.status_code == 200:
|
| 29 |
+
with open(DATASET_PATH, "wb") as file:
|
| 30 |
+
file.write(response.content)
|
| 31 |
+
print("β
Dataset downloaded successfully!")
|
| 32 |
+
else:
|
| 33 |
+
raise Exception(f"β Failed to download dataset: {response.status_code}")
|
| 34 |
+
|
| 35 |
+
except requests.exceptions.RequestException as e:
|
| 36 |
+
print(f"β Error downloading dataset: {e}")
|
| 37 |
+
raise Exception("Dataset download failed.")
|
| 38 |
+
|
| 39 |
+
# β
Download dataset at startup
|
| 40 |
+
download_dataset()
|
| 41 |
+
|
| 42 |
+
# β
Load dataset with error handling
|
| 43 |
+
try:
|
| 44 |
+
df = pd.read_csv(DATASET_PATH, encoding="utf-8", delimiter=",", error_bad_lines=False)
|
| 45 |
+
except:
|
| 46 |
+
try:
|
| 47 |
+
df = pd.read_csv(DATASET_PATH, encoding="utf-8", delimiter=";", error_bad_lines=False)
|
| 48 |
+
except:
|
| 49 |
+
raise Exception("β Unable to read CSV. Check delimiter and format.")
|
| 50 |
+
|
| 51 |
+
# β
Check if necessary columns exist
|
| 52 |
+
required_columns = ["Case Problem", "Feedback"]
|
| 53 |
+
for col in required_columns:
|
| 54 |
+
if col not in df.columns:
|
| 55 |
+
raise Exception(f"β Column '{col}' is missing from the dataset!")
|
| 56 |
+
|
| 57 |
+
# β
Encode categorical variables
|
| 58 |
+
encoder = LabelEncoder()
|
| 59 |
+
df["Case Problem"] = encoder.fit_transform(df["Case Problem"])
|
| 60 |
+
df["Feedback"] = encoder.fit_transform(df["Feedback"])
|
| 61 |
+
|
| 62 |
+
# β
Train Model
|
| 63 |
+
X = df[["Case Problem"]]
|
| 64 |
+
y = df["Feedback"]
|
| 65 |
+
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
|
| 66 |
+
model = RandomForestClassifier(n_estimators=100, random_state=42)
|
| 67 |
+
model.fit(X_train, y_train)
|
| 68 |
+
|
| 69 |
+
# β
Save model
|
| 70 |
+
joblib.dump(model, "feedback_model.pkl")
|
| 71 |
+
print("β
Model trained successfully!")
|
| 72 |
+
|
| 73 |
+
# β
API Input Model
|
| 74 |
+
class PredictionInput(BaseModel):
|
| 75 |
+
case_problem: str
|
| 76 |
+
|
| 77 |
+
@app.post("/predict/")
|
| 78 |
+
def predict_feedback(data: PredictionInput):
|
| 79 |
+
""" Predicts feedback based on Case Problem """
|
| 80 |
+
if model is None:
|
| 81 |
+
return {"error": "Model is not trained yet."}
|
| 82 |
+
|
| 83 |
+
try:
|
| 84 |
+
case_problem_encoded = encoder.transform([data.case_problem])
|
| 85 |
+
prediction = model.predict([[case_problem_encoded[0]]])
|
| 86 |
+
feedback_predicted = encoder.inverse_transform(prediction)[0]
|
| 87 |
+
return {"Predicted Feedback": feedback_predicted}
|
| 88 |
+
except Exception as e:
|
| 89 |
+
return {"error": str(e)}
|
| 90 |
+
|
| 91 |
+
# β
Gradio UI
|
| 92 |
+
def gradio_interface(case_problem):
|
| 93 |
+
if model is None:
|
| 94 |
+
return "Model not trained yet."
|
| 95 |
+
|
| 96 |
+
try:
|
| 97 |
+
case_problem_encoded = encoder.transform([case_problem])
|
| 98 |
+
prediction = model.predict([[case_problem_encoded[0]]])
|
| 99 |
+
feedback_predicted = encoder.inverse_transform(prediction)[0]
|
| 100 |
+
return f"Predicted Feedback: {feedback_predicted}"
|
| 101 |
+
except:
|
| 102 |
+
return "Invalid case problem. Please enter a valid category."
|
| 103 |
+
|
| 104 |
+
# β
Start both API & Gradio
|
| 105 |
+
def start_app():
|
| 106 |
+
""" Start API and Gradio Interface """
|
| 107 |
+
gr_interface = gr.Interface(fn=gradio_interface, inputs="text", outputs="text")
|
| 108 |
+
gr_interface.launch()
|
| 109 |
+
uvicorn.run(app, host="0.0.0.0", port=8000)
|
| 110 |
+
|
| 111 |
+
if __name__ == "__main__":
|
| 112 |
+
start_app()
|