Dineshpopuri commited on
Commit
6f29b2c
·
verified ·
1 Parent(s): cfac319

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +47 -23
app.py CHANGED
@@ -10,6 +10,7 @@ from retry import retry
10
  import time
11
  from datetime import datetime
12
  import base64
 
13
 
14
  # Print statement to confirm script initialization
15
  print("Starting Project Closure Readiness Evaluator app...")
@@ -24,9 +25,11 @@ formatter = logging.Formatter("%(asctime)s - %(levelname)s - %(message)s")
24
  console_handler.setFormatter(formatter)
25
  logger.addHandler(console_handler)
26
 
27
- # Attempt to import Salesforce library with fallback
 
28
  try:
29
- from simple_salesforce import Salesforce, SalesforceError
 
30
  SALESFORCE_AVAILABLE = True
31
  except ImportError as e:
32
  logging.error(f"Failed to import simple-salesforce: {str(e)}. Salesforce functionality will be disabled.")
@@ -57,7 +60,12 @@ if not HF_API_TOKEN:
57
  HF_AVAILABLE = False
58
  else:
59
  HF_AVAILABLE = True
60
- hf_client = InferenceClient(token=HF_API_TOKEN)
 
 
 
 
 
61
 
62
  # Initialize Salesforce connection with retry mechanism
63
  @retry(tries=3, delay=2, backoff=2, logger=logger)
@@ -70,7 +78,7 @@ def init_salesforce():
70
  logging.info("Attempting to connect to Salesforce with the following credentials:")
71
  logging.info(f"Username: {SF_USERNAME}")
72
  logging.info(f"Instance URL: {SF_INSTANCE_URL}")
