Spaces:
Sleeping
Sleeping
Update app.py
Browse files6 unmodified lines78910111257 unmodified lines707172737475767778798081822 unmodified lines858687888990919293949596976 unmodified lines1041051061071081091101111121131141151161171181191201211221231241256 unmodified linesfrom reportlab.platypus import SimpleDocTemplate, Paragraph, Spacerfrom reportlab.lib.styles import getSampleStyleSheet, ParagraphStylefrom reportlab.lib import colors# Load BLIP model and processorprocessor = BlipProcessor.from_pretrained("Salesforce/blip-image-captioning-base")57 unmodified lines# Build the PDFdoc.build(flowables)return f"PDF saved successfully as {filename}"except Exception as e:return f"Error saving PDF: {str(e)}"# Function to generate the daily progress report (DPR) text and save as PDFdef generate_dpr(files):dpr_text = []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 pathimage = Image.open(file.name) # Using file.name for filepathif image.mode != "RGB":image = image.convert("RGB")# Dynamically generate a caption based on the imagecaption = generate_captions_from_image(image)# Generate DPR section for this image with dynamic captiondpr_section = f"\nImage: {file.name}\nDescription: {caption}\n"6 unmodified linespdf_filename = f"DPR_{datetime.now().strftime('%Y-%m-%d_%H-%M-%S')}.pdf"# Save DPR text to PDFpdf_result = save_dpr_to_pdf(dpr_output, pdf_filename)# Return the DPR text and the PDF file path for downloadreturn dpr_output + f"\n\n{pdf_result}", pdf_filename# 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 imagesoutputs=[gr.Textbox(label="Daily Progress Report"), # Display DPR textgr.File(label="Download PDF") # Provide PDF download link],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)if __name__ == "__main__":6 unmodified lines789101112131415161718192021222324252627282930313257 unmodified lines909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291302 unmodified lines1331341351361371381391401411421431441451466 unmodified lines1531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242256 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 = Noneprint(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 PDFdoc.build(flowables)return f"PDF saved successfully as {filename}", filenameexcept Exception as e:return f"Error saving PDF: {str(e)}", None# 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 base64with open(file_path, 'rb') as f:file_content = f.read()file_content_b64 = base64.b64encode(file_content).decode('utf-8')# Create ContentVersioncontent_version = sf_connection.ContentVersion.create({'Title': filename,'PathOnClient': filename,'VersionData': file_content_b64,'Description': f'Uploaded for {field_name}'})# Get ContentDocumentIdcontent_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 pathimage = Image.open(file.name)if image.mode != "RGB":image = image.convert("RGB")# Dynamically generate a caption based on the imagecaption = generate_captions_from_image(image)captions.append(caption)# Generate DPR section for this image with dynamic captiondpr_section = f"\nImage: {file.name}\nDescription: {caption}\n"6 unmodified linespdf_filename = f"DPR_{datetime.now().strftime('%Y-%m-%d_%H-%M-%S')}.pdf"# Save DPR text to PDFpdf_result, pdf_filepath = save_dpr_to_pdf(dpr_output, pdf_filename)# Salesforce uploadsalesforce_result = ""if sf and pdf_filepath:try:# Create Daily_Progress_Reports__c recordreport_description = "; ".join(captions)[:255] # Concatenate captions, limit to 255 charsdpr_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__cpdf_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 recordif 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__cfor 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 recordif 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 DPR text, PDF file, and Salesforce upload statusreturn (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"),outputs=[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 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