SailajaS commited on
Commit
7d07c47
Β·
verified Β·
1 Parent(s): c4da40d

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +112 -20
app.py CHANGED
@@ -1,20 +1,112 @@
1
- runtime error
2
- Exit code: 1. Reason: πŸ“₯ Downloading dataset from Hugging Face...
3
- βœ… Dataset downloaded successfully!
4
- Traceback (most recent call last):
5
- File "/home/user/app/app.py", line 39, in <module>
6
- df = pd.read_csv(DATASET_PATH)
7
- File "/usr/local/lib/python3.10/site-packages/pandas/io/parsers/readers.py", line 1026, in read_csv
8
- return _read(filepath_or_buffer, kwds)
9
- File "/usr/local/lib/python3.10/site-packages/pandas/io/parsers/readers.py", line 626, in _read
10
- return parser.read(nrows)
11
- File "/usr/local/lib/python3.10/site-packages/pandas/io/parsers/readers.py", line 1923, in read
12
- ) = self._engine.read( # type: ignore[attr-defined]
13
- File "/usr/local/lib/python3.10/site-packages/pandas/io/parsers/c_parser_wrapper.py", line 234, in read
14
- chunks = self._reader.read_low_memory(nrows)
15
- File "parsers.pyx", line 838, in pandas._libs.parsers.TextReader.read_low_memory
16
- File "parsers.pyx", line 905, in pandas._libs.parsers.TextReader._read_rows
17
- File "parsers.pyx", line 874, in pandas._libs.parsers.TextReader._tokenize_rows
18
- File "parsers.pyx", line 891, in pandas._libs.parsers.TextReader._check_tokenize_status
19
- File "parsers.pyx", line 2061, in pandas._libs.parsers.raise_parser_error
20
- pandas.errors.ParserError: Error tokenizing data. C error: Expected 1 fields in line 5, saw 3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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()