Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -9,6 +9,7 @@ from datetime import datetime
|
|
| 9 |
from fastapi.responses import HTMLResponse
|
| 10 |
from simple_salesforce import Salesforce
|
| 11 |
from dotenv import load_dotenv
|
|
|
|
| 12 |
|
| 13 |
# Load environment variables
|
| 14 |
load_dotenv()
|
|
@@ -68,6 +69,24 @@ class VendorLog(BaseModel):
|
|
| 68 |
# Store vendor logs
|
| 69 |
vendor_logs = []
|
| 70 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 71 |
def validate_salesforce_fields():
|
| 72 |
"""Validate required Salesforce fields"""
|
| 73 |
try:
|
|
@@ -85,7 +104,8 @@ def validate_salesforce_fields():
|
|
| 85 |
score_fields = [f['name'] for f in sf.Subcontractor_Performance_Score__c.describe()['fields']]
|
| 86 |
required_score_fields = [
|
| 87 |
'Vendor__c', 'Month__c', 'Quality_Score__c', 'Timeliness_Score__c',
|
| 88 |
-
'Safety_Score__c', 'Communication_Score__c', 'Alert_Flag__c'
|
|
|
|
| 89 |
]
|
| 90 |
for field in required_score_fields:
|
| 91 |
if field not in score_fields:
|
|
@@ -156,8 +176,12 @@ def calculate_scores_local(log: VendorLog):
|
|
| 156 |
return {'qualityScore': 0.0, 'timelinessScore': 0.0, 'safetyScore': 0.0, 'communicationScore': 0.0}
|
| 157 |
|
| 158 |
def calculate_scores(log: VendorLog):
|
| 159 |
-
|
| 160 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 161 |
|
| 162 |
def get_feedback(score: float, metric: str) -> str:
|
| 163 |
try:
|
|
@@ -235,8 +259,9 @@ def store_scores_in_salesforce(log: VendorLog, scores: dict, pdf_content: bytes,
|
|
| 235 |
content_document_id = content_version_record['records'][0]['ContentDocumentId']
|
| 236 |
pdf_url = f"https://{sf.sf_instance}/sfc/servlet.shepherd/document/download/{content_document_id}"
|
| 237 |
|
| 238 |
-
|
| 239 |
-
|
|
|
|
| 240 |
except Exception as e:
|
| 241 |
logger.error(f"Error storing scores in Salesforce: {str(e)}")
|
| 242 |
raise HTTPException(status_code=500, detail="Failed to store scores")
|
|
@@ -466,18 +491,32 @@ async def debug_info():
|
|
| 466 |
log_count = sf.query("SELECT COUNT() FROM Vendor_Log__c")['totalSize']
|
| 467 |
fields = [f['name'] for f in sf.Vendor_Log__c.describe()['fields']]
|
| 468 |
score_fields = [f['name'] for f in sf.Subcontractor_Performance_Score__c.describe()['fields']]
|
|
|
|
|
|
|
| 469 |
return {
|
| 470 |
"salesforce_connected": True,
|
| 471 |
"vendor_log_count": log_count,
|
| 472 |
"vendor_log_fields": fields,
|
| 473 |
"score_fields": score_fields,
|
| 474 |
-
"huggingface_enabled": USE_HUGGINGFACE
|
|
|
|
| 475 |
}
|
| 476 |
except Exception as e:
|
| 477 |
logger.error(f"Debug error: {str(e)}")
|
| 478 |
return {"salesforce_connected": False, "error": str(e)}
|
| 479 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 480 |
if __name__ == "__main__":
|
| 481 |
import uvicorn
|
| 482 |
uvicorn.run(app, host="0.0.0.0", port=7860)
|
| 483 |
-
|
|
|
|
| 9 |
from fastapi.responses import HTMLResponse
|
| 10 |
from simple_salesforce import Salesforce
|
| 11 |
from dotenv import load_dotenv
|
| 12 |
+
from datasets import load_dataset # Added for Hugging Face
|
| 13 |
|
| 14 |
# Load environment variables
|
| 15 |
load_dotenv()
|
|
|
|
| 69 |
# Store vendor logs
|
| 70 |
vendor_logs = []
|
| 71 |
|
| 72 |
+
# New function to fetch records from Hugging Face
|
| 73 |
+
def fetch_huggingface_records(dataset_name: str = "imdb"):
|
| 74 |
+
"""Fetch a dataset from Hugging Face and return its records."""
|
| 75 |
+
if not USE_HUGGINGFACE:
|
| 76 |
+
logger.warning("Hugging Face integration is disabled. Cannot fetch records.")
|
| 77 |
+
return []
|
| 78 |
+
try:
|
| 79 |
+
# Set Hugging Face token for authentication
|
| 80 |
+
os.environ["HUGGINGFACE_TOKEN"] = HUGGINGFACE_API_KEY
|
| 81 |
+
dataset = load_dataset(dataset_name)
|
| 82 |
+
logger.info(f"Successfully fetched dataset: {dataset_name}")
|
| 83 |
+
# Example: Convert dataset to a list of records (adjust based on dataset structure)
|
| 84 |
+
records = [record for record in dataset['train']] # Assuming 'train' split
|
| 85 |
+
return records[:10] # Limit to 10 records for demonstration
|
| 86 |
+
except Exception as e:
|
| 87 |
+
logger.error(f"Error fetching Hugging Face dataset {dataset_name}: {str(e)}")
|
| 88 |
+
return []
|
| 89 |
+
|
| 90 |
def validate_salesforce_fields():
|
| 91 |
"""Validate required Salesforce fields"""
|
| 92 |
try:
|
|
|
|
| 104 |
score_fields = [f['name'] for f in sf.Subcontractor_Performance_Score__c.describe()['fields']]
|
| 105 |
required_score_fields = [
|
| 106 |
'Vendor__c', 'Month__c', 'Quality_Score__c', 'Timeliness_Score__c',
|
| 107 |
+
'Safety_Score__c', 'Communication_Score__c', 'Alert_Flag__c'
|
| 108 |
+
# Removed 'Certification_URL__c' to avoid error
|
| 109 |
]
|
| 110 |
for field in required_score_fields:
|
| 111 |
if field not in score_fields:
|
|
|
|
| 176 |
return {'qualityScore': 0.0, 'timelinessScore': 0.0, 'safetyScore': 0.0, 'communicationScore': 0.0}
|
| 177 |
|
| 178 |
def calculate_scores(log: VendorLog):
|
| 179 |
+
if USE_HUGGINGFACE:
|
| 180 |
+
# Example: Use Hugging Face model for score enhancement (placeholder)
|
| 181 |
+
logger.info("Using Hugging Face for score calculation (placeholder)")
|
| 182 |
+
return calculate_scores_local(log) # Replace with actual Hugging Face logic if needed
|
| 183 |
+
else:
|
| 184 |
+
return calculate_scores_local(log)
|
| 185 |
|
| 186 |
def get_feedback(score: float, metric: str) -> str:
|
| 187 |
try:
|
|
|
|
| 259 |
content_document_id = content_version_record['records'][0]['ContentDocumentId']
|
| 260 |
pdf_url = f"https://{sf.sf_instance}/sfc/servlet.shepherd/document/download/{content_document_id}"
|
| 261 |
|
| 262 |
+
# Comment out Certification_URL__c update to avoid error
|
| 263 |
+
# sf.Subcontractor_Performance_Score__c.update(score_record_id, {'Certification_URL__c': pdf_url})
|
| 264 |
+
logger.info(f"Updated score record with PDF (URL not stored due to missing field)")
|
| 265 |
except Exception as e:
|
| 266 |
logger.error(f"Error storing scores in Salesforce: {str(e)}")
|
| 267 |
raise HTTPException(status_code=500, detail="Failed to store scores")
|
|
|
|
| 491 |
log_count = sf.query("SELECT COUNT() FROM Vendor_Log__c")['totalSize']
|
| 492 |
fields = [f['name'] for f in sf.Vendor_Log__c.describe()['fields']]
|
| 493 |
score_fields = [f['name'] for f in sf.Subcontractor_Performance_Score__c.describe()['fields']]
|
| 494 |
+
# Fetch sample Hugging Face records for debugging
|
| 495 |
+
hf_records = fetch_huggingface_records() if USE_HUGGINGFACE else []
|
| 496 |
return {
|
| 497 |
"salesforce_connected": True,
|
| 498 |
"vendor_log_count": log_count,
|
| 499 |
"vendor_log_fields": fields,
|
| 500 |
"score_fields": score_fields,
|
| 501 |
+
"huggingface_enabled": USE_HUGGINGFACE,
|
| 502 |
+
"huggingface_records_sample": hf_records
|
| 503 |
}
|
| 504 |
except Exception as e:
|
| 505 |
logger.error(f"Debug error: {str(e)}")
|
| 506 |
return {"salesforce_connected": False, "error": str(e)}
|
| 507 |
|
| 508 |
+
@app.get('/huggingface-records')
|
| 509 |
+
async def get_huggingface_records():
|
| 510 |
+
"""New endpoint to fetch and return Hugging Face records."""
|
| 511 |
+
try:
|
| 512 |
+
records = fetch_huggingface_records()
|
| 513 |
+
if not records:
|
| 514 |
+
raise HTTPException(status_code=404, detail="No records fetched from Hugging Face")
|
| 515 |
+
return {"records": records}
|
| 516 |
+
except Exception as e:
|
| 517 |
+
logger.error(f"Error fetching Hugging Face records: {str(e)}")
|
| 518 |
+
raise HTTPException(status_code=500, detail=f"Failed to fetch Hugging Face records: {str(e)}")
|
| 519 |
+
|
| 520 |
if __name__ == "__main__":
|
| 521 |
import uvicorn
|
| 522 |
uvicorn.run(app, host="0.0.0.0", port=7860)
|
|
|