SailajaS commited on
Commit
04652fb
·
verified ·
1 Parent(s): 0ba3640

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +96 -31
app.py CHANGED
@@ -1,32 +1,97 @@
 
1
  import pandas as pd
2
- from faker import Faker
3
- import random
4
-
5
- # Initialize Faker
6
- fake = Faker()
7
-
8
- # Sample case problems and feedback
9
- case_problems = ["Login Issues", "Payment Failure", "UI Bug", "Slow Performance", "Feature Request"]
10
- feedback_types = ["Negative", "Positive", "Neutral"]
11
- details = [
12
- "Unable to login after password reset.",
13
- "Payment went through after retrying.",
14
- "The interface is a bit confusing at times.",
15
- "The page load time is slow.",
16
- "Would love a dark mode feature."
17
- ]
18
-
19
- # Generate 50 unique records
20
- data = {
21
- "Name": [fake.name() for _ in range(50)],
22
- "Email": [fake.email() for _ in range(50)],
23
- "Case Problem": [random.choice(case_problems) for _ in range(50)],
24
- "Feedback": [random.choice(feedback_types) for _ in range(50)],
25
- "Details": [random.choice(details) for _ in range(50)],
26
- }
27
-
28
- # Create DataFrame and Save as CSV
29
- df = pd.DataFrame(data)
30
- df.to_csv("sample_case_records_real_names.csv", index=False)
31
-
32
- print("CSV File Generated Successfully")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from fastapi import FastAPI, UploadFile, File
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
+
12
+ app = FastAPI()
13
+
14
+ # Ensure file upload directory exists
15
+ UPLOAD_DIR = "uploaded_files"
16
+ os.makedirs(UPLOAD_DIR, exist_ok=True)
17
+
18
+ # Function to load dataset
19
+ def load_data(file_path):
20
+ if file_path.endswith(".csv"):
21
+ df = pd.read_csv(file_path)
22
+ elif file_path.endswith(".xlsx"):
23
+ df = pd.read_excel(file_path)
24
+ else:
25
+ raise ValueError("Unsupported file format. Please upload a CSV or Excel file.")
26
+
27
+ return df
28
+
29
+ # Placeholder for dataset and model
30
+ df = None
31
+ model = None
32
+ encoder = LabelEncoder()
33
+
34
+ @app.post("/upload/")
35
+ async def upload_file(file: UploadFile = File(...)):
36
+ """ Upload and process the dataset """
37
+ global df, model, encoder
38
+
39
+ file_path = os.path.join(UPLOAD_DIR, file.filename)
40
+
41
+ # Save the uploaded file
42
+ with open(file_path, "wb") as buffer:
43
+ buffer.write(await file.read())
44
+
45
+ # Load the dataset
46
+ df = load_data(file_path)
47
+
48
+ # Encode categorical variables
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
+
62
+ return {"message": f"File '{file.filename}' uploaded and model trained successfully."}
63
+
64
+ # API Input Model
65
+ class PredictionInput(BaseModel):
66
+ case_problem: str
67
+
68
+ @app.post("/predict/")
69
+ def predict_feedback(data: PredictionInput):
70
+ """ Predicts feedback based on Case Problem """
71
+ if model is None:
72
+ return {"error": "Model is not trained yet. Please upload a dataset first."}
73
+
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
+
79
+ # Gradio UI
80
+ def gradio_interface(case_problem):
81
+ if model is None:
82
+ return "Model not trained yet. Please upload a dataset first."
83
+
84
+ case_problem_encoded = encoder.transform([case_problem])
85
+ prediction = model.predict([[case_problem_encoded[0]]])
86
+ feedback_predicted = encoder.inverse_transform(prediction)[0]
87
+ return f"Predicted Feedback: {feedback_predicted}"
88
+
89
+ # Start both API & Gradio
90
+ def start_app():
91
+ """ Start API and Gradio Interface """
92
+ gr_interface = gr.Interface(fn=gradio_interface, inputs="text", outputs="text")
93
+ gr_interface.launch()
94
+ uvicorn.run(app, host="0.0.0.0", port=8000)
95
+
96
+ if __name__ == "__main__":
97
+ start_app()