73
- sf = Salesforce(
74
  username=SF_USERNAME,
75
  password=SF_PASSWORD,
76
  security_token=SF_SECURITY_TOKEN,
@@ -80,11 +88,11 @@ def init_salesforce():
80
  # Test read access on Project_Closure_Handover__c
81
  test_query = sf.query("SELECT Id FROM Project_Closure_Handover__c LIMIT 1")
82
  logging.info(f"Test query result (read access): {test_query}")
83
- # Test create access by attempting to describe the object and check permissions
84
  object_description = sf.Project_Closure_Handover__c.describe()
85
  logging.info(f"Object description: {object_description}")
86
  return sf, "Salesforce connected successfully"
87
- except SalesforceError as e:
88
  logging.error(f"Salesforce authentication failed: {str(e)}")
89
  logging.error("Possible issues: Incorrect credentials, IP restrictions, or insufficient permissions.")
90
  raise
@@ -117,7 +125,7 @@ def summarize_text(text, max_length=100, min_length=30):
117
  def create_salesforce_record(score, checklist_summary, missing_summary, status, escalated, logs, qa_report, punch_list_text, open_punch_items, pdf_path=None):
118
  if not SALESFORCE_AVAILABLE:
119
  logging.error("Salesforce library not available. Skipping record creation.")
120
- return "Salesforce library not available"
121
 
122
  try:
123
  sf, connection_message = init_salesforce()
@@ -209,7 +217,7 @@ def create_salesforce_record(score, checklist_summary, missing_summary, status,
209
  logging.warning(f"No PDF file found at {pdf_path}. Skipping attachment and URL update.")
210
 
211
  return f"Record created successfully. Record ID: {record_id}. PDF attached and URL set to: {pdf_download_url}. Project ID: {project_id}"
212
- except SalesforceError as e:
213
  logging.error(f"Salesforce error while creating Project_Closure_Handover__c record: {str(e)}")
214
  logging.error("Possible issues: Object permissions, field-level security, validation rules, or required fields.")
215
  logging.error("Check the following in your Salesforce org:")
@@ -377,7 +385,7 @@ def generate_pdf(score, checklist_summary, missing_summary, checklist_status, lo
377
  return pdf_path, "PDF generation completed. Click the link to download."
378
  except Exception as e:
379
  logging.error(f"Error in generate_pdf: {str(e)}")
380
- raise
381
 
382
  # Gradio interface with updated UI
383
  with gr.Blocks(css="""
@@ -422,25 +430,41 @@ with gr.Blocks(css="""
422
  pdf_output = gr.File(label="Download PDF Report", type="filepath", interactive=False)
423
  pdf_debug = gr.Textbox(label="PDF Debug Output")
424
  salesforce_output = gr.Textbox(label="Salesforce Save Status")
 
425
 
426
  # Chain the evaluation, PDF generation, and Salesforce record creation
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
427
  submit_btn.click(
428
- fn=evaluate_readiness,
429
  inputs=[logs_input, qa_input, punch_input],
430
  outputs=[
431
  score_output, checklist_output, missing_output, status_output, progress_output,
432
- gr.State(), gr.State(), gr.State(), gr.State(), open_punch_items_output, status_output
 
433
  ]
434
- ).then(
435
- fn=generate_pdf,
436
- inputs=[score_output, checklist_output, missing_output, status_output, gr.State(), gr.State(), gr.State()],
437
- outputs=[pdf_output, pdf_debug]
438
- ).then(
439
- fn=create_salesforce_record,
440
- inputs=[
441
- score_output, checklist_output, missing_summary, status_output,
442
- gr.State(), gr.State(), gr.State(), gr.State(), open_punch_items_output, pdf_output
443
- ],
444
- outputs=[salesforce_output]
445
  )
446
- demo.launch()
 
 
 
 
10
  import time
11
  from datetime import datetime
12
  import base64
13
+ import sys
14
 
15
  # Print statement to confirm script initialization
16
  print("Starting Project Closure Readiness Evaluator app...")
 
25
  console_handler.setFormatter(formatter)
26
  logger.addHandler(console_handler)
27
 
28
+ # Check Python version and dependencies
29
+ logging.info(f"Python version: {sys.version}")
30
  try:
31
+ import simple_salesforce
32
+ logging.info(f"simple-salesforce version: {simple_salesforce.__version__}")
33
  SALESFORCE_AVAILABLE = True
34
  except ImportError as e:
35
  logging.error(f"Failed to import simple-salesforce: {str(e)}. Salesforce functionality will be disabled.")
 
60
  HF_AVAILABLE = False
61
  else:
62
  HF_AVAILABLE = True
63
+ try:
64
+ hf_client = InferenceClient(token=HF_API_TOKEN)
65
+ logging.info("Hugging Face InferenceClient initialized successfully")
66
+ except Exception as e:
67
+ logging.error(f"Failed to initialize Hugging Face InferenceClient: {str(e)}")
68
+ HF_AVAILABLE = False
69
 
70
  # Initialize Salesforce connection with retry mechanism
71
  @retry(tries=3, delay=2, backoff=2, logger=logger)
 
78
  logging.info("Attempting to connect to Salesforce with the following credentials:")
79
  logging.info(f"Username: {SF_USERNAME}")
80
  logging.info(f"Instance URL: {SF_INSTANCE_URL}")
81
+ sf = simple_salesforce.Salesforce(
82
  username=SF_USERNAME,
83
  password=SF_PASSWORD,
84
  security_token=SF_SECURITY_TOKEN,
 
88
  # Test read access on Project_Closure_Handover__c
89
  test_query = sf.query("SELECT Id FROM Project_Closure_Handover__c LIMIT 1")
90
  logging.info(f"Test query result (read access): {test_query}")
91
+ # Test create access by attempting to describe the object
92
  object_description = sf.Project_Closure_Handover__c.describe()
93
  logging.info(f"Object description: {object_description}")
94
  return sf, "Salesforce connected successfully"
95
+ except simple_salesforce.SalesforceError as e:
96
  logging.error(f"Salesforce authentication failed: {str(e)}")
97
  logging.error("Possible issues: Incorrect credentials, IP restrictions, or insufficient permissions.")
98
  raise
 
125
  def create_salesforce_record(score, checklist_summary, missing_summary, status, escalated, logs, qa_report, punch_list_text, open_punch_items, pdf_path=None):
126
  if not SALESFORCE_AVAILABLE:
127
  logging.error("Salesforce library not available. Skipping record creation.")
128
+ return "Salesforce library not available. Ensure 'simple-salesforce' is installed."
129
 
130
  try:
131
  sf, connection_message = init_salesforce()
 
217
  logging.warning(f"No PDF file found at {pdf_path}. Skipping attachment and URL update.")
218
 
219
  return f"Record created successfully. Record ID: {record_id}. PDF attached and URL set to: {pdf_download_url}. Project ID: {project_id}"
220
+ except simple_salesforce.SalesforceError as e:
221
  logging.error(f"Salesforce error while creating Project_Closure_Handover__c record: {str(e)}")
222
  logging.error("Possible issues: Object permissions, field-level security, validation rules, or required fields.")
223
  logging.error("Check the following in your Salesforce org:")
 
385
  return pdf_path, "PDF generation completed. Click the link to download."
386
  except Exception as e:
387
  logging.error(f"Error in generate_pdf: {str(e)}")
388
+ return None, f"Error generating PDF: {str(e)}"
389
 
390
  # Gradio interface with updated UI
391
  with gr.Blocks(css="""
 
430
  pdf_output = gr.File(label="Download PDF Report", type="filepath", interactive=False)
431
  pdf_debug = gr.Textbox(label="PDF Debug Output")
432
  salesforce_output = gr.Textbox(label="Salesforce Save Status")
433
+ error_output = gr.Textbox(label="Error Details (if any)")
434
 
435
  # Chain the evaluation, PDF generation, and Salesforce record creation
436
+ def handle_submission(logs, qa_report, punch_list_text):
437
+ try:
438
+ # Evaluate readiness
439
+ result = evaluate_readiness(logs, qa_report, punch_list_text)
440
+ score, checklist_summary, missing_summary, status, progress_bar, escalated, logs, qa_report, punch_list_text, open_punch_items, checklist_status = result
441
+
442
+ # Generate PDF
443
+ pdf_path, pdf_message = generate_pdf(score, checklist_summary, missing_summary, checklist_status, logs, qa_report, punch_list_text)
444
+
445
+ # Save to Salesforce
446
+ salesforce_message = create_salesforce_record(
447
+ score, checklist_summary, missing_summary, status, escalated, logs, qa_report, punch_list_text, open_punch_items, pdf_path
448
+ )
449
+
450
+ return [
451
+ score, checklist_summary, missing_summary, status, progress_bar, escalated, logs, qa_report, punch_list_text, open_punch_items, checklist_status,
452
+ pdf_path, pdf_message, salesforce_message, ""
453
+ ]
454
+ except Exception as e:
455
+ logging.error(f"Submission error: {str(e)}")
456
+ return [None, None, None, None, None, None, None, None, None, None, None, None, None, f"Error: {str(e)}"]
457
+
458
  submit_btn.click(
459
+ fn=handle_submission,
460
  inputs=[logs_input, qa_input, punch_input],
461
  outputs=[
462
  score_output, checklist_output, missing_output, status_output, progress_output,
463
+ gr.State(), gr.State(), gr.State(), gr.State(), open_punch_items_output, status_output,
464
+ pdf_output, pdf_debug, salesforce_output, error_output
465
  ]
 
 
 
 
 
 
 
 
 
 
 
466
  )
467
+
468
+ if __name__ == "__main__":
469
+ try:
470
+ demo.launch()