varshakolanu commited on
Commit
c21dfef
·
verified ·
1 Parent(s): 17aa312

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +86 -50
app.py CHANGED
@@ -2,18 +2,24 @@ import gradio as gr
2
  import pandas as pd
3
  import joblib
4
  import numpy as np
5
- from typing import Dict, Any, List
 
 
 
 
 
 
6
 
7
  # 1. Load the Model and Artifacts
8
  # Model and artifact paths - adjust as necessary
9
- model_path = 'your_model.pkl'
10
  scaler_path = 'scaler.pkl' # If you used a scaler
11
- # encoder_path = 'encoder.pkl' # If you used an encoder
12
 
13
  try:
14
  model = joblib.load(model_path)
15
- scaler = joblib.load(scaler_path) if scaler_path else None # Load scaler
16
- # encoder = joblib.load(encoder_path) if encoder_path else None # Load encoder
17
  except Exception as e:
18
  print(f"Error loading model or artifacts: {e}")
19
  model = None
@@ -39,10 +45,10 @@ def preprocess_data(data: Dict[str, Any]) -> pd.DataFrame:
39
  'Quality_Report__c', # Long Text Area
40
  'Delay_Days__c', # Number
41
  'Incident_Log__c', # Long Text Area
42
- 'Vendor__c', # Lookup (Important: Send the Salesforce ID, not the name)
43
  'Work_Details__c', # Long Text Area
44
- 'Work_Completion_Date__c', # Date
45
- 'Actual_Completion_Date__c' # Date
46
  ]
47
 
48
  # 1. Check for missing fields
@@ -63,7 +69,7 @@ def preprocess_data(data: Dict[str, Any]) -> pd.DataFrame:
63
  df['Work_Completion_Year'] = df['Work_Completion_Date__c'].dt.year
64
  df['Work_Completion_Month'] = df['Work_Completion_Date__c'].dt.month
65
  df['Work_Completion_Day'] = df['Work_Completion_Date__c'].dt.day
66
- df = df.drop(columns=['Work_Completion_Date__c']) #remove original date
67
 
68
  if 'Actual_Completion_Date__c' in df.columns:
69
  df['Actual_Completion_Date__c'] = pd.to_datetime(df['Actual_Completion_Date__c'])
@@ -72,10 +78,10 @@ def preprocess_data(data: Dict[str, Any]) -> pd.DataFrame:
72
  df['Actual_Completion_Day'] = df['Actual_Completion_Date__c'].dt.day
73
  df = df.drop(columns=['Actual_Completion_Date__c'])
74
 
75
- # 4. Text Handling (Example - for long text areas)
76
- # if 'Work_Details__c' in df.columns:
77
- # df['Work_Details__c'] = df['Work_Details__c'].fillna('')
78
- # df['Work_Details_Length'] = df['Work_Details__c'].apply(len) #example feature
79
 
80
  df = df[expected_fields]
81
  return df
@@ -87,26 +93,28 @@ def preprocess_data(data: Dict[str, Any]) -> pd.DataFrame:
87
  return pd.DataFrame()
88
 
89
  # 3. Prediction Function
90
- def predict_vendor_score(*args: Any) -> List[Any]: # Change return type
91
  """
92
  Predicts the vendor performance score based on the input data from Vendor_Log__c.
93
- Returns a dictionary containing the Subcontractor_Performance_Score__c fields.
 
94
 
95
  Args:
96
  *args: Input values from the Gradio interface, in the order matching
97
  the Vendor_Log__c fields.
98
 
99
  Returns:
100
- List[Any]: A list of output values.
101
  """
102
  if model is None:
 
103
  return [
104
- 'Model not loaded. Check server logs.', # Quality Score
105
- 'Model not loaded. Check server logs.', # Timeliness Score
106
- 'Model not loaded. Check server logs.', # Safety Score
107
- 'Model not loaded. Check server logs.', # Communication Score
108
- 'Model not loaded. Check server logs.', # Final Score
109
- ]
110
 
111
  # 1. Prepare input data as a dictionary, mapping to Vendor_Log__c fields
