Spaces:
Sleeping
Sleeping
Commit Β·
9c60c5f
1
Parent(s): 79b6caa
initial code
Browse filesFiles changed (6)
- app.pyAdded+785
- config/agents.yamlAdded+20
- config/tasks.yamlAdded+30
- crew.pyAdded+132
- requirements.txtAdded+3
- tools/custom_tool.pyAdded+382
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785
# #main.py# import sys# import os# import warnings# from crew import DocProcessing# import re
# # Fix Unicode encoding issues on Windows# if sys.platform.startswith('win'):# import codecs# sys.stdout = codecs.getwriter('utf-8')(sys.stdout.detach())# sys.stderr = codecs.getwriter('utf-8')(sys.stderr.detach())
# warnings.filterwarnings("ignore", category=SyntaxWarning, module="pysbd")
# def determine_file_type(file_path):# """# Determine the file type based on the file extension. # Args:# file_path (str): Path to the file # Returns:# str: 'pdf' if the file is a PDF, 'image' otherwise# """# _, ext = os.path.splitext(file_path)# if ext.lower() == '.pdf':# return 'pdf'# return 'image'
# def run():# """# Run the crew with file paths received from command line arguments.# """# # Get file paths from command line arguments# file_paths = sys.argv[1:] if len(sys.argv) > 1 else [] # if not file_paths:# print("No file paths provided. Usage: python main.py <file_path1> <file_path2> ...")# return # # Process the first file (you can modify this to handle multiple files if needed)# file_path = file_paths[0]# file_type = determine_file_type(file_path) # # Prepare inputs for the CrewAI# inputs = {# "file_path": file_path,# "file_type": file_type,# } # try: # # Pass the inputs to the crew kickoff method# result = DocProcessing().crew().kickoff(inputs=inputs) # # Try to get the actual output content from CrewOutput # return result# except Exception as e:# error_msg = f"An error occurred while running the crew: {e}"# print(error_msg)# raise Exception(error_msg)
# if __name__ == "__main__":# run()
#&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&# import gradio as gr# import os# import tempfile# import shutil# from pathlib import Path# import warnings# from typing import Tuple, Optional# import sys
# # Suppress warnings# warnings.filterwarnings("ignore", category=SyntaxWarning, module="pysbd")
# # Import your existing modules# from crew import DocProcessing# from tools.custom_tool import landing_ai_document_analysis
# def get_landing_ai_key():# """Get Landing AI API key from environment (HF secrets or local .env)"""# # Try multiple environment variable names for flexibility# return (# os.getenv("LANDING_AI_API_KEY") or # HuggingFace secrets or production# os.getenv("LANDING_AI_API_KEY_LOCAL") or # Local development alternative# os.getenv("LANDINGAI_API_KEY") or # Alternative naming# os.getenv("LANDING_API_KEY") # Another alternative# )
# def validate_api_key(api_key: str) -> bool:# """Validate Anthropic API key format"""# if not api_key:# return False# return api_key.startswith("sk-ant-") and len(api_key) > 20
# def determine_file_type(file_path: str) -> str:# """Determine file type based on extension"""# _, ext = os.path.splitext(file_path)# return 'pdf' if ext.lower() == '.pdf' else 'image'
# def process_document(file, anthropic_api_key: str) -> Tuple[str, str]:# """# Process the uploaded document and return analysis + generated code # Args:# file: Uploaded file object from Gradio# anthropic_api_key: User's Anthropic API key # Returns:# Tuple of (analysis_result, generated_code)# """# try:# # Validate inputs# if not file:# return "β No file uploaded", "" # if not validate_api_key(anthropic_api_key):# return "β Invalid Anthropic API key. Please ensure it starts with 'sk-ant-' and is complete.", "" # # Check if Landing AI key is available# landing_ai_key = get_landing_ai_key()# if not landing_ai_key:# return "β Landing AI API key not configured. Please ensure LANDING_AI_API_KEY is set in environment variables or HuggingFace secrets.", "" # # Set environment variables securely# os.environ["ANTHROPIC_API_KEY"] = anthropic_api_key# os.environ["LANDING_AI_API_KEY"] = landing_ai_key # # Create temporary directory for processing# with tempfile.TemporaryDirectory() as temp_dir:# # Save uploaded file# file_extension = Path(file.name).suffix# temp_file_path = os.path.join(temp_dir, f"uploaded_file{file_extension}") # # Copy uploaded file to temp location# shutil.copy2(file.name, temp_file_path) # # Determine file type# file_type = determine_file_type(temp_file_path) # # Prepare inputs for CrewAI# inputs = {# "file_path": temp_file_path,# "file_type": file_type,# } # # Initialize and run the crew with the API key# doc_processing = DocProcessing(anthropic_api_key=anthropic_api_key)# result = doc_processing.crew().kickoff(inputs=inputs) # # Extract results from CrewOutput# if hasattr(result, 'tasks_output') and result.tasks_output:# analysis_result = ""# generated_code = "" # for i, task_output in enumerate(result.tasks_output):# if i == 0: # First task is document analysis# analysis_result = str(task_output.raw) if hasattr(task_output, 'raw') else str(task_output)# elif i == 1: # Second task is code implementation# generated_code = str(task_output.raw) if hasattr(task_output, 'raw') else str(task_output) # return analysis_result, generated_code# else:# # Fallback if structure is different# result_str = str(result)# return result_str, "Code generation completed. Check the analysis section for details." # except Exception as e:# error_msg = f"β Error processing document: {str(e)}"# return error_msg, "" # finally:# # Clean up environment variables for security# if "ANTHROPIC_API_KEY" in os.environ:# del os.environ["ANTHROPIC_API_KEY"]
# def create_demo_interface():# """Create the Gradio interface""" # # Custom CSS for better styling# custom_css = """# .gradio-container {# max-width: 1200px !important;# margin: auto !important;# }# .header {# text-align: center;# margin-bottom: 2rem;# }# .api-key-input {# margin-bottom: 1rem;# }# .output-section {# margin-top: 2rem;# }# """ # with gr.Blocks(css=custom_css, title="Document to Code Converter") as demo:# gr.HTML("""# <div class="header"># <h1>π Document to Code Converter</h1># <p>Upload your design documents (images/PDFs) and convert them to working HTML/CSS/JS code!</p># </div># """) # with gr.Row():# with gr.Column(scale=1):# gr.HTML("<h3>π€ Upload & Configuration</h3>") # # API Key input# api_key_input = gr.Textbox(# label="π Anthropic API Key",# placeholder="sk-ant-...",# type="password",# info="Enter your Anthropic API key. It will be used securely and not stored.",# elem_classes=["api-key-input"]# ) # # File upload# file_input = gr.File(# label="π Upload Document",# file_types=[".pdf", ".png", ".jpg", ".jpeg", ".gif", ".bmp", ".tiff"], # ) # # Process button# process_btn = gr.Button(# "π Process Document",# variant="primary",# size="lg"# ) # # Status indicator# gr.HTML("""# <div style="margin-top: 1rem; padding: 1rem; background: #f0f9ff; border-radius: 8px; border-left: 4px solid #0ea5e9;"># <h4 style="margin: 0; color: #0c4a6e;">βΉοΈ How it works:</h4># <ol style="margin: 0.5rem 0; color: #164e63;"># <li>Upload your design document (image or PDF)</li># <li>Enter your Anthropic API key</li># <li>Click "Process Document" to analyze and generate code</li># <li>Get detailed analysis and working HTML/CSS/JS code</li># </ol># </div># """) # with gr.Row():# with gr.Column(scale=1):# gr.HTML("<h3 class='output-section'>π Document Analysis</h3>")# analysis_output = gr.Textbox(# label="Analysis Results",# lines=15,# placeholder="Document analysis will appear here...",# show_copy_button=True# ) # with gr.Column(scale=1):# gr.HTML("<h3 class='output-section'>π» Generated Code</h3>")# code_output = gr.Textbox(# label="HTML/CSS/JS Code",# lines=15,# placeholder="Generated code will appear here...",# show_copy_button=True# ) # # Add examples section# gr.HTML("""# <div style="margin-top: 2rem; padding: 1rem; background: #f8fafc; border-radius: 8px;"># <h4>π― Best Results Tips:</h4># <ul># <li><strong>High Quality Images:</strong> Use clear, high-resolution images for better analysis</li># <li><strong>Design Mockups:</strong> Website mockups, app designs, and UI sketches work great</li># <li><strong>PDF Documents:</strong> Multi-page design documents are supported</li># <li><strong>Clear Layouts:</strong> Well-organized designs produce better code structure</li># </ul># </div># """) # # Set up the processing event# process_btn.click(# fn=process_document,# inputs=[file_input, api_key_input],# outputs=[analysis_output, code_output],# show_progress=True# ) # # Add footer# gr.HTML("""# <div style="text-align: center; margin-top: 2rem; padding: 1rem; border-top: 1px solid #e2e8f0; color: #64748b;"># <p>π Your API keys are handled securely and never stored. # <br>Built with CrewAI, LandingAI, and Anthropic Claude.</p># </div># """) # return demo
# if __name__ == "__main__":# # Test Landing AI connection on startup# from tools.custom_tool import test_landing_ai_connection # print("π Testing API connections...")# landing_ai_available = test_landing_ai_connection() # if not landing_ai_available:# print("\nβ οΈ Warning: Landing AI API key not properly configured!")# print("For local development: Set LANDING_AI_API_KEY in your .env file")# print("For HuggingFace deployment: Add LANDING_AI_API_KEY to your Space secrets")# print("The app will still start, but document analysis will fail without the API key.\n")# else:# print("β
Landing AI API key configured correctly!\n") # # Create and launch the demo# demo = create_demo_interface() # # Launch configuration# demo.launch(# server_name="0.0.0.0", # Required for HuggingFace deployment# server_port=7860, # Standard port for HuggingFace# share=False, # Set to True for temporary public link during development# debug=False, # Set to True for development# show_error=True, # Show errors in the interface# quiet=False # Set to True to reduce console output# )
import gradio as grimport osimport tempfileimport shutilfrom pathlib import Pathimport warningsfrom typing import Tuple, Optionalimport sys
# Suppress warningswarnings.filterwarnings("ignore", category=SyntaxWarning, module="pysbd")
# Import your existing modulesfrom crew import DocProcessingfrom tools.custom_tool import landing_ai_document_analysis
def get_landing_ai_key(): """Get Landing AI API key from environment (HF secrets or local .env)""" # Try multiple environment variable names for flexibility return ( os.getenv("LANDING_AI_API_KEY") or # HuggingFace secrets or production os.getenv("LANDING_AI_API_KEY_LOCAL") or # Local development alternative os.getenv("LANDINGAI_API_KEY") or # Alternative naming os.getenv("LANDING_API_KEY") # Another alternative )
def validate_api_key(api_key: str) -> bool: """Validate Anthropic API key format""" if not api_key: return False return api_key.startswith("sk-ant-") and len(api_key) > 20
def create_html_file(code_content: str, filename: str = "generated_page.html") -> str: """ Create an HTML file from the generated code Args: code_content: The HTML/CSS/JS code filename: Name for the HTML file Returns: str: Path to the created file """ try: # Create temporary file temp_dir = tempfile.gettempdir() file_path = os.path.join(temp_dir, filename) # Clean the code content - remove any markdown formatting if present cleaned_code = code_content.strip() if cleaned_code.startswith("```html"): cleaned_code = cleaned_code[7:] if cleaned_code.endswith("```"): cleaned_code = cleaned_code[:-3] cleaned_code = cleaned_code.strip() # Ensure it's a complete HTML document if not cleaned_code.lower().startswith('<!doctype') and not cleaned_code.lower().startswith('<html'): cleaned_code = f"""<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Generated Page</title></head><body>{cleaned_code}</body></html>""" # Write to file with open(file_path, 'w', encoding='utf-8') as f: f.write(cleaned_code) return file_path except Exception as e: print(f"Error creating HTML file: {e}") return None
def determine_file_type(file_path: str) -> str: """Determine file type based on extension""" _, ext = os.path.splitext(file_path) return 'pdf' if ext.lower() == '.pdf' else 'image'def prepare_preview_content(code_content: str) -> str: """ Prepare code content for safe preview in iframe Args: code_content: The HTML/CSS/JS code Returns: str: Cleaned and safe HTML content for preview """ try: if not code_content or code_content.strip() == "": return "<div style='padding: 20px; text-align: center; color: #666;'>No code generated yet...</div>" # Clean the code content cleaned_code = code_content.strip() # Remove markdown formatting if present if cleaned_code.startswith("```html"): cleaned_code = cleaned_code[7:] if cleaned_code.startswith("```"): cleaned_code = cleaned_code[3:] if cleaned_code.endswith("```"): cleaned_code = cleaned_code[:-3] cleaned_code = cleaned_code.strip() # If it's not a complete HTML document, wrap it if not cleaned_code.lower().startswith('<!doctype') and not cleaned_code.lower().startswith('<html'): cleaned_code = f"""<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Preview</title> <style> body {{ margin: 0; padding: 10px; font-family: Arial, sans-serif; }} * {{ box-sizing: border-box; }} </style></head><body>{cleaned_code}</body></html>""" # Wrap in iframe for safe rendering iframe_content = f""" <iframe srcdoc="{cleaned_code.replace('"', '"')}" style="width: 100%; height: 400px; border: 1px solid #ddd; border-radius: 8px;" sandbox="allow-scripts allow-same-origin"> </iframe> """ return iframe_content except Exception as e: return f"<div style='padding: 20px; color: red;'>Error preparing preview: {str(e)}</div>"
def toggle_to_code(): """Show code view and hide preview""" return ( gr.update(visible=True), # code_output gr.update(visible=False), # preview_output gr.update(variant="primary"), # code_view_btn gr.update(variant="secondary") # preview_btn )
def toggle_to_preview(code_content): """Show preview and hide code view""" preview_html = prepare_preview_content(code_content) return ( gr.update(visible=False), # code_output gr.update(visible=True, value=preview_html), # preview_output gr.update(variant="secondary"), # code_view_btn gr.update(variant="primary") # preview_btn )
# def download_html_file(code_content):# """Create downloadable HTML file"""# if not code_content or code_content.strip() == "":# return gr.update(visible=False) # file_path = create_html_file(code_content)# if file_path:# return gr.update(visible=True, value=file_path)# else:# return gr.update(visible=False)
def process_document(file, anthropic_api_key: str) -> Tuple[str, str]: """ Process the uploaded document and return analysis + generated code Args: file: Uploaded file object from Gradio anthropic_api_key: User's Anthropic API key Returns: Tuple of (analysis_result, generated_code) """ try: # Validate inputs if not file: return "β No file uploaded", "" if not validate_api_key(anthropic_api_key): return "β Invalid Anthropic API key. Please ensure it starts with 'sk-ant-' and is complete.", "" # Check if Landing AI key is available landing_ai_key = get_landing_ai_key() if not landing_ai_key: return "β Landing AI API key not configured. Please ensure LANDING_AI_API_KEY is set in environment variables or HuggingFace secrets.", "" # Set environment variables securely os.environ["ANTHROPIC_API_KEY"] = anthropic_api_key os.environ["LANDING_AI_API_KEY"] = landing_ai_key # Create temporary directory for processing with tempfile.TemporaryDirectory() as temp_dir: # Save uploaded file file_extension = Path(file.name).suffix temp_file_path = os.path.join(temp_dir, f"uploaded_file{file_extension}") # Copy uploaded file to temp location shutil.copy2(file.name, temp_file_path) # Determine file type file_type = determine_file_type(temp_file_path) # Prepare inputs for CrewAI inputs = { "file_path": temp_file_path, "file_type": file_type, } # Initialize and run the crew with the API key doc_processing = DocProcessing(anthropic_api_key=anthropic_api_key) result = doc_processing.crew().kickoff(inputs=inputs) # Extract results from CrewOutput if hasattr(result, 'tasks_output') and result.tasks_output: analysis_result = "" generated_code = "" for i, task_output in enumerate(result.tasks_output): if i == 0: # First task is document analysis analysis_result = str(task_output.raw) if hasattr(task_output, 'raw') else str(task_output) elif i == 1: # Second task is code implementation generated_code = str(task_output.raw) if hasattr(task_output, 'raw') else str(task_output) return generated_code # analysis_result, else: # Fallback if structure is different result_str = str(result) return result_str, "Code generation completed. Check the analysis section for details." except Exception as e: error_msg = f"β Error processing document: {str(e)}" return error_msg, "" finally: # Clean up environment variables for security if "ANTHROPIC_API_KEY" in os.environ: del os.environ["ANTHROPIC_API_KEY"]
def create_demo_interface(): """Create the Gradio interface""" # Custom CSS for better styling custom_css = """ .gradio-container { max-width: 1200px !important; margin: auto !important; } .header { text-align: center; margin-bottom: 2rem; } .api-key-input { margin-bottom: 1rem; } .output-section { margin-top: 2rem; } .toggle-buttons { margin-bottom: 1rem; } .preview-container { border: 1px solid #e2e8f0; border-radius: 8px; background: #f8fafc; min-height: 400px; } """ with gr.Blocks(css=custom_css, title="Document to Code Converter") as demo: gr.HTML(""" <div class="header"> <h1>π Document to Code Converter</h1> <p>Upload your design documents (images/PDFs) and convert them to working HTML/CSS/JS code!</p> </div> """) with gr.Row(): with gr.Column(scale=1): gr.HTML("<h3>π€ Upload & Configuration</h3>") # API Key input api_key_input = gr.Textbox( label="π Anthropic API Key", placeholder="sk-ant-...", type="password", info="Enter your Anthropic API key. It will be used securely and not stored.", elem_classes=["api-key-input"] ) # File upload file_input = gr.File( label="π Upload Document", file_types=[".pdf", ".png", ".jpg", ".jpeg", ".gif", ".bmp", ".tiff"], ) # Process button process_btn = gr.Button( "π Process Document", variant="primary", size="lg" ) # Status indicator gr.HTML(""" <div style="margin-top: 1rem; padding: 1rem; background: #f0f9ff; border-radius: 8px; border-left: 4px solid #0ea5e9;"> <h4 style="margin: 0; color: #0c4a6e;">βΉοΈ How it works:</h4> <ol style="margin: 0.5rem 0; color: #164e63;"> <li>Upload your design document (image or PDF)</li> <li>Enter your Anthropic API key</li> <li>Click "Process Document" to analyze and generate code</li> <li>Use toggle buttons to switch between code view and live preview</li> </ol> </div> """) gr.HTML("<h3 class='output-section'>π» Generated Code & Preview</h3>") # Toggle buttons for code/preview with gr.Row(): code_view_btn = gr.Button("π View Code", variant="primary", size="sm") preview_btn = gr.Button("ποΈ Preview Result", variant="secondary", size="sm") # Code output (visible by default) code_output = gr.Textbox( label="HTML/CSS/JS Code", lines=15, placeholder="Generated code will appear here...", show_copy_button=True, visible=True ) # Preview output (hidden by default) preview_output = gr.HTML( label="Live Preview", value="<div style='padding: 20px; text-align: center; color: #666;'>Preview will appear here after code generation...</div>", visible=False ) # with gr.Row(): # with gr.Column(scale=1): # gr.HTML("<h3 class='output-section'>π Document Analysis</h3>") # analysis_output = gr.Textbox( # label="Analysis Results", # lines=15, # placeholder="Document analysis will appear here...", # show_copy_button=True # ) # with gr.Column(scale=1): # Download file component (hidden) # download_file = gr.File( # label="Download", # visible=False # ) # Add examples section gr.HTML(""" <div style="margin-top: 2rem; padding: 1rem; background: #f8fafc; border-radius: 8px;"> <h4>π― New Features:</h4> <ul> <li><strong>π Code View:</strong> See the raw HTML/CSS/JS code generated from your design</li> <li><strong>ποΈ Live Preview:</strong> Toggle to see how your code will actually look when rendered</li> <li><strong>π Real-time Toggle:</strong> Switch between code and preview instantly</li> </ul> <h4>π― Best Results Tips:</h4> <ul> <li><strong>High Quality Images:</strong> Use clear, high-resolution images for better analysis</li> <li><strong>Design Mockups:</strong> Website mockups, app designs, and UI sketches work great</li> <li><strong>PDF Documents:</strong> Multi-page design documents are supported</li> <li><strong>Clear Layouts:</strong> Well-organized designs produce better code structure</li> </ul> </div> """) # Set up the processing event process_btn.click( fn=process_document, inputs=[file_input, api_key_input], outputs=[code_output], # analysis_output, show_progress=True ) # Set up toggle events code_view_btn.click( fn=toggle_to_code, inputs=[], outputs=[code_output, preview_output, code_view_btn, preview_btn] ) preview_btn.click( fn=toggle_to_preview, inputs=[code_output], outputs=[code_output, preview_output, code_view_btn, preview_btn] ) # Set up download event # download_btn.click( # fn=download_html_file, # inputs=[code_output], # outputs=[download_file] # ) # Add footer gr.HTML(""" <div style="text-align: center; margin-top: 2rem; padding: 1rem; border-top: 1px solid #e2e8f0; color: #64748b;"> <p>π Your API keys are handled securely and never stored. <br>Built with CrewAI, LandingAI, and Anthropic Claude.</p> </div> """) return demo
if __name__ == "__main__": # Test Landing AI connection on startup from tools.custom_tool import test_landing_ai_connection print("π Testing API connections...") landing_ai_available = test_landing_ai_connection() if not landing_ai_available: print("\nβ οΈ Warning: Landing AI API key not properly configured!") print("For local development: Set LANDING_AI_API_KEY in your .env file") print("For HuggingFace deployment: Add LANDING_AI_API_KEY to your Space secrets") print("The app will still start, but document analysis will fail without the API key.\n") else: print("β
Landing AI API key configured correctly!\n") # Create and launch the demo demo = create_demo_interface() # Launch configuration demo.launch( server_name="0.0.0.0", # Required for HuggingFace deployment server_port=7860, # Standard port for HuggingFace share=False, # Set to True for temporary public link during development debug=False, # Set to True for development show_error=True, # Show errors in the interface quiet=False # Set to True to reduce console output )1234567891011121314151617181920#agents.yamldocument_analyst: role: > Senior Document Analyst goal: > To analyze the document backstory: > You have a keen eye to details and you are able to analyze the document with precision. You role is to analyze the document and extract the exact information from it.DO NOT miss any point, cover all the points from the start to the end of the document.
developer_agent: role: > HTML/CSS/JS Implementation Specialist goal: > Turn design descriptions into working web code using HTML, CSS, and JavaScript. backstory: > You are a web developer who creates clean code using HTML, CSS, and JavaScript without frameworks. You write semantically correct HTML, use inline CSS styles, and add vanilla JavaScript when needed. Your code is cross-browser compatible and matches designs exactly. You only output code - no explanations, no comments, no conversation. You receive detailed descriptions and transform them directly into working code.123456789101112131415161718192021222324252627282930#tasks.yamldocument_analysis: description: > Analyze the document and extract the exact information from it. {file_path} is the path of the document. {file_type} is the type of the document. expected_output: > The document is analyzed and the exact information is extracted from it. Return in Markdown format. Include all the details and information from the document. Do not miss any details. agent: document_analyst
code_implementation: description: > Turn design specifications into working web code using HTML, CSS, and JavaScript. Do not miss any details from the design and complete all the said pages. Use inline styles directly in HTML elements rather than separate stylesheets. Write vanilla JavaScript without frameworks unless absolutely necessary. Match all measurements, colors, positions, and text exactly as specified in the design. expected_output: > Clean HTML with inline CSS that perfectly matches the design specifications. The code should work as a standalone file without external dependencies. DO NOT,I REPEAT DO NOT include any comments ,thoughts or explanations - only write working code. Example: <!-- Header implementation with positioned styling --> <div style="position: absolute; top: 20px; left: 10px; width: 100px; height: 50px; background: #f0f0f0;"> <h1 style="margin: 0; font-size: 1.2rem;">Header</h1> </div> agent: developer_agent123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132# # crew.py file of design_to_code# from crewai import Agent, Crew, Process, Task, LLM# from crewai.project import CrewBase, agent, crew, task# from tools.custom_tool import landing_ai_document_analysis# from dotenv import load_dotenv# import os
# # Load environment variables# load_dotenv()
# @CrewBase# class DocProcessing():# """DocProcessing crew"""
# agents_config = 'config/agents.yaml'# tasks_config = 'config/tasks.yaml'
# llm = LLM(# model = "claude-3-haiku-20240307",# api_key = os.getenv("ANTHROPIC_API_KEY"),# temperature = 0,# )
# @agent# def document_analyst(self) -> Agent:# return Agent(# config=self.agents_config['document_analyst'],# tools=[landing_ai_document_analysis],# llm=self.llm,# ) # @agent# def developer_agent(self) -> Agent:# return Agent(# config=self.agents_config['developer_agent'],# llm=self.llm,# )
# @task# def document_analysis(self) -> Task:# return Task(# config=self.tasks_config['document_analysis'],# ) # @task# def code_implementation(self) -> Task:# return Task(# config=self.tasks_config['code_implementation'],# )
# @crew# def crew(self) -> Crew:# """Creates the DocProcessing crew"""# return Crew(# agents=self.agents, # Automatically created by the @agent decorator# tasks=self.tasks, # Automatically created by the @task decorator# process=Process.sequential,# verbose=True,# )from crewai import Agent, Crew, Process, Task, LLMfrom crewai.project import CrewBase, agent, crew, taskfrom tools.custom_tool import landing_ai_document_analysisfrom dotenv import load_dotenvimport os
# Load environment variablesload_dotenv()
@CrewBaseclass DocProcessing(): """DocProcessing crew"""
agents_config = 'config/agents.yaml' tasks_config = 'config/tasks.yaml'
def __init__(self, anthropic_api_key: str = None): """ Initialize DocProcessing crew with API key Args: anthropic_api_key: The Anthropic API key to use for LLM """ # Use provided API key or fall back to environment variable api_key = anthropic_api_key or os.getenv("ANTHROPIC_API_KEY") if not api_key: raise ValueError("Anthropic API key is required. Please provide it as parameter or set ANTHROPIC_API_KEY environment variable.") self.llm = LLM( model="claude-3-haiku-20240307", api_key=api_key, temperature=0, )
@agent def document_analyst(self) -> Agent: return Agent( config=self.agents_config['document_analyst'], tools=[landing_ai_document_analysis], llm=self.llm, ) @agent def developer_agent(self) -> Agent: return Agent( config=self.agents_config['developer_agent'], llm=self.llm, )
@task def document_analysis(self) -> Task: return Task( config=self.tasks_config['document_analysis'], ) @task def code_implementation(self) -> Task: return Task( config=self.tasks_config['code_implementation'], )
@crew def crew(self) -> Crew: """Creates the DocProcessing crew""" return Crew( agents=self.agents, # Automatically created by the @agent decorator tasks=self.tasks, # Automatically created by the @task decorator process=Process.sequential, verbose=True, )123gradiocrewaipython-dotenv123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382# #crew_tool.py# import json# import os# import requests# from crewai.tools import tool# from dotenv import load_dotenv
# # Load environment variables# load_dotenv()
# def safe_format_with_indicators(text):# """Replace emojis with text indicators"""# if not isinstance(text, str):# text = str(text) # emoji_replacements = {# 'π': '[BATTERY]',# 'β
': '[SUCCESS]',# 'β': '[ERROR]',# 'π': '[DOCUMENT]',# 'π': '[CHART]',# 'β οΈ': '[WARNING]',# 'π': '[SEARCH]',# 'π‘': '[INSIGHT]',# 'π―': '[TARGET]',# 'β¨': '[HIGHLIGHT]',# 'π': '[LAUNCH]',# 'π': '[GROWTH]',# 'π': '[DECLINE]',# 'π§': '[TOOL]',# 'π»': '[CODE]',# 'π': '[STAR]',# 'π¨': '[DESIGN]',# 'π±': '[MOBILE]',# 'π₯οΈ': '[DESKTOP]',# 'π': '[LINK]',# 'π': '[NOTE]',# 'π': '[ACHIEVEMENT]',# 'π°': '[MONEY]',# 'π': '[CELEBRATION]',# 'π': '[SECURE]',# 'π': '[UNLOCKED]',# 'β': '[RATING]',# 'β€οΈ': '[FAVORITE]',# 'π': '[THUMBS_UP]',# 'π': '[THUMBS_DOWN]',# 'π₯': '[HOT]',# 'βοΈ': '[COLD]',# 'π‘οΈ': '[TEMPERATURE]'# } # for emoji, replacement in emoji_replacements.items():# text = text.replace(emoji, replacement) # return text
# def format_api_response(response_data):# """# Format API response and replace emojis with safe indicators. # Args:# response_data: Raw API response (dict, str, or other) # Returns:# str: Formatted response with safe emoji replacements# """# try:# if isinstance(response_data, dict):# # Convert dict to readable format# formatted_parts = [] # for key, value in response_data.items():# if isinstance(value, (str, int, float)):# safe_value = safe_format_with_indicators(str(value))# formatted_parts.append(f"{key}: {safe_value}")# elif isinstance(value, list):# safe_items = [safe_format_with_indicators(str(item)) for item in value]# formatted_parts.append(f"{key}: {', '.join(safe_items)}")# elif isinstance(value, dict):# # Handle nested dictionaries# nested_items = []# for nested_key, nested_value in value.items():# safe_nested = safe_format_with_indicators(str(nested_value))# nested_items.append(f"{nested_key}: {safe_nested}")# formatted_parts.append(f"{key}: {'; '.join(nested_items)}") # result = "\n".join(formatted_parts)# return safe_format_with_indicators(result)# else:# return safe_format_with_indicators(str(response_data)) # except Exception as e:# error_msg = f"Error formatting response: {str(e)}"# return safe_format_with_indicators(error_msg)
# @tool("LandingAI Document Analysis")# def landing_ai_document_analysis(file_path: str, file_type: str = "image") -> str:# """# Analyze images or PDFs using LandingAI's document analysis API. # Args:# file_path (str): Path to the image or PDF file to analyze# file_type (str): Type of file, either "image" or "pdf" # Returns:# str: Analysis results from the API# """# # Get API key from environment variable# api_key = os.getenv("LANDING_AI_API_KEY") # # API endpoint# url = "https://api.va.landing.ai/v1/tools/agentic-document-analysis" # # Prepare the file for upload based on file_type# with open(file_path, "rb") as file_obj:# if file_type.lower() == "pdf":# files = {"pdf": file_obj}# else:# files = {"image": file_obj} # # Prepare headers with authentication# headers = {"Authorization": f"Basic {api_key}"}
# # Make the API request# response = requests.post(url, files=files, headers=headers)# if response.status_code == 200:# try:# response_json = response.json()# formatted_result = format_api_response(response_json)# # result += f"π ANALYSIS:\n{formatted_result}"# return safe_format_with_indicators(formatted_result) # except json.JSONDecodeError:# # If response isn't JSON, format the text response# safe_text = safe_format_with_indicators(response.text)# return safe_format_with_indicators(safe_text) # return response.json()
import jsonimport osimport requestsfrom crewai.tools import toolfrom dotenv import load_dotenv
# Load environment variablesload_dotenv()
def get_landing_ai_api_key(): """ Get Landing AI API key from environment variables. Tries multiple sources for compatibility with different deployment environments. Returns: str: The API key if found, None otherwise """ # Try different environment variable names for flexibility api_key = ( os.getenv("LANDING_AI_API_KEY") or # HuggingFace secrets or production os.getenv("LANDING_AI_API_KEY_LOCAL") or # Local development alternative os.getenv("LANDINGAI_API_KEY") or # Alternative naming os.getenv("LANDING_API_KEY") # Another alternative ) return api_key
def safe_format_with_indicators(text): """Replace emojis with text indicators""" if not isinstance(text, str): text = str(text) emoji_replacements = { 'π': '[BATTERY]', 'β
': '[SUCCESS]', 'β': '[ERROR]', 'π': '[DOCUMENT]', 'π': '[CHART]', 'β οΈ': '[WARNING]', 'π': '[SEARCH]', 'π‘': '[INSIGHT]', 'π―': '[TARGET]', 'β¨': '[HIGHLIGHT]', 'π': '[LAUNCH]', 'π': '[GROWTH]', 'π': '[DECLINE]', 'π§': '[TOOL]', 'π»': '[CODE]', 'π': '[STAR]', 'π¨': '[DESIGN]', 'π±': '[MOBILE]', 'π₯οΈ': '[DESKTOP]', 'π': '[LINK]', 'π': '[NOTE]', 'π': '[ACHIEVEMENT]', 'π°': '[MONEY]', 'π': '[CELEBRATION]', 'π': '[SECURE]', 'π': '[UNLOCKED]', 'β': '[RATING]', 'β€οΈ': '[FAVORITE]', 'π': '[THUMBS_UP]', 'π': '[THUMBS_DOWN]', 'π₯': '[HOT]', 'βοΈ': '[COLD]', 'π‘οΈ': '[TEMPERATURE]' } for emoji, replacement in emoji_replacements.items(): text = text.replace(emoji, replacement) return text
def format_api_response(response_data): """ Format API response and replace emojis with safe indicators. Args: response_data: Raw API response (dict, str, or other) Returns: str: Formatted response with safe emoji replacements """ try: if isinstance(response_data, dict): # Convert dict to readable format formatted_parts = [] for key, value in response_data.items(): if isinstance(value, (str, int, float)): safe_value = safe_format_with_indicators(str(value)) formatted_parts.append(f"{key}: {safe_value}") elif isinstance(value, list): safe_items = [safe_format_with_indicators(str(item)) for item in value] formatted_parts.append(f"{key}: {', '.join(safe_items)}") elif isinstance(value, dict): # Handle nested dictionaries nested_items = [] for nested_key, nested_value in value.items(): safe_nested = safe_format_with_indicators(str(nested_value)) nested_items.append(f"{nested_key}: {safe_nested}") formatted_parts.append(f"{key}: {'; '.join(nested_items)}") result = "\n".join(formatted_parts) return safe_format_with_indicators(result) else: return safe_format_with_indicators(str(response_data)) except Exception as e: error_msg = f"Error formatting response: {str(e)}" return safe_format_with_indicators(error_msg)
@tool("LandingAI Document Analysis")def landing_ai_document_analysis(file_path: str, file_type: str = "image") -> str: """ Analyze images or PDFs using LandingAI's document analysis API. Args: file_path (str): Path to the image or PDF file to analyze file_type (str): Type of file, either "image" or "pdf" Returns: str: Analysis results from the API """ try: # Get API key with improved error handling api_key = get_landing_ai_api_key() if not api_key: error_msg = "Landing AI API key not found. Please ensure LANDING_AI_API_KEY is set in environment variables or HuggingFace secrets." return safe_format_with_indicators(f"[ERROR] {error_msg}") # Validate file exists if not os.path.exists(file_path): error_msg = f"File not found: {file_path}" return safe_format_with_indicators(f"[ERROR] {error_msg}") # API endpoint url = "https://api.va.landing.ai/v1/tools/agentic-document-analysis" # Prepare the file for upload based on file_type try: with open(file_path, "rb") as file_obj: if file_type.lower() == "pdf": files = {"pdf": file_obj} else: files = {"image": file_obj} # Prepare headers with authentication headers = {"Authorization": f"Basic {api_key}"} # Make the API request with timeout response = requests.post( url, files=files, headers=headers, timeout=60 # 60 second timeout ) # Handle different response status codes if response.status_code == 200: try: response_json = response.json() formatted_result = format_api_response(response_json) return safe_format_with_indicators(formatted_result) except json.JSONDecodeError: # If response isn't JSON, format the text response safe_text = safe_format_with_indicators(response.text) return safe_format_with_indicators(safe_text) elif response.status_code == 401: error_msg = "Authentication failed. Please check your Landing AI API key." return safe_format_with_indicators(f"[ERROR] {error_msg}") elif response.status_code == 403: error_msg = "Access forbidden. Your API key may not have the required permissions." return safe_format_with_indicators(f"[ERROR] {error_msg}") elif response.status_code == 429: error_msg = "Rate limit exceeded. Please try again later." return safe_format_with_indicators(f"[ERROR] {error_msg}") elif response.status_code == 500: error_msg = "Server error from Landing AI. Please try again later." return safe_format_with_indicators(f"[ERROR] {error_msg}") else: error_msg = f"API request failed with status code {response.status_code}: {response.text}" return safe_format_with_indicators(f"[ERROR] {error_msg}") except FileNotFoundError: error_msg = f"File not found: {file_path}" return safe_format_with_indicators(f"[ERROR] {error_msg}") except requests.exceptions.Timeout: error_msg = "Request timed out. The file may be too large or the service is slow." return safe_format_with_indicators(f"[ERROR] {error_msg}") except requests.exceptions.ConnectionError: error_msg = "Connection error. Please check your internet connection." return safe_format_with_indicators(f"[ERROR] {error_msg}") except requests.exceptions.RequestException as e: error_msg = f"Request failed: {str(e)}" return safe_format_with_indicators(f"[ERROR] {error_msg}") except Exception as e: error_msg = f"Unexpected error in document analysis: {str(e)}" return safe_format_with_indicators(f"[ERROR] {error_msg}")
def test_landing_ai_connection(): """ Test function to verify Landing AI API connection. This can be called to verify the setup before processing documents. Returns: bool: True if API key is available and valid format, False otherwise """ api_key = get_landing_ai_api_key() if not api_key: print("β Landing AI API key not found in environment variables") print("Available environment variables:") for key in os.environ.keys(): if 'LANDING' in key.upper() or 'API' in key.upper(): print(f" - {key}: {'SET' if os.environ[key] else 'EMPTY'}") return False # Basic format validation (adjust based on Landing AI key format) if len(api_key) < 10: print("β Landing AI API key appears to be too short") return False print("β
Landing AI API key found and appears valid") return True
# Test the connection when module is imported (optional)if __name__ == "__main__": test_landing_ai_connection()app.pyAdded+785
config/agents.yamlAdded+20
config/tasks.yamlAdded+30
crew.pyAdded+132
requirements.txtAdded+3
tools/custom_tool.pyAdded+382