varshakolanu commited on
Commit
465a073
·
verified ·
1 Parent(s): 7daf73c

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +73 -42
app.py CHANGED
@@ -1,73 +1,87 @@
1
- import gradio as gr
2
- import pandas as pd
3
- import joblib
4
- import numpy as np
5
  from fastapi import FastAPI, HTTPException, Header
6
  from pydantic import BaseModel
7
  from reportlab.lib.pagesizes import letter
8
  from reportlab.pdfgen import canvas
9
  import base64
10
  import os
 
 
 
 
 
 
 
11
 
12
  app = FastAPI()
13
 
14
  # Load API key from environment variable
15
  API_KEY = os.getenv("HUGGINGFACE_API_KEY")
16
  if not API_KEY:
 
17
  raise ValueError("HUGGINGFACE_API_KEY environment variable not set")
18
 
 
 
 
19
  class VendorLog(BaseModel):
20
  vendorLogId: str
21
  vendorId: str
22
- workCompletionPercentage: float
23
- qualityPercentage: float
24
- incidentSeverity: str
25
- delayDays: int
 
 
 
 
 
 
 
 
 
 
 
 
 
 
26
 
27
  def calculate_scores(log: VendorLog):
28
- quality_score = log.qualityPercentage
29
- timeliness_score = 100.0 if log.delayDays == 0 else 80.0 if log.delayDays <= 3 else 60.0 if log.delayDays <= 7 else 40.0
30
- safety_score = 100.0 if log.incidentSeverity == 'None' else 80.0 if log.incidentSeverity == 'Minor' else 50.0 if log.incidentSeverity == 'Major' else 20.0
31
- communication_score = (quality_score + timeliness_score + safety_score) / 3
32
- return {
33
- 'qualityScore': quality_score,
34
- 'timelinessScore': timeliness_score,
35
- 'safetyScore': safety_score,
36
- 'communicationScore': communication_score
37
- }
38
 
39
- def generate_feedback(score: float, metric: str):
40
- if score >= 90:
41
- return 'Excellent: Maintain this standard.'
42
- elif score >= 70:
43
- return 'Good: Continue to improve consistency.'
44
- elif score >= 50:
45
- return f'Needs Improvement: {metric_feedback(metric)}'
46
- else:
47
- return f'Poor: {metric_feedback(metric, True)}'
48
 
49
- def metric_feedback(metric: str, poor: bool = False):
50
- if metric == 'Timeliness':
51
- return 'Significant delays detected; prioritize timely completion.' if poor else 'Maintain schedules to complete tasks on time.'
52
- elif metric == 'Safety':
53
- return 'Critical safety issues; review safety procedures.' if poor else 'Implement stricter safety protocols.'
54
- elif metric == 'Quality':
55
- return 'Low quality output; improve quality control.' if poor else 'Enhance work quality standards.'
56
- else:
57
- return 'Poor communication; improve team interactions.' if poor else 'Enhance coordination with project teams.'
 
 
 
 
58
 
59
  def generate_pdf(vendor_id: str, scores: dict):
60
  filename = f'report_{vendor_id}.pdf'
61
  c = canvas.Canvas(filename, pagesize=letter)
62
  c.setFont('Helvetica', 12)
63
- c.drawString(100, 750, f'Vendor Performance Report')
64
  c.drawString(100, 730, f'Vendor ID: {vendor_id}')
65
  y = 700
66
  for metric, score in scores.items():
67
- feedback = generate_feedback(score, metric.replace('Score', ''))
68
- c.drawString(100, y, f'{metric.replace("Score", " Score")}: {score}% ({feedback})')
69
  y -= 20
70
- c.drawString(100, y, f'Final Score: {sum(scores.values()) / 4}%')
71
  c.save()
72
 
73
  with open(filename, 'rb') as f:
@@ -75,6 +89,14 @@ def generate_pdf(vendor_id: str, scores: dict):
75
  os.remove(filename)
76
  return pdf_content
77
 
 
 
 
 
 
 
 
 
78
  @app.post('/score')
79
  async def score_vendor(log: VendorLog, authorization: str = Header(...)):
80
  if authorization != f'Bearer {API_KEY}':
@@ -83,13 +105,22 @@ async def score_vendor(log: VendorLog, authorization: str = Header(...)):
83
  scores = calculate_scores(log)
84
  pdf_content = generate_pdf(log.vendorId, scores)
85
  pdf_base64 = base64.b64encode(pdf_content).decode('utf-8')
 
86
 
87
  return {
88
  'vendorLogId': log.vendorLogId,
 
 
89
  'qualityScore': scores['qualityScore'],
90
  'timelinessScore': scores['timelinessScore'],
91
  'safetyScore': scores['safetyScore'],
92
  'communicationScore': scores['communicationScore'],
 
93
  'pdfContent': pdf_base64,
94
- 'pdfUrl': f'/files/report_{log.vendorId}.pdf'
95
- }
 
 
 
 
 
 
 
 
 
 
1
  from fastapi import FastAPI, HTTPException, Header
2
  from pydantic import BaseModel
3
  from reportlab.lib.pagesizes import letter
4
  from reportlab.pdfgen import canvas
5
  import base64
6
  import os
7
+ import logging
8
+ from huggingface_hub import InferenceClient
9
+ import numpy as np
10
+
11
+ # Set up logging
12
+ logging.basicConfig(level=logging.INFO)
13
+ logger = logging.getLogger(__name__)
14
 
15
  app = FastAPI()
