Spaces:
Sleeping
Sleeping
Update app.py
Browse files6 unmodified lines789101112131415161718192021222324252627282930313257 unmodified lines909192739394759596779798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291302 unmodified lines133134135881361371381391401411421431441451466 unmodified lines1531541551071561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042051091102062072082092102112122132141152152161171182172182192201211222212222232242256 unmodified linesfrom reportlab.platypus import SimpleDocTemplate, Paragraph, Spacerfrom reportlab.lib.styles import getSampleStyleSheet, ParagraphStylefrom reportlab.lib import colorsfrom simple_salesforce import Salesforceimport osfrom dotenv import load_dotenvimport base64import io
# Load environment variables from .env fileload_dotenv()
# Salesforce credentialsSF_USERNAME = os.getenv('SF_USERNAME')SF_PASSWORD = os.getenv('SF_PASSWORD')SF_SECURITY_TOKEN = os.getenv('SF_SECURITY_TOKEN')
# Initialize Salesforce connectiontry: sf = Salesforce(username=SF_USERNAME, password=SF_PASSWORD, security_token=SF_SECURITY_TOKEN)except Exception as e: sf = None print(f"Failed to connect to Salesforce: {str(e)}")
# Load BLIP model and processorprocessor = BlipProcessor.from_pretrained("Salesforce/blip-image-captioning-base")57 unmodified lines # Build the PDF doc.build(flowables) return f"PDF saved successfully as {filename}" return f"PDF saved successfully as {filename}", filename except Exception as e: return f"Error saving PDF: {str(e)}" return f"Error saving PDF: {str(e)}", None
# Function to generate the daily progress report (DPR) text and save as PDF# Function to upload a file to Salesforce as ContentVersiondef upload_file_to_salesforce(file_path, filename, sf_connection, field_name): try: # Read file content and encode in base64 with open(file_path, 'rb') as f: file_content = f.read() file_content_b64 = base64.b64encode(file_content).decode('utf-8') # Create ContentVersion content_version = sf_connection.ContentVersion.create({ 'Title': filename, 'PathOnClient': filename, 'VersionData': file_content_b64, 'Description': f'Uploaded for {field_name}' }) # Get ContentDocumentId content_version_id = content_version['id'] content_document = sf_connection.query( f"SELECT ContentDocumentId FROM ContentVersion WHERE Id = '{content_version_id}'" ) content_document_id = content_document['records'][0]['ContentDocumentId'] return content_document_id, f"File {filename} uploaded successfully for {field_name}" except Exception as e: return None, f"Error uploading {filename} to Salesforce for {field_name}: {str(e)}"
# Function to generate the daily progress report (DPR), save as PDF, and upload to Salesforcedef generate_dpr(files): dpr_text = [] captions = [] current_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S") # Add header to the DPR2 unmodified lines # Process each uploaded file (image) for file in files: # Open the image from file path image = Image.open(file.name) # Using file.name for filepath image = Image.open(file.name) if image.mode != "RGB": image = image.convert("RGB") # Dynamically generate a caption based on the image caption = generate_captions_from_image(image) captions.append(caption) # Generate DPR section for this image with dynamic caption dpr_section = f"\nImage: {file.name}\nDescription: {caption}\n"6 unmodified lines pdf_filename = f"DPR_{datetime.now().strftime('%Y-%m-%d_%H-%M-%S')}.pdf" # Save DPR text to PDF pdf_result = save_dpr_to_pdf(dpr_output, pdf_filename) pdf_result, pdf_filepath = save_dpr_to_pdf(dpr_output, pdf_filename) # Salesforce upload salesforce_result = "" if sf and pdf_filepath: try: # Create Daily_Progress_Reports__c record report_description = "; ".join(captions)[:255] # Concatenate captions, limit to 255 chars dpr_record = sf.Daily_Progress_Reports__c.create({ 'Report_Date__c': current_time, 'Report_Description__c': report_description }) dpr_record_id = dpr_record['id'] salesforce_result += f"Created Daily_Progress_Reports__c record with ID: {dpr_record_id}\n" # Upload PDF to Salesforce for Report_PDF__c pdf_content_document_id, pdf_upload_result = upload_file_to_salesforce( pdf_filepath, pdf_filename, sf, 'Report_PDF__c' ) salesforce_result += pdf_upload_result + "\n" # Link PDF to DPR record if pdf_content_document_id: sf.ContentDocumentLink.create({ 'ContentDocumentId': pdf_content_document_id, 'LinkedEntityId': dpr_record_id, 'ShareType': 'V' }) # Upload images to Salesforce for Site_Images__c for file in files: image_filename = os.path.basename(file.name) image_content_document_id, image_upload_result = upload_file_to_salesforce( file.name, image_filename, sf, 'Site_Images__c' ) salesforce_result += image_upload_result + "\n" # Link image to DPR record if image_content_document_id: sf.ContentDocumentLink.create({ 'ContentDocumentId': image_content_document_id, 'LinkedEntityId': dpr_record_id, 'ShareType': 'V' }) except Exception as e: salesforce_result += f"Error interacting with Salesforce: {str(e)}\n" else: salesforce_result = "Salesforce connection not available or PDF generation failed.\n" # Return the DPR text and the PDF file path for download return dpr_output + f"\n\n{pdf_result}", pdf_filename # Return DPR text, PDF file, and Salesforce upload status return ( dpr_output + f"\n\n{pdf_result}\n\nSalesforce Upload Status:\n{salesforce_result}", pdf_filepath )
# Gradio interface for uploading multiple files, displaying DPR, and downloading PDFiface = gr.Interface( fn=generate_dpr, inputs=gr.Files(type="filepath", label="Upload Site Photos"), # Handle batch upload of images inputs=gr.Files(type="filepath", label="Upload Site Photos"), outputs=[ gr.Textbox(label="Daily Progress Report"), # Display DPR text gr.File(label="Download PDF") # Provide PDF download link gr.Textbox(label="Daily Progress Report"), gr.File(label="Download PDF") ], title="Daily Progress Report Generator", description="Upload up to 10 site photos. The AI model will dynamically detect construction activities, materials, and progress and generate a text-based Daily Progress Report (DPR). The DPR will also be saved as a PDF, which you can download.", allow_flagging="never" # Optional: Disable flagging description="Upload up to 10 site photos. The AI model will generate a text-based Daily Progress Report (DPR), save it as a PDF, and upload the PDF to Report_PDF__c and images to Site_Images__c in Salesforce under Daily_Progress_Reports__c. Download the PDF locally if needed.", allow_flagging="never")
if __name__ == "__main__":app.py+112-12