SailajaS commited on
Commit
0cbe5f3
Β·
verified Β·
1 Parent(s): b7f9af6

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +29 -17
app.py CHANGED
@@ -12,7 +12,7 @@ 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
@@ -32,29 +32,35 @@ def download_dataset():
32
  print(f"❌ Failed to download dataset: {response.status_code}")
33
  raise Exception("Dataset download failed.")
34
 
35
- # Download dataset at startup
36
  download_dataset()
37
 
38
- # Load dataset
39
  df = pd.read_csv(DATASET_PATH)
40
 
41
- # Encode categorical variables
 
 
 
 
 
 
42
  encoder = LabelEncoder()
43
  df["Case Problem"] = encoder.fit_transform(df["Case Problem"])
44
  df["Feedback"] = encoder.fit_transform(df["Feedback"])
45
 
46
- # Train Model
47
  X = df[["Case Problem"]]
48
  y = df["Feedback"]
49
  X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
50
  model = RandomForestClassifier(n_estimators=100, random_state=42)
51
  model.fit(X_train, y_train)
52
 
53
- # Save model
54
  joblib.dump(model, "feedback_model.pkl")
55
  print("βœ… Model trained successfully!")
56
 
57
- # API Input Model
58
  class PredictionInput(BaseModel):
59
  case_problem: str
60
 
@@ -64,22 +70,28 @@ def predict_feedback(data: PredictionInput):
64
  if model is None:
65
  return {"error": "Model is not trained yet."}
66
 
67
- case_problem_encoded = encoder.transform([data.case_problem])
68
- prediction = model.predict([[case_problem_encoded[0]]])
69
- feedback_predicted = encoder.inverse_transform(prediction)[0]
70
- return {"Predicted Feedback": feedback_predicted}
 
 
 
71
 
72
- # Gradio UI
73
  def gradio_interface(case_problem):
74
  if model is None:
75
  return "Model not trained yet."
76
 
77
- case_problem_encoded = encoder.transform([case_problem])
78
- prediction = model.predict([[case_problem_encoded[0]]])
79
- feedback_predicted = encoder.inverse_transform(prediction)[0]
80
- return f"Predicted Feedback: {feedback_predicted}"
 
 
 
81
 
82
- # Start both API & Gradio
83
  def start_app():
84
  """ Start API and Gradio Interface """
85
  gr_interface = gr.Interface(fn=gradio_interface, inputs="text", outputs="text")
 
12
 
13
  app = FastAPI()
14
 
15
+ # βœ… Correct dataset URL from Hugging Face (Replace if needed)
16
  DATASET_URL = "https://huggingface.co/datasets/SailajaS/CDART/resolve/main/train.csv"
17
 
18
  # File path for saving dataset
 
32
  print(f"❌ Failed to download dataset: {response.status_code}")
33
  raise Exception("Dataset download failed.")
34
 
35
+ # βœ… Download dataset at startup
36
  download_dataset()
37
 
38
+ # βœ… Load dataset
39
  df = pd.read_csv(DATASET_PATH)
40
 
41
+ # βœ… Check if necessary columns exist
42
+ required_columns = ["Case Problem", "Feedback"]
43
+ for col in required_columns:
44
+ if col not in df.columns:
45
+ raise Exception(f"❌ Column '{col}' is missing from the dataset!")
46
+
47
+ # βœ… Encode categorical variables
48
  encoder = LabelEncoder()
49
  df["Case Problem"] = encoder.fit_transform(df["Case Problem"])
50
  df["Feedback"] = encoder.fit_transform(df["Feedback"])
51
 
52
+ # βœ… Train Model
53
  X = df[["Case Problem"]]
54
  y = df["Feedback"]
55
  X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
56
  model = RandomForestClassifier(n_estimators=100, random_state=42)
57
  model.fit(X_train, y_train)
58
 
59
+ # βœ… Save model
60
  joblib.dump(model, "feedback_model.pkl")
61
  print("βœ… Model trained successfully!")
62
 
63
+ # βœ… API Input Model
64
  class PredictionInput(BaseModel):
65
  case_problem: str
66
 
 
70
  if model is None:
71
  return {"error": "Model is not trained yet."}
72
 
73
+ try:
74
+ case_problem_encoded = encoder.transform([data.case_problem])
75
+ prediction = model.predict([[case_problem_encoded[0]]])
76
+ feedback_predicted = encoder.inverse_transform(prediction)[0]
77
+ return {"Predicted Feedback": feedback_predicted}
78
+ except Exception as e:
79
+ return {"error": str(e)}
80
 
81
+ # βœ… Gradio UI
82
  def gradio_interface(case_problem):
83
  if model is None:
84
  return "Model not trained yet."
85
 
86
+ try:
87
+ case_problem_encoded = encoder.transform([case_problem])
88
+ prediction = model.predict([[case_problem_encoded[0]]])
89
+ feedback_predicted = encoder.inverse_transform(prediction)[0]
90
+ return f"Predicted Feedback: {feedback_predicted}"
91
+ except:
92
+ return "Invalid case problem. Please enter a valid category."
93
 
94
+ # βœ… Start both API & Gradio
95
  def start_app():
96
  """ Start API and Gradio Interface """
97
  gr_interface = gr.Interface(fn=gradio_interface, inputs="text", outputs="text")