Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,60 +1,33 @@
|
|
| 1 |
|
| 2 |
import gradio as gr
|
| 3 |
-
import logging
|
| 4 |
from transformers import AutoModelForSeq2SeqLM, AutoTokenizer
|
| 5 |
import os
|
| 6 |
from fastapi import FastAPI
|
| 7 |
from pydantic import BaseModel
|
| 8 |
from simple_salesforce import Salesforce
|
| 9 |
from dotenv import load_dotenv
|
| 10 |
-
from datetime import datetime
|
| 11 |
|
| 12 |
# Load environment variables
|
| 13 |
load_dotenv()
|
| 14 |
|
| 15 |
-
# Configure logging
|
| 16 |
-
logging.basicConfig(
|
| 17 |
-
level=logging.INFO,
|
| 18 |
-
format='%(asctime)s - %(levelname)s - %(message)s',
|
| 19 |
-
handlers=[
|
| 20 |
-
logging.FileHandler('app.log'),
|
| 21 |
-
logging.StreamHandler()
|
| 22 |
-
]
|
| 23 |
-
)
|
| 24 |
-
logger = logging.getLogger(__name__)
|
| 25 |
-
|
| 26 |
# Salesforce connection
|
| 27 |
def get_salesforce_connection():
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
)
|
| 35 |
-
logger.info("Salesforce connection established successfully")
|
| 36 |
-
return sf
|
| 37 |
-
except Exception as e:
|
| 38 |
-
logger.error(f"Failed to connect to Salesforce: {str(e)}")
|
| 39 |
-
raise e
|
| 40 |
|
| 41 |
# Load Hugging Face token
|
| 42 |
HF_TOKEN = os.getenv("HF_TOKEN")
|
| 43 |
-
if not HF_TOKEN:
|
| 44 |
-
logger.warning("HF_TOKEN not set. Using public models only.")
|
| 45 |
|
| 46 |
# Model configuration
|
| 47 |
MODEL_PATH = "facebook/bart-large" # Public model
|
| 48 |
# MODEL_PATH = "your_actual_username/fine_tuned_bart_construction" # Uncomment after uploading
|
| 49 |
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
model = AutoModelForSeq2SeqLM.from_pretrained(MODEL_PATH, use_auth_token=HF_TOKEN if HF_TOKEN else None)
|
| 53 |
-
tokenizer = AutoTokenizer.from_pretrained(MODEL_PATH, use_auth_token=HF_TOKEN if HF_TOKEN else None)
|
| 54 |
-
logger.info(f"Model and tokenizer loaded successfully from {MODEL_PATH}")
|
| 55 |
-
except Exception as e:
|
| 56 |
-
logger.error(f"Failed to load model from {MODEL_PATH}: {str(e)}")
|
| 57 |
-
raise e
|
| 58 |
|
| 59 |
# Define input model for FastAPI
|
| 60 |
class ChecklistInput(BaseModel):
|
|
@@ -73,67 +46,52 @@ app = FastAPI()
|
|
| 73 |
|
| 74 |
@app.post("/generate")
|
| 75 |
async def generate_checklist(data: ChecklistInput):
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
'Engagement_Score__c': existing_record.get('Engagement_Score__c', 0) + 10,
|
| 106 |
-
'KPI_Flag__c': kpi_flag,
|
| 107 |
-
'Supervisor_ID__c': data.supervisor_id if data.supervisor_id else existing_record.get('Supervisor_ID__c'),
|
| 108 |
-
'Project_ID__c': data.project_id_sf if data.project_id_sf else existing_record.get('Project_ID__c'),
|
| 109 |
-
'Reflection_Log__c': data.reflection_log if data.reflection_log else existing_record.get('Reflection_Log__c', ''),
|
| 110 |
-
'Download_Link__c': data.download_link if data.download_link else existing_record.get('Download_Link__c', '')
|
| 111 |
-
}
|
| 112 |
-
sf.Supervisor_AI_Coaching__c.update(data.record_id, update_data)
|
| 113 |
-
logger.info(f"Updated Salesforce record {data.record_id} with fields: {update_data}")
|
| 114 |
-
except Exception as sf_e:
|
| 115 |
-
logger.error(f"Failed to update Salesforce: {str(sf_e)}")
|
| 116 |
-
|
| 117 |
-
return {
|
| 118 |
-
"checklist": checklist,
|
| 119 |
-
"tips": tips,
|
| 120 |
-
"kpi_flag": kpi_flag
|
| 121 |
}
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 125 |
|
| 126 |
# Login and display records
|
| 127 |
def login_and_display(project_id_sf):
|
| 128 |
try:
|
| 129 |
-
logger.info(f"Login attempt with Project_ID__c: {project_id_sf}")
|
| 130 |
sf = get_salesforce_connection()
|
| 131 |
query = f"SELECT Id, Name, Supervisor_ID__c, Project_ID__c, Daily_Checklist__c, Suggested_Tips__c, Reflection_Log__c, Engagement_Score__c, KPI_Flag__c, Download_Link__c FROM Supervisor_AI_Coaching__c WHERE Project_ID__c = '{project_id_sf}'"
|
| 132 |
-
logger.info(f"Executing SOQL query: {query}")
|
| 133 |
records = sf.query(query)["records"]
|
| 134 |
if not records:
|
| 135 |
-
|
| 136 |
-
return "No records found for Project ID.", "", False, get_logs()
|
| 137 |
|
| 138 |
output = "Supervisor_AI_Coaching__c Records:\n"
|
| 139 |
for record in records:
|
|
@@ -150,16 +108,13 @@ def login_and_display(project_id_sf):
|
|
| 150 |
f"Download Link: {record['Download_Link__c'] or 'N/A'}\n"
|
| 151 |
f"{'-'*50}\n"
|
| 152 |
)
|
| 153 |
-
|
| 154 |
-
return output, "", False, get_logs()
|
| 155 |
except Exception as e:
|
| 156 |
-
|
| 157 |
-
return f"Error querying Salesforce: {str(e)}", "", False, get_logs()
|
| 158 |
|
| 159 |
# Generate checklist from record
|
| 160 |
def gradio_generate_checklist(record_id, role="Supervisor", project_id="Unknown", project_name="Unknown Project", milestones="No milestones provided", supervisor_id="", project_id_sf="", reflection_log="", download_link=""):
|
| 161 |
try:
|
| 162 |
-
logger.info(f"Generating checklist for record_id: {record_id}")
|
| 163 |
sf = get_salesforce_connection()
|
| 164 |
existing_record = sf.Supervisor_AI_Coaching__c.get(record_id, default={
|
| 165 |
'Name': '',
|
|
@@ -172,15 +127,12 @@ def gradio_generate_checklist(record_id, role="Supervisor", project_id="Unknown"
|
|
| 172 |
'Daily_Checklist__c': '',
|
| 173 |
'Suggested_Tips__c': ''
|
| 174 |
})
|
| 175 |
-
logger.info(f"Fetched record {record_id}: {existing_record}")
|
| 176 |
inputs = f"Role: {role} Project: {project_id} ({project_name}) Milestones: {milestones}"
|
| 177 |
-
logger.info(f"Model input: {inputs[:100]}...")
|
| 178 |
input_ids = tokenizer(inputs, return_tensors="pt", max_length=128, truncation=True).input_ids
|
| 179 |
outputs = model.generate(input_ids, max_length=128, num_beams=4, early_stopping=True)
|
| 180 |
checklist = tokenizer.decode(outputs[0], skip_special_tokens=True)
|
| 181 |
tips = "1. Prioritize safety checks\n2. Review milestones\n3. Log progress"
|
| 182 |
kpi_flag = "delay" in milestones.lower() or "behind" in milestones.lower()
|
| 183 |
-
logger.info(f"Generated checklist: {checklist[:50]}..., tips: {tips[:50]}..., KPI Flag: {kpi_flag}")
|
| 184 |
|
| 185 |
update_data = {
|
| 186 |
'Daily_Checklist__c': checklist,
|
|
@@ -193,23 +145,11 @@ def gradio_generate_checklist(record_id, role="Supervisor", project_id="Unknown"
|
|
| 193 |
'Download_Link__c': download_link if download_link else existing_record.get('Download_Link__c', '')
|
| 194 |
}
|
| 195 |
sf.Supervisor_AI_Coaching__c.update(record_id, update_data)
|
| 196 |
-
|
| 197 |
-
|
| 198 |
-
return checklist, tips, kpi_flag, get_logs()
|
| 199 |
-
except Exception as e:
|
| 200 |
-
logger.error(f"Error generating checklist: {str(e)}")
|
| 201 |
-
return f"Error: {str(e)}", "", False, get_logs()
|
| 202 |
|
| 203 |
-
|
| 204 |
-
def get_logs():
|
| 205 |
-
try:
|
| 206 |
-
with open('app.log', 'r') as f:
|
| 207 |
-
logs = f.read()
|
| 208 |
-
logger.info("Retrieved logs from app.log")
|
| 209 |
-
return logs
|
| 210 |
except Exception as e:
|
| 211 |
-
|
| 212 |
-
return "No logs available."
|
| 213 |
|
| 214 |
# Define Gradio interface
|
| 215 |
with gr.Blocks() as iface:
|
|
@@ -220,11 +160,10 @@ with gr.Blocks() as iface:
|
|
| 220 |
project_id_input = gr.Textbox(label="Project ID (Salesforce Project__c ID)", placeholder="Enter Project ID")
|
| 221 |
login_button = gr.Button("Submit")
|
| 222 |
records_output = gr.Textbox(label="Records", lines=10)
|
| 223 |
-
login_logs = gr.Textbox(label="Logs", lines=5, interactive=False)
|
| 224 |
login_button.click(
|
| 225 |
fn=login_and_display,
|
| 226 |
inputs=project_id_input,
|
| 227 |
-
outputs=[records_output, gr.Textbox(visible=False), gr.Checkbox(visible=False)
|
| 228 |
)
|
| 229 |
|
| 230 |
with gr.Tab("Generate Checklist"):
|
|
@@ -232,7 +171,7 @@ with gr.Blocks() as iface:
|
|
| 232 |
role = gr.Textbox(label="Role", value="Supervisor")
|
| 233 |
project_id = gr.Textbox(label="Project ID", value="P001")
|
| 234 |
project_name = gr.Textbox(label="Project Name", value="Building A")
|
| 235 |
-
milestones = gr.Textbox(label="
|
| 236 |
supervisor_id = gr.Textbox(label="Supervisor ID (Salesforce User ID, optional)", value="")
|
| 237 |
project_id_sf = gr.Textbox(label="Project ID (Salesforce Project__c ID, optional)", value="")
|
| 238 |
reflection_log = gr.Textbox(label="Reflection Log (optional)", value="")
|
|
@@ -241,21 +180,15 @@ with gr.Blocks() as iface:
|
|
| 241 |
checklist_output = gr.Textbox(label="Checklist")
|
| 242 |
tips_output = gr.Textbox(label="Tips")
|
| 243 |
kpi_flag_output = gr.Checkbox(label="KPI Flag")
|
| 244 |
-
|
| 245 |
generate_button.click(
|
| 246 |
fn=gradio_generate_checklist,
|
| 247 |
inputs=[record_id, role, project_id, project_name, milestones, supervisor_id, project_id_sf, reflection_log, download_link],
|
| 248 |
-
outputs=[checklist_output, tips_output, kpi_flag_output,
|
| 249 |
)
|
| 250 |
|
| 251 |
# Mount FastAPI
|
| 252 |
iface.app = app
|
| 253 |
|
| 254 |
if __name__ == "__main__":
|
| 255 |
-
|
| 256 |
-
logger.info("Starting Gradio application")
|
| 257 |
-
iface.launch(server_name="0.0.0.0", server_port=7860, share=False)
|
| 258 |
-
logger.info("Gradio interface launched successfully")
|
| 259 |
-
except Exception as e:
|
| 260 |
-
logger.error(f"Failed to launch Gradio interface: {str(e)}")
|
| 261 |
-
raise e
|
|
|
|
| 1 |
|
| 2 |
import gradio as gr
|
|
|
|
| 3 |
from transformers import AutoModelForSeq2SeqLM, AutoTokenizer
|
| 4 |
import os
|
| 5 |
from fastapi import FastAPI
|
| 6 |
from pydantic import BaseModel
|
| 7 |
from simple_salesforce import Salesforce
|
| 8 |
from dotenv import load_dotenv
|
|
|
|
| 9 |
|
| 10 |
# Load environment variables
|
| 11 |
load_dotenv()
|
| 12 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 13 |
# Salesforce connection
|
| 14 |
def get_salesforce_connection():
|
| 15 |
+
sf = Salesforce(
|
| 16 |
+
username=os.getenv("SF_USERNAME"),
|
| 17 |
+
password=os.getenv("SF_PASSWORD"),
|
| 18 |
+
security_token=os.getenv("SF_SECURITY_TOKEN")
|
| 19 |
+
)
|
| 20 |
+
return sf
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 21 |
|
| 22 |
# Load Hugging Face token
|
| 23 |
HF_TOKEN = os.getenv("HF_TOKEN")
|
|
|
|
|
|
|
| 24 |
|
| 25 |
# Model configuration
|
| 26 |
MODEL_PATH = "facebook/bart-large" # Public model
|
| 27 |
# MODEL_PATH = "your_actual_username/fine_tuned_bart_construction" # Uncomment after uploading
|
| 28 |
|
| 29 |
+
model = AutoModelForSeq2SeqLM.from_pretrained(MODEL_PATH, use_auth_token=HF_TOKEN if HF_TOKEN else None)
|
| 30 |
+
tokenizer = AutoTokenizer.from_pretrained(MODEL_PATH, use_auth_token=HF_TOKEN if HF_TOKEN else None)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 31 |
|
| 32 |
# Define input model for FastAPI
|
| 33 |
class ChecklistInput(BaseModel):
|
|
|
|
| 46 |
|
| 47 |
@app.post("/generate")
|
| 48 |
async def generate_checklist(data: ChecklistInput):
|
| 49 |
+
inputs = f"Role: {data.role} Project: {data.project_id} ({data.project_name}) Milestones: {data.milestones}"
|
| 50 |
+
input_ids = tokenizer(inputs, return_tensors="pt", max_length=128, truncation=True).input_ids
|
| 51 |
+
outputs = model.generate(input_ids, max_length=128, num_beams=4, early_stopping=True)
|
| 52 |
+
checklist = tokenizer.decode(outputs[0], skip_special_tokens=True)
|
| 53 |
+
tips = "1. Prioritize safety checks\n2. Review milestones\n3. Log progress"
|
| 54 |
+
kpi_flag = "delay" in data.milestones.lower() or "behind" in data.milestones.lower()
|
| 55 |
+
|
| 56 |
+
if data.record_id:
|
| 57 |
+
sf = get_salesforce_connection()
|
| 58 |
+
existing_record = sf.Supervisor_AI_Coaching__c.get(data.record_id, default={
|
| 59 |
+
'Name': '',
|
| 60 |
+
'Supervisor_ID__c': None,
|
| 61 |
+
'Project_ID__c': None,
|
| 62 |
+
'Reflection_Log__c': '',
|
| 63 |
+
'Download_Link__c': '',
|
| 64 |
+
'Engagement_Score__c': 0,
|
| 65 |
+
'KPI_Flag__c': False,
|
| 66 |
+
'Daily_Checklist__c': '',
|
| 67 |
+
'Suggested_Tips__c': ''
|
| 68 |
+
})
|
| 69 |
+
update_data = {
|
| 70 |
+
'Daily_Checklist__c': checklist,
|
| 71 |
+
'Suggested_Tips__c': tips,
|
| 72 |
+
'Engagement_Score__c': existing_record.get('Engagement_Score__c', 0) + 10,
|
| 73 |
+
'KPI_Flag__c': kpi_flag,
|
| 74 |
+
'Supervisor_ID__c': data.supervisor_id if data.supervisor_id else existing_record.get('Supervisor_ID__c'),
|
| 75 |
+
'Project_ID__c': data.project_id_sf if data.project_id_sf else existing_record.get('Project_ID__c'),
|
| 76 |
+
'Reflection_Log__c': data.reflection_log if data.reflection_log else existing_record.get('Reflection_Log__c', ''),
|
| 77 |
+
'Download_Link__c': data.download_link if data.download_link else existing_record.get('Download_Link__c', '')
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 78 |
}
|
| 79 |
+
sf.Supervisor_AI_Coaching__c.update(data.record_id, update_data)
|
| 80 |
+
|
| 81 |
+
return {
|
| 82 |
+
"checklist": checklist,
|
| 83 |
+
"tips": tips,
|
| 84 |
+
"kpi_flag": kpi_flag
|
| 85 |
+
}
|
| 86 |
|
| 87 |
# Login and display records
|
| 88 |
def login_and_display(project_id_sf):
|
| 89 |
try:
|
|
|
|
| 90 |
sf = get_salesforce_connection()
|
| 91 |
query = f"SELECT Id, Name, Supervisor_ID__c, Project_ID__c, Daily_Checklist__c, Suggested_Tips__c, Reflection_Log__c, Engagement_Score__c, KPI_Flag__c, Download_Link__c FROM Supervisor_AI_Coaching__c WHERE Project_ID__c = '{project_id_sf}'"
|
|
|
|
| 92 |
records = sf.query(query)["records"]
|
| 93 |
if not records:
|
| 94 |
+
return "No records found for Project ID.", "", False
|
|
|
|
| 95 |
|
| 96 |
output = "Supervisor_AI_Coaching__c Records:\n"
|
| 97 |
for record in records:
|
|
|
|
| 108 |
f"Download Link: {record['Download_Link__c'] or 'N/A'}\n"
|
| 109 |
f"{'-'*50}\n"
|
| 110 |
)
|
| 111 |
+
return output, "", False
|
|
|
|
| 112 |
except Exception as e:
|
| 113 |
+
return f"Error querying Salesforce: {str(e)}", "", False
|
|
|
|
| 114 |
|
| 115 |
# Generate checklist from record
|
| 116 |
def gradio_generate_checklist(record_id, role="Supervisor", project_id="Unknown", project_name="Unknown Project", milestones="No milestones provided", supervisor_id="", project_id_sf="", reflection_log="", download_link=""):
|
| 117 |
try:
|
|
|
|
| 118 |
sf = get_salesforce_connection()
|
| 119 |
existing_record = sf.Supervisor_AI_Coaching__c.get(record_id, default={
|
| 120 |
'Name': '',
|
|
|
|
| 127 |
'Daily_Checklist__c': '',
|
| 128 |
'Suggested_Tips__c': ''
|
| 129 |
})
|
|
|
|
| 130 |
inputs = f"Role: {role} Project: {project_id} ({project_name}) Milestones: {milestones}"
|
|
|
|
| 131 |
input_ids = tokenizer(inputs, return_tensors="pt", max_length=128, truncation=True).input_ids
|
| 132 |
outputs = model.generate(input_ids, max_length=128, num_beams=4, early_stopping=True)
|
| 133 |
checklist = tokenizer.decode(outputs[0], skip_special_tokens=True)
|
| 134 |
tips = "1. Prioritize safety checks\n2. Review milestones\n3. Log progress"
|
| 135 |
kpi_flag = "delay" in milestones.lower() or "behind" in milestones.lower()
|
|
|
|
| 136 |
|
| 137 |
update_data = {
|
| 138 |
'Daily_Checklist__c': checklist,
|
|
|
|
| 145 |
'Download_Link__c': download_link if download_link else existing_record.get('Download_Link__c', '')
|
| 146 |
}
|
| 147 |
sf.Supervisor_AI_Coaching__c.update(record_id, update_data)
|
| 148 |
+
status = f"Updated Salesforce record {record_id}"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 149 |
|
| 150 |
+
return checklist, tips, kpi_flag, status
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 151 |
except Exception as e:
|
| 152 |
+
return f"Error: {str(e)}", "", False, ""
|
|
|
|
| 153 |
|
| 154 |
# Define Gradio interface
|
| 155 |
with gr.Blocks() as iface:
|
|
|
|
| 160 |
project_id_input = gr.Textbox(label="Project ID (Salesforce Project__c ID)", placeholder="Enter Project ID")
|
| 161 |
login_button = gr.Button("Submit")
|
| 162 |
records_output = gr.Textbox(label="Records", lines=10)
|
|
|
|
| 163 |
login_button.click(
|
| 164 |
fn=login_and_display,
|
| 165 |
inputs=project_id_input,
|
| 166 |
+
outputs=[records_output, gr.Textbox(visible=False), gr.Checkbox(visible=False)]
|
| 167 |
)
|
| 168 |
|
| 169 |
with gr.Tab("Generate Checklist"):
|
|
|
|
| 171 |
role = gr.Textbox(label="Role", value="Supervisor")
|
| 172 |
project_id = gr.Textbox(label="Project ID", value="P001")
|
| 173 |
project_name = gr.Textbox(label="Project Name", value="Building A")
|
| 174 |
+
milestones = gr.Textbox(label="Milestones", value="Complete foundation by 5/15")
|
| 175 |
supervisor_id = gr.Textbox(label="Supervisor ID (Salesforce User ID, optional)", value="")
|
| 176 |
project_id_sf = gr.Textbox(label="Project ID (Salesforce Project__c ID, optional)", value="")
|
| 177 |
reflection_log = gr.Textbox(label="Reflection Log (optional)", value="")
|
|
|
|
| 180 |
checklist_output = gr.Textbox(label="Checklist")
|
| 181 |
tips_output = gr.Textbox(label="Tips")
|
| 182 |
kpi_flag_output = gr.Checkbox(label="KPI Flag")
|
| 183 |
+
status_output = gr.Textbox(label="Salesforce Status")
|
| 184 |
generate_button.click(
|
| 185 |
fn=gradio_generate_checklist,
|
| 186 |
inputs=[record_id, role, project_id, project_name, milestones, supervisor_id, project_id_sf, reflection_log, download_link],
|
| 187 |
+
outputs=[checklist_output, tips_output, kpi_flag_output, status_output]
|
| 188 |
)
|
| 189 |
|
| 190 |
# Mount FastAPI
|
| 191 |
iface.app = app
|
| 192 |
|
| 193 |
if __name__ == "__main__":
|
| 194 |
+
iface.launch(server_name="0.0.0.0", server_port=7860, share=False)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|