112
  input_data = {
@@ -122,13 +130,14 @@ def predict_vendor_score(*args: Any) -> List[Any]: # Change return type
122
  # 2. Preprocess the data
123
  processed_df = preprocess_data(input_data)
124
  if processed_df.empty:
 
125
  return [
126
- 'Error in input data. Check logs.', # Quality Score
127
- 'Error in input data. Check logs.', # Timeliness Score
128
- 'Error in input data. Check logs.', # Safety Score
129
- 'Error in input data. Check logs.', # Communication Score
130
- 'Error in input data. Check logs.' # Final Score
131
- ]
132
 
133
  # 3. Make Prediction
134
  try:
@@ -139,23 +148,55 @@ def predict_vendor_score(*args: Any) -> List[Any]: # Change return type
139
  # This is a *crucial* step where you tell Gradio how to interpret
140
  # the numbers coming from your model.
141
  output_data = [
142
- predictions[0] * 100, # Quality Score (%)
143
- predictions[1] * 100, # Timeliness Score (%)
144
- predictions[2] * 100, # Safety Score (%)
145
- predictions[3] * 100, # Communication Score (%)
146
- (predictions[0] + predictions[1] + predictions[2] + predictions[3]) / 4 * 100, # Final Score (%)
147
  ]
148
- return output_data
 
149
 
150
  except Exception as e:
 
151
  print(f"Error during prediction: {e}")
152
  return [
153
- f'Error during prediction: {e}', # Quality Score
154
- f'Error during prediction: {e}', # Timeliness Score
155
- f'Error during prediction: {e}', # Safety Score
156
- f'Error during prediction: {e}', # Communication Score
157
- f'Error during prediction: {e}' # Final Score
158
- ]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
159
 
160
  # 4. Gradio Interface
161
  iface = gr.Interface(
@@ -167,21 +208,16 @@ iface = gr.Interface(
167
  gr.Textbox(label="Vendor ID (Text)"), # Send ID
168
  gr.Textbox(label="Work Details (Long Text)", type="text"),
169
  gr.DateTime(label="Work Completion Date", type="datetime"), # Corrected to "datetime"
170
- gr.DateTime(label="Actual Completion Date", type="datetime"), # Corrected to "datetime"
171
  ],
172
- outputs=[ # Changed to a list
173
- gr.HighlightedText(label="Quality Score (%)"),
174
- gr.HighlightedText(label="Timeliness Score (%)"),
175
- gr.HighlightedText(label="Safety Score (%)"),
176
- gr.HighlightedText(label="Communication Score (%)"),
177
- gr.HighlightedText(label="Final Score (%)"),
178
- # "Download_PDF": gr.File(label="Download PDF"), # removed file
179
  ],
180
  title="Subcontractor Performance Score Calculator",
181
- description="Enter Vendor Log details to calculate performance scores.",
182
  )
183
 
184
  # 5. Launch the Interface
185
  if __name__ == "__main__":
186
  iface.launch()
187
-
 
2
  import pandas as pd
3
  import joblib
4
  import numpy as np
5
+ from typing import Dict, Any, List, Tuple
6
+ from reportlab.lib.pagesizes import letter
7
+ from reportlab.pdfgen import canvas
8
+ from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer
9
+ from reportlab.lib.styles import getSampleStyleSheet
10
+ from reportlab.lib.units import inch
11
+ import io # Import the io module
12
 
13
  # 1. Load the Model and Artifacts
14
  # Model and artifact paths - adjust as necessary
15
+ model_path = 'your_model.pkl' # Make sure this path is correct
16
  scaler_path = 'scaler.pkl' # If you used a scaler
17
+ # encoder_path = 'encoder.pkl' # If you used an encoder
18
 
19
  try:
20
  model = joblib.load(model_path)
21
+ scaler = joblib.load(scaler_path) if scaler_path else None
22
+ # encoder = joblib.load(encoder_path) if encoder_path else None
23
  except Exception as e:
24
  print(f"Error loading model or artifacts: {e}")
25
  model = None
 
45
  'Quality_Report__c', # Long Text Area
46
  'Delay_Days__c', # Number
47
  'Incident_Log__c', # Long Text Area
48
+ 'Vendor__c', # Lookup (Important: Send the Salesforce ID, not the name)
49
  'Work_Details__c', # Long Text Area
50
+ 'Work_Completion_Date__c', # Date
51
+ 'Actual_Completion_Date__c' # Date
52
  ]
53
 
54
  # 1. Check for missing fields
 
69
  df['Work_Completion_Year'] = df['Work_Completion_Date__c'].dt.year
70
  df['Work_Completion_Month'] = df['Work_Completion_Date__c'].dt.month
71
  df['Work_Completion_Day'] = df['Work_Completion_Date__c'].dt.day
72
+ df = df.drop(columns=['Work_Completion_Date__c']) # remove original date
73
 
74
  if 'Actual_Completion_Date__c' in df.columns:
75
  df['Actual_Completion_Date__c'] = pd.to_datetime(df['Actual_Completion_Date__c'])
 
78
  df['Actual_Completion_Day'] = df['Actual_Completion_Date__c'].dt.day
79
  df = df.drop(columns=['Actual_Completion_Date__c'])
80
 
81
+ # 4. Text Handling (Example - for long text areas)
82
+ # if 'Work_Details__c' in df.columns:
83
+ # df['Work_Details__c'] = df['Work_Details__c'].fillna('')
84
+ # df['Work_Details_Length'] = df['Work_Details__c'].apply(len) #example feature
85
 
86
  df = df[expected_fields]
87
  return df
 
93
  return pd.DataFrame()
94
 
95
  # 3. Prediction Function
