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