Spaces:
Runtime error
Runtime error
Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,98 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from fastapi import FastAPI, HTTPException
|
2 |
+
from pydantic import BaseModel
|
3 |
+
import simple_salesforce
|
4 |
+
import requests
|
5 |
+
from typing import Optional
|
6 |
+
import os
|
7 |
+
|
8 |
+
app = FastAPI()
|
9 |
+
|
10 |
+
# Salesforce credentials (replace with environment variables in production)
|
11 |
+
SF_USERNAME = "your_salesforce_username" # Replace with your username
|
12 |
+
SF_PASSWORD = "your_salesforce_password" # Replace with your password
|
13 |
+
SF_SECURITY_TOKEN = "BNgBGeH986OPZk0fWxPlIR3Is"
|
14 |
+
SF_INSTANCE_URL = "https://aicoachforsitesupervisors-dev-ed.develop.my.salesforce.com"
|
15 |
+
|
16 |
+
# OpenWeatherMap API key
|
17 |
+
WEATHER_API_KEY = "60c00e1b8293d3c0482f8d6ca1a37003"
|
18 |
+
|
19 |
+
# Pydantic model for request body
|
20 |
+
class ProjectRequest(BaseModel):
|
21 |
+
projectId: str
|
22 |
+
projectName: str
|
23 |
+
milestones: Optional[str] = None
|
24 |
+
weatherLogs: Optional[str] = None
|
25 |
+
safetyLogs: Optional[str] = None
|
26 |
+
role: str
|
27 |
+
|
28 |
+
# Initialize Salesforce connection
|
29 |
+
sf = simple_salesforce.Salesforce(
|
30 |
+
username=SF_USERNAME,
|
31 |
+
password=SF_PASSWORD,
|
32 |
+
security_token=SF_SECURITY_TOKEN,
|
33 |
+
instance_url=SF_INSTANCE_URL
|
34 |
+
)
|
35 |
+
|
36 |
+
def fetch_weather_data(location: str) -> str:
|
37 |
+
"""Fetch weather data for a given location."""
|
38 |
+
try:
|
39 |
+
url = f"http://api.openweathermap.org/data/2.5/weather?q={location}&appid={WEATHER_API_KEY}&units=metric"
|
40 |
+
response = requests.get(url)
|
41 |
+
response.raise_for_status()
|
42 |
+
data = response.json()
|
43 |
+
weather = data['weather'][0]['description']
|
44 |
+
temp = data['main']['temp']
|
45 |
+
return f"{weather}, {temp}°C"
|
46 |
+
except Exception:
|
47 |
+
return "Weather data unavailable"
|
48 |
+
|
49 |
+
def generate_coaching_data(project: dict, role: str) -> dict:
|
50 |
+
"""Mock AI model to generate checklist, tips, and engagement score."""
|
51 |
+
checklist = f"1. Review safety protocols for {project.get('Project_Name__c', 'project')}\n2. Check {role} tasks\n3. Update milestones"
|
52 |
+
tips = f"1. Prioritize safety due to {project.get('Weather_Logs__c', 'conditions')}\n2. Focus on {role} responsibilities\n3. Communicate progress"
|
53 |
+
engagement_score = 85.0 # Mock score; replace with real AI model
|
54 |
+
return {
|
55 |
+
"checklist": checklist,
|
56 |
+
"tips": tips,
|
57 |
+
"engagementScore": engagement_score
|
58 |
+
}
|
59 |
+
|
60 |
+
@app.post("/api/generate")
|
61 |
+
async def generate_coaching(request: ProjectRequest):
|
62 |
+
try:
|
63 |
+
# Query Project__c by Supervisor_ID__c (lookup via role or projectId)
|
64 |
+
query = f"SELECT Id, Name, Project_Name__c, Milestones__c, Weather_Logs__c, Safety_Logs__c, Location__c, Supervisor_ID__c FROM Project__c WHERE Name = '{request.projectId}' LIMIT 1"
|
65 |
+
result = sf.query(query)
|
66 |
+
|
67 |
+
if result['totalSize'] == 0:
|
68 |
+
raise HTTPException(status_code=404, detail="Project not found")
|
69 |
+
|
70 |
+
project = result['records'][0]
|
71 |
+
|
72 |
+
# Update weather logs if location available
|
73 |
+
if project.get('Location__c'):
|
74 |
+
project['Weather_Logs__c'] = fetch_weather_data(project['Location__c'])
|
75 |
+
|
76 |
+
# Generate coaching data
|
77 |
+
coaching_data = generate_coaching_data(project, request.role)
|
78 |
+
|
79 |
+
# Prepare response with extracted fields and generated results
|
80 |
+
response = {
|
81 |
+
"projectId": project['Name'],
|
82 |
+
"projectName": project['Project_Name__c'],
|
83 |
+
"milestones": project.get('Milestones__c', ''),
|
84 |
+
"weatherLogs": project.get('Weather_Logs__c', ''),
|
85 |
+
"safetyLogs": project.get('Safety_Logs__c', ''),
|
86 |
+
"role": request.role,
|
87 |
+
"checklist": coaching_data['checklist'],
|
88 |
+
"tips": coaching_data['tips'],
|
89 |
+
"engagementScore": coaching_data['engagementScore']
|
90 |
+
}
|
91 |
+
|
92 |
+
return response
|
93 |
+
except Exception as e:
|
94 |
+
raise HTTPException(status_code=500, detail=str(e))
|
95 |
+
|
96 |
+
@app.get("/")
|
97 |
+
async def root():
|
98 |
+
return {"message": "Welcome to AI Coach API. Use POST /api/generate"}
|