96
+ def predict_vendor_score(*args: Any) -> Tuple[List[Tuple[str, float]], bytes]:
97
  """
98
  Predicts the vendor performance score based on the input data from Vendor_Log__c.
99
+ Returns a list of tuples, where each tuple contains the score name and its value,
100
+ and the PDF data as bytes.
101
 
102
  Args:
103
  *args: Input values from the Gradio interface, in the order matching
104
  the Vendor_Log__c fields.
105
 
106
  Returns:
107
+ Tuple[List[Tuple[str, float]], bytes]: A tuple containing the score data and the PDF data.
108
  """
109
  if model is None:
110
+ error_message = "Model not loaded. Check server logs."
111
  return [
112
+ ("Quality Score (%)", 0.0),
113
+ ("Timeliness Score (%)", 0.0),
114
+ ("Safety Score (%)", 0.0),
115
+ ("Communication Score (%)", 0.0),
116
+ ("Final Score (%)", 0.0),
117
+ ], generate_pdf(error_message)
118
 
119
  # 1. Prepare input data as a dictionary, mapping to Vendor_Log__c fields
120
  input_data = {
 
130
  # 2. Preprocess the data
131
  processed_df = preprocess_data(input_data)
132
  if processed_df.empty:
133
+ error_message = "Error in input data. Check logs."
134
  return [
135
+ ("Quality Score (%)", 0.0),
136
+ ("Timeliness Score (%)", 0.0),
137
+ ("Safety Score (%)", 0.0),
138
+ ("Communication Score (%)", 0.0),
139
+ ("Final Score (%)", 0.0),
140
+ ], generate_pdf(error_message) # Return empty PDF
141
 
142
  # 3. Make Prediction
143
  try:
 
148
  # This is a *crucial* step where you tell Gradio how to interpret
149
  # the numbers coming from your model.
150
  output_data = [
151
+ ("Quality Score (%)", predictions[0] * 100),
152
+ ("Timeliness Score (%)", predictions[1] * 100),
153
+ ("Safety Score (%)", predictions[2] * 100),
154
+ ("Communication Score (%)", predictions[3] * 100),
155
+ ("Final Score (%)", (predictions[0] + predictions[1] + predictions[2] + predictions[3]) / 4 * 100),
156
  ]
157
+ pdf_data = generate_pdf(output_data)
158
+ return output_data, pdf_data
159
 
160
  except Exception as e:
161
+ error_message = f"Error during prediction: {e}"
162
  print(f"Error during prediction: {e}")
163
  return [
164
+ ("Quality Score (%)", 0.0),
165
+ ("Timeliness Score (%)", 0.0),
166
+ ("Safety Score (%)", 0.0),
167
+ ("Communication Score (%)", 0.0),
168
+ ("Final Score (%)", 0.0),
169
+ ], generate_pdf(error_message)
170
+
171
+ def generate_pdf(scores: List[Tuple[str, float]]) -> bytes:
172
+ """Generates a PDF report of the subcontractor performance scores.
173
+
174
+ Args:
175
+ scores (List[Tuple[str, float]]): A list of (score_name, score_value) tuples.
176
+ Returns:
177
+ bytes: The PDF data as bytes.
178
+ """
179
+ buffer = io.BytesIO() # Use BytesIO for in-memory PDF generation
180
+ doc = SimpleDocTemplate(buffer, pagesize=letter)
181
+ styles = getSampleStyleSheet()
182
+ Story = []
183
+
184
+ # Add a title
185
+ Story.append(Paragraph("Subcontractor Performance Report", styles['Title']))
186
+ Story.append(Spacer(1, 0.2 * inch))
187
+
188
+ if isinstance(scores, str): # Check if it is an error message
189
+ Story.append(Paragraph(scores, styles['Normal']))
190
+ else:
191
+ # Add the scores to the PDF
192
+ for score_name, score_value in scores:
193
+ Story.append(Paragraph(f"{score_name}: {score_value:.2f}", styles['Normal']))
194
+ Story.append(Spacer(1, 0.1 * inch))
195
+
196
+ doc.build(Story)
197
+ pdf_data = buffer.getvalue()
198
+ buffer.close()
199
+ return pdf_data
200
 
201
  # 4. Gradio Interface
202
  iface = gr.Interface(
 
208
  gr.Textbox(label="Vendor ID (Text)"), # Send ID
209
  gr.Textbox(label="Work Details (Long Text)", type="text"),
210
  gr.DateTime(label="Work Completion Date", type="datetime"), # Corrected to "datetime"
211
+ gr.DateTime(label="Actual Completion Date", type="datetime"), # Corrected to "datetime"
212
  ],
213
+ outputs=[ # Changed to a list
214
+ gr.HighlightedText(label="Performance Scores"),
215
+ gr.File(label="Download PDF Report"),
 
 
 
 
216
  ],
217
  title="Subcontractor Performance Score Calculator",
218
+ description="Enter Vendor Log details to calculate performance scores and generate a PDF report.",
219
  )
220
 
221
  # 5. Launch the Interface
222
  if __name__ == "__main__":
223
  iface.launch()