16
 
17
  # Load API key from environment variable
18
  API_KEY = os.getenv("HUGGINGFACE_API_KEY")
19
  if not API_KEY:
20
+ logger.error("HUGGINGFACE_API_KEY environment variable not set")
21
  raise ValueError("HUGGINGFACE_API_KEY environment variable not set")
22
 
23
+ # Initialize Hugging Face Inference Client
24
+ client = InferenceClient(token=API_KEY)
25
+
26
  class VendorLog(BaseModel):
27
  vendorLogId: str
28
  vendorId: str
29
+ workDetails: str
30
+ workCompletionDate: str # ISO format (e.g., "2025-05-12")
31
+ actualCompletionDate: str # ISO format
32
+ incidentLog: str
33
+ qualityReport: str
34
+ vendorLogName: str
35
+
36
+ def analyze_sentiment(text: str) -> float:
37
+ """Analyze text sentiment using Hugging Face Inference API."""
38
+ try:
39
+ if not text:
40
+ return 50.0 # Neutral score for empty text
41
+ result = client.text_classification(text, model="distilbert-base-uncased-finetuned-sst-2-english")
42
+ score = result[0]['score'] if result[0]['label'] == 'POSITIVE' else 1 - result[0]['score']
43
+ return score * 100 # Convert to percentage
44
+ except Exception as e:
45
+ logger.error(f"Sentiment analysis error: {e}")
46
+ return 50.0 # Fallback score
47
 
48
  def calculate_scores(log: VendorLog):
49
+ # Sentiment analysis for work details, quality report, incident log
50
+ work_completion_score = analyze_sentiment(log.workDetails)
51
+ quality_score = analyze_sentiment(log.qualityReport)
52
+ incident_score = analyze_sentiment(log.incidentLog) if log.incidentLog else 100.0 # No incidents = high score
 
 
 
 
 
 
53
 
54
+ # Timeliness score based on date difference
55
+ from datetime import datetime
56
+ work_date = datetime.fromisoformat(log.workCompletionDate.replace('Z', '+00:00'))
57
+ actual_date = datetime.fromisoformat(log.actualCompletionDate.replace('Z', '+00:00'))
58
+ delay_days = (actual_date - work_date).days
59
+ timeliness_score = 100.0 if delay_days <= 0 else 80.0 if delay_days <= 3 else 60.0 if delay_days <= 7 else 40.0
 
 
 
60
 
61
+ # Safety score (inverse of incident sentiment)
62
+ safety_score = 100.0 - (incident_score if incident_score < 100.0 else 0.0)
63
+
64
+ # Communication score (average of work and quality sentiment)
65
+ communication_score = (work_completion_score + quality_score) / 2
66
+
67
+ return {
68
+ 'qualityScore': round(quality_score, 2),
69
+ 'timelinessScore': round(timeliness_score, 2),
70
+ 'safetyScore': round(safety_score, 2),
71
+ 'communicationScore': round(communication_score, 2),
72
+ 'finalScore': round((quality_score + timeliness_score + safety_score + communication_score) / 4, 2)
73
+ }
74
 
75
  def generate_pdf(vendor_id: str, scores: dict):
76
  filename = f'report_{vendor_id}.pdf'
77
  c = canvas.Canvas(filename, pagesize=letter)
78
  c.setFont('Helvetica', 12)
79
+ c.drawString(100, 750, 'Vendor Performance Report')
80
  c.drawString(100, 730, f'Vendor ID: {vendor_id}')
81
  y = 700
82
  for metric, score in scores.items():
83
+ c.drawString(100, y, f'{metric.replace("Score", " Score")}: {score}%')
 
84
  y -= 20
 
85
  c.save()
86
 
87
  with open(filename, 'rb') as f:
 
89
  os.remove(filename)
90
  return pdf_content
91
 
92
+ def send_alert(vendor_id: str, final_score: float):
93
+ """Placeholder for alert logic (e.g., email or webhook)."""
94
+ if final_score < 50:
95
+ logger.info(f"Alert: Vendor {vendor_id} has low final score ({final_score}%)")
96
+ # Implement email or webhook notification here
97
+ return {"vendorId": vendor_id, "message": f"Low performance score ({final_score}%) detected"}
98
+ return None
99
+
100
  @app.post('/score')
101
  async def score_vendor(log: VendorLog, authorization: str = Header(...)):
102
  if authorization != f'Bearer {API_KEY}':
 
105
  scores = calculate_scores(log)
106
  pdf_content = generate_pdf(log.vendorId, scores)
107
  pdf_base64 = base64.b64encode(pdf_content).decode('utf-8')
108
+ alert = send_alert(log.vendorId, scores['finalScore'])
109
 
110
  return {
111
  'vendorLogId': log.vendorLogId,
112
+ 'vendorId': log.vendorId,
113
+ 'vendorLogName': log.vendorLogName,
114
  'qualityScore': scores['qualityScore'],
115
  'timelinessScore': scores['timelinessScore'],
116
  'safetyScore': scores['safetyScore'],
117
  'communicationScore': scores['communicationScore'],
118
+ 'finalScore': scores['finalScore'],
119
  'pdfContent': pdf_base64,
120
+ 'pdfUrl': f'/files/report_{log.vendorId}.pdf',
121
+ 'alert': alert
122
+ }
123
+
124
+ if __name__ == "__main__":
125
+ import uvicorn
126
+ uvicorn.run(app, host="0.0.0.0", port=7860)