pratikshahp commited on
Commit
bbaef5b
·
verified ·
1 Parent(s): b986756

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +112 -0
app.py ADDED
@@ -0,0 +1,112 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import os
3
+ import gradio as gr
4
+ import pandas as pd
5
+ from openai import OpenAI
6
+ from transformers import pipeline
7
+ from dotenv import load_dotenv
8
+
9
+ # Load API key
10
+ load_dotenv()
11
+ api_key = os.getenv("OPENAI_API_KEY")
12
+ client = OpenAI(api_key=api_key)
13
+
14
+ # Load sentiment analysis model
15
+ pipe = pipeline("text-classification", model="cardiffnlp/twitter-roberta-base-sentiment-latest")
16
+
17
+ # Function to process CSV file and extract sentiment
18
+ def process_csv(file):
19
+ df = pd.read_csv(file)
20
+
21
+ if "Feedback" not in df.columns or "Employee" not in df.columns:
22
+ return None, "❌ Error: CSV must contain 'Employee' and 'Feedback' columns."
23
+
24
+ # Apply sentiment analysis
25
+ df["Sentiment"] = df["Feedback"].apply(lambda x: pipe(x)[0]["label"])
26
+
27
+ return {"df": df}, "✅ CSV file processed successfully!"
28
+
29
+ # Function to predict attrition risk based on sentiment
30
+ def predict_attrition_risk(employee_name: str, sentiment: str):
31
+ """Predicts attrition risk based on employee sentiment."""
32
+ risk_level = {
33
+ "positive": "Low Risk - Positive sentiment detected.",
34
+ "neutral": "Medium Risk - Neutral sentiment detected.",
35
+ "negative": "High Risk - Negative sentiment detected."
36
+ }
37
+ return f"{employee_name}: {risk_level.get(sentiment.lower(), 'Unknown Sentiment')}"
38
+
39
+ # Function Calling Example - HR Query Analysis
40
+ def analyze_attrition_with_llm(df_dict, hr_query):
41
+ if df_dict is None or "df" not in df_dict:
42
+ return "❌ Error: No processed employee data available. Please upload a CSV file first."
43
+
44
+ df = df_dict["df"]
45
+
46
+ employees_data = [
47
+ {"employee_name": row["Employee"], "sentiment": row["Sentiment"], "feedback": row["Feedback"]}
48
+ for _, row in df.iterrows()
49
+ ]
50
+
51
+ prompt = f"HR asked: '{hr_query}'. Here is the employee sentiment data:\n{json.dumps(employees_data, indent=2)}\n" \
52
+ "Based on sentiment, determine attrition risk and call the function predict_attrition_risk for specific employees."
53
+
54
+ # Call OpenAI API with function calling enabled
55
+ response = client.chat.completions.create(
56
+ model="gpt-4-turbo",
57
+ messages=[{"role": "user", "content": prompt}],
58
+ functions=[
59
+ {
60
+ "name": "predict_attrition_risk",
61
+ "description": "Predicts attrition risk based on sentiment.",
62
+ "parameters": {
63
+ "type": "object",
64
+ "properties": {
65
+ "employee_name": {"type": "string", "description": "Employee's name"},
66
+ "sentiment": {"type": "string", "description": "Extracted sentiment"}
67
+ },
68
+ "required": ["employee_name", "sentiment"]
69
+ }
70
+ }
71
+ ],
72
+ function_call="auto" # Let GPT decide when to call the function
73
+ )
74
+
75
+ # Debug: Print the full LLM response for function calling demonstration
76
+ print("🔍 LLM Response:", response)
77
+
78
+ # Extract function call from GPT response
79
+ message = response.choices[0].message
80
+
81
+ if hasattr(message, "function_call") and message.function_call is not None:
82
+ try:
83
+ function_call = json.loads(message.function_call.arguments)
84
+ employee_name = function_call.get("employee_name")
85
+ sentiment = function_call.get("sentiment")
86
+
87
+ if employee_name and sentiment:
88
+ return f"🤖 **LLM Called Function:** `predict_attrition_risk({employee_name}, {sentiment})`\n\n" + predict_attrition_risk(employee_name, sentiment)
89
+ except Exception as e:
90
+ return f"❌ Error processing LLM function call: {str(e)}"
91
+
92
+ return "🤖 No specific attrition risk prediction was made."
93
+
94
+ # Gradio UI
95
+ with gr.Blocks() as demo:
96
+ gr.Markdown("<h1 style='text-align: center;'>AI-Driven Employee Attrition Risk Analysis</h1>")
97
+
98
+ file_input = gr.File(label="Upload Employee Feedback CSV", file_types=[".csv"])
99
+ process_button = gr.Button("Process CSV")
100
+ analyze_button = gr.Button("Ask HR Query")
101
+
102
+ hr_input = gr.Textbox(label="HR Query (e.g., 'Which employees are at high risk?')")
103
+
104
+ output_text = gr.Markdown(label="Attrition Risk Prediction")
105
+ process_message = gr.Markdown(label="Processing Status")
106
+
107
+ df_state = gr.State()
108
+
109
+ process_button.click(process_csv, inputs=file_input, outputs=[df_state, process_message])
110
+ analyze_button.click(analyze_attrition_with_llm, inputs=[df_state, hr_input], outputs=output_text)
111
+
112
+ demo.launch(share=True)