varshakolanu commited on
Commit
d1b6abf
·
verified ·
1 Parent(s): 896c289

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +68 -303
app.py CHANGED
@@ -1,317 +1,82 @@
1
- from fastapi import FastAPI, Request
2
- from fastapi.responses import HTMLResponse
3
  from transformers import pipeline
4
- import uvicorn
5
- from typing import Optional
 
6
 
7
  # Initialize sentiment analysis pipeline
8
  sentiment_analyzer = pipeline("sentiment-analysis", model="distilbert-base-uncased-finetuned-sst-2-english")
9
 
10
- # FastAPI app
11
- app = FastAPI()
12
-
13
- # Function to calculate scores (moved outside the route for reusability)
14
- def calculate_scores_from_logs(logs: list) -> dict:
15
  """
16
- Calculates performance scores from a list of vendor logs.
17
 
18
  Args:
19
- logs (list): A list of vendor log dictionaries.
 
 
 
 
 
 
20
 
21
  Returns:
22
- dict: A dictionary containing the calculated scores and alert flag.
23
  """
24
- quality_score = 0
25
- timeliness_score = 0
26
- safety_score = 0
27
- communication_score = 0
28
- quality_count = 0
29
- delay_count = 0
30
- incident_count = 0
31
- feedback_count = 0
32
-
33
- for log in logs:
34
- log_type = log.get("log_type")
35
- if log_type == "Quality" and "quality_score" in log and log["quality_score"] is not None:
36
- try:
37
- quality_score += float(log["quality_score"])
38
- quality_count += 1
39
- except (ValueError, TypeError):
40
- pass
41
- if log_type == "Delay" and "delay_percentage" in log and log["delay_percentage"] is not None:
42
- try:
43
- timeliness_score += (100 - float(log["delay_percentage"]))
44
- delay_count += 1
45
- except (ValueError, TypeError):
46
- pass
47
- if log_type == "Incident":
48
- safety_score += (100 if log.get("safety_compliance", False) else 0)
49
- incident_count += 1
50
- if "feedback" in log and log["feedback"]:
51
- feedback = log["feedback"]
52
- sentiment = sentiment_analyzer(feedback)[0]
53
- sentiment_score = sentiment["score"] * 100 if sentiment["label"] == "POSITIVE" else 50
54
- base_score = 90 if len(feedback) > 50 else 70
55
- communication_score += base_score * (sentiment_score / 100)
56
- feedback_count += 1
57
-
58
- quality_score = quality_score / quality_count if quality_count > 0 else 0
59
- timeliness_score = timeliness_score / delay_count if delay_count > 0 else 0
60
- safety_score = safety_score / incident_count if incident_count > 0 else 0
61
- communication_score = communication_score / feedback_count if feedback_count > 0 else 0
62
- alert_flag = quality_score < 50 or timeliness_score < 50
63
 
64
- return {
65
- "quality_score": round(quality_score, 2),
66
- "timeliness_score": round(timeliness_score, 2),
67
- "safety_score": round(safety_score, 2),
68
- "communication_score": round(communication_score, 2),
69
- "alert_flag": alert_flag,
70
- }
71
-
72
- @app.post("/calculate_scores")
73
- async def calculate_scores_endpoint(request: Request):
74
- """
75
- Endpoint to receive vendor logs from Salesforce and return calculated scores.
76
- """
77
  try:
78
- logs = await request.json()
79
- scores = calculate_scores_from_logs(logs) # Use the function
80
- return scores
81
- except Exception as e:
82
- return {"error": str(e)}, 400
83
-
84
- @app.get("/")
85
- async def main():
86
- """
87
- Root endpoint to display a user-friendly HTML form for testing.
88
- """
89
- html_content = """
90
- <!DOCTYPE html>
91
- <html lang="en">
92
- <head>
93
- <meta charset="UTF-8">
94
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
95
- <title>Vendor Score Calculator</title>
96
- <style>
97
- body {
98
- font-family: Arial, sans-serif;
99
- margin: 0;
100
- padding: 0;
101
- background-color: #f4f4f4;
102
- display: flex;
103
- justify-content: center;
104
- align-items: center;
105
- min-height: 100vh;
106
- }
107
-
108
- .container {
109
- background-color: #fff;
110
- padding: 20px;
111
- border-radius: 8px;
112
- box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
113
- width: 80%;
114
- max-width: 600px;
115
- }
116
-
117
- h1 {
118
- text-align: center;
119
- color: #333;
120
- }
121
-
122
- form {
123
- margin-top: 20px;
124
- }
125
-
126
- label {
127
- display: block;
128
- margin-bottom: 5px;
129
- color: #555;
130
- }
131
-
132
- input[type="text"], select, textarea {
133
- width: 100%;
134
- padding: 8px 10px;
135
- margin-bottom: 15px;
136
- border: 1px solid #ddd;
137
- border-radius: 4px;
138
- box-sizing: border-box;
139
- }
140
- textarea {
141
- resize: none;
142
- height: 80px;
143
- }
144
-
145
- button[type="submit"] {
146
- background-color: #4caf50;
147
- color: white;
148
- padding: 10px 15px;
149
- border: none;
150
- border-radius: 4px;
151
- cursor: pointer;
152
- width: 100%;
153
- transition: background-color 0.3s ease;
154
- font-size: 16px;
155
- display: block;
156
- margin: 20px auto;
157
-
158
- }
159
-
160
- button[type="submit"]:hover {
161
- background-color: #45a049;
162
- }
163
-
164
- #results {
165
- margin-top: 30px;
166
- padding: 15px;
167
- background-color: #e3e3e3;
168
- border-radius: 4px;
169
- text-align: center;
170
- display: none;
171
- }
172
-
173
- #results h2{
174
- color: #333;
175
- }
176
-
177
- #results p {
178
- margin: 10px 0;
179
- font-size: 18px;
180
- color: #333;
181
- }
182
- #results p strong{
183
- color: #2196f3;
184
- }
185
-
186
- @media screen and (max-width: 768px) {
187
- .container {
188
- width: 95%;
189
- }
190
- }
191
- </style>
192
- </head>
193
- <body>
194
- <div class="container">
195
- <h1>Vendor Performance Score Calculator</h1>
196
- <form id="scoreForm">
197
- <label for="log_type_1">Log Type 1:</label>
198
- <select id="log_type_1" name="log_type_1">
199
- <option value="Quality">Quality</option>
200
- <option value="Delay">Delay</option>
201
- <option value="Incident">Incident</option>
202
- <option value="Communication">Communication</option>
203
- </select>
204
- <input type="text" id="quality_score_1" name="quality_score_1" placeholder="Quality Score (for Quality)">
205
- <input type="text" id="delay_percentage_1" name="delay_percentage_1" placeholder="Delay Percentage (for Delay)">
206
- <label for="safety_compliance_1">Safety Compliance 1:</label>
207
- <select id="safety_compliance_1" name="safety_compliance_1">
208
- <option value="true">Compliant</option>
209
- <option value="false">Non-Compliant</option>
210
- </select>
211
- <textarea id="feedback_1" name="feedback_1" placeholder="Feedback (for Communication)"></textarea>
212
-
213
- <label for="log_type_2">Log Type 2:</label>
214
- <select id="log_type_2" name="log_type_2">
215
- <option value="Quality">Quality</option>
216
- <option value="Delay">Delay</option>
217
- <option value="Incident">Incident</option>
218
- <option value="Communication">Communication</option>
219
- </select>
220
- <input type="text" id="quality_score_2" name="quality_score_2" placeholder="Quality Score (for Quality)">
221
- <input type="text" id="delay_percentage_2" name="delay_percentage_2" placeholder="Delay Percentage (for Delay)">
222
- <label for="safety_compliance_2">Safety Compliance 2:</label>
223
- <select id="safety_compliance_2" name="safety_compliance_2">
224
- <option value="true">Compliant</option>
225
- <option value="false">Non-Compliant</option>
226
- </select>
227
- <textarea id="feedback_2" name="feedback_2" placeholder="Feedback (for Communication)"></textarea>
228
-
229
- <button type="submit">Calculate Scores</button>
230
- </form>
231
-
232
- <div id="results">
233
- <h2>Performance Scores</h2>
234
- <p>Quality Score: <strong id="display_quality_score"></strong></p>
235
- <p>Timeliness Score: <strong id="display_timeliness_score"></strong></p>
236
- <p>Safety Score: <strong id="display_safety_score"></strong></p>
237
- <p>Communication Score: <strong id="display_communication_score"></strong></p>
238
- <p>Alert Flag: <strong id="display_alert_flag"></strong></p>
239
- </div>
240
- </div>
241
-
242
- <script>
243
- document.getElementById('scoreForm').addEventListener('submit', async (event) => {
244
- event.preventDefault();
245
-
246
- const log1_type = document.getElementById('log_type_1').value;
247
- const quality_score_1 = document.getElementById('quality_score_1').value;
248
- const delay_percentage_1 = document.getElementById('delay_percentage_1').value;
249
- const safety_compliance_1 = document.getElementById('safety_compliance_1').value;
250
- const feedback_1 = document.getElementById('feedback_1').value;
251
-
252
- const log2_type = document.getElementById('log_type_2').value;
253
- const quality_score_2 = document.getElementById('quality_score_2').value;
254
- const delay_percentage_2 = document.getElementById('delay_percentage_2').value;
255
- const safety_compliance_2 = document.getElementById('safety_compliance_2').value;
256
- const feedback_2 = document.getElementById('feedback_2').value;
257
-
258
-
259
- const logs = [
260
- {
261
- log_type: log1_type,
262
- quality_score: log1_type === 'Quality' ? quality_score_1 : null,
263
- delay_percentage: log1_type === 'Delay' ? delay_percentage_1 : null,
264
- safety_compliance: log1_type === 'Incident' ? safety_compliance_1 === 'true' : null,
265
- feedback: log1_type === 'Communication' ? feedback_1 : '',
266
- },
267
- {
268
- log_type: log2_type,
269
- quality_score: log2_type === 'Quality' ? quality_score_2 : null,
270
- delay_percentage: log2_type === 'Delay' ? delay_percentage_2 : null,
271
- safety_compliance: log2_type === 'Incident' ? safety_compliance_2 === 'true' : null,
272
- feedback: log2_type === 'Communication' ? feedback_2 : '',
273
- },
274
- ];
275
-
276
- try {
277
- const response = await fetch('/calculate_scores', {
278
- method: 'POST',
279
- headers: {
280
- 'Content-Type': 'application/json',
281
- },
282
- body: JSON.stringify(logs),
283
- });
284
-
285
- if (!response.ok) {
286
- throw new Error(`HTTP error! status: ${response.status}`);
287
- }
288
-
289
- const data = await response.json();
290
-
291
- document.getElementById('display_quality_score').textContent = data.quality_score;
292
- document.getElementById('display_timeliness_score').textContent = data.timeliness_score;
293
- document.getElementById('display_safety_score').textContent = data.safety_score;
294
- document.getElementById('display_communication_score').textContent = data.communication_score;
295
- document.getElementById('display_alert_flag').textContent = data.alert_flag;
296
- document.getElementById('results').style.display = 'block';
297
-
298
- } catch (error) {
299
- alert('Error calculating scores. Check console');
300
- console.error('Error:', error);
301
- }
302
- });
303
- </script>
304
- </body>
305
- </html>
306
- """
307
-
308
-
309
- @app.get("/")
310
- async def main():
311
- """
312
- Root endpoint to display a user-friendly HTML form for testing.
313
- """
314
- return HTMLResponse(content=html_content)
315
-
316
  if __name__ == "__main__":
317
- uvicorn.run(app, host="0.0.0.0", port=7860)
 
1
+ import gradio as gr
 
2
  from transformers import pipeline
3
+ import requests
4
+ import json
5
+ import pandas as pd # Import pandas
6
 
7
  # Initialize sentiment analysis pipeline
8
  sentiment_analyzer = pipeline("sentiment-analysis", model="distilbert-base-uncased-finetuned-sst-2-english")
9
 
10
+ # Function to calculate scores via API call
11
+ def calculate_scores_from_logs(log_type_1, quality_score_1, delay_percentage_1, safety_compliance_1, feedback_1,
12
+ log_type_2, quality_score_2, delay_percentage_2, safety_compliance_2, feedback_2, vendor_id, month):
 
 
13
  """
14
+ Calculates performance scores by calling the Salesforce API.
15
 
16
  Args:
17
+ log_type_1, log_type_2 (str): Type of log (Quality, Delay, Incident, Communication).
18
+ quality_score_1, quality_score_2 (float): Quality score.
19
+ delay_percentage_1, delay_percentage_2 (float): Delay percentage.
20
+ safety_compliance_1, safety_compliance_2 (str): Safety compliance (True/False).
21
+ feedback_1, feedback_2 (str): Feedback text.
22
+ vendor_id (str): Vendor ID.
23
+ month (str): The month for which to calculate scores (YYYY-MM-DD).
24
 
25
  Returns:
26
+ dict: A dictionary containing the calculated scores and alert flag, or an error message.
27
  """
28
+ logs = [
29
+ {
30
+ "log_type": log_type_1,
31
+ "quality_score": float(quality_score_1) if log_type_1 == "Quality" and quality_score_1 else None,
32
+ "delay_percentage": float(delay_percentage_1) if log_type_1 == "Delay" and delay_percentage_1 else None,
33
+ "safety_compliance": safety_compliance_1 == "True" if log_type_1 == "Incident" else None,
34
+ "feedback": feedback_1 if log_type_1 == "Communication" else "",
35
+ },
36
+ {
37
+ "log_type": log_type_2,
38
+ "quality_score": float(quality_score_2) if log_type_2 == "Quality" and quality_score_2 else None,
39
+ "delay_percentage": float(delay_percentage_2) if log_type_2 == "Delay" and delay_percentage_2 else None,
40
+ "safety_compliance": safety_compliance_2 == "True" if log_type_2 == "Incident" else None,
41
+ "feedback": feedback_2 if log_type_2 == "Communication" else "",
42
+ },
43
+ ]
44
+ payload = json.dumps(logs)
45
+ headers = {'Content-Type': 'application/json'}
46
+ # Replace with your Salesforce API endpoint
47
+ salesforce_api_url = f"https://your-salesforce-domain.com/services/apexrest/VendorScoreCalculator?vendorId={vendor_id}&month={month}"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
48
 
 
 
 
 
 
 
 
 
 
 
 
 
 
49
  try:
50
+ response = requests.post(salesforce_api_url, headers=headers, data=payload)
51
+ response.raise_for_status() # Raise HTTPError for bad responses (4xx or 5xx)
52
+ return response.json() # Return the JSON response from Salesforce
53
+ except requests.exceptions.RequestException as e:
54
+ error_message = f"Error calling Salesforce API: {e}"
55
+ print(error_message)
56
+ return {"error": error_message} # Return a user-friendly error message
57
+
58
+ # Gradio Interface
59
+ iface = gr.Interface(
60
+ fn=calculate_scores_from_logs,
61
+ inputs=[
62
+ gr.Dropdown(["Quality", "Delay", "Incident", "Communication"], label="Log Type 1"),
63
+ gr.Number(label="Quality Score 1 (for Quality)"),
64
+ gr.Number(label="Delay Percentage 1 (for Delay)"),
65
+ gr.Radio(["True", "False"], label="Safety Compliance 1 (for Incident)"),
66
+ gr.Textbox(label="Feedback 1 (for Communication)"),
67
+ gr.Dropdown(["Quality", "Delay", "Incident", "Communication"], label="Log Type 2"),
68
+ gr.Number(label="Quality Score 2 (for Quality)"),
69
+ gr.Number(label="Delay Percentage 2 (for Delay)"),
70
+ gr.Radio(["True", "False"], label="Safety Compliance 2 (for Incident)"),
71
+ gr.Textbox(label="Feedback 2 (for Communication)"),
72
+ gr.Textbox(label="Vendor ID", placeholder="Enter Vendor ID"), # Added Vendor ID
73
+ gr.Textbox(label="Month (YYYY-MM-DD)", placeholder="Enter Month (YYYY-MM-DD)"), # Added Month
74
+ ],
75
+ outputs=gr.Label(label="Calculated Scores"),
76
+ title="Vendor Performance Score Calculator",
77
+ description="Calculate vendor performance scores based on log data and Vendor ID/Month."
78
+ )
79
+
80
+ # Run the Gradio interface
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
81
  if __name__ == "__main__":
82
+ iface.launch(server_name="0.0.0.0", server_port=7860)