Spaces:
Sleeping
Sleeping
Commit Β·
ae43d88
1
Parent(s): 91881f8
initial code
Browse filesFiles changed (6)
- config/agents.yamlAdded+8
- config/tasks.yamlAdded+9
- crew.pyAdded+111
- main.pyAdded+247
- requirements.txtAdded+2
- tools/custom_tool.pyAdded+91
12345678document_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.123456789document_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. agent: document_analyst
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111# 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# # from langchain_groq import ChatGroq# # 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,# )
# # llm = ChatGroq(# # model = "groq/llama-3.1-8b-instant",# # api_key= os.getenv("GROQ_API_KEY"),# # )
# @agent# def document_analyst(self) -> Agent:# return Agent(# config=self.agents_config['document_analyst'],# verbose=True,# tools=[landing_ai_document_analysis],# llm=self.llm,# )
# @task# def document_analysis(self) -> Task:# return Task(# config=self.tasks_config['document_analysis'],# )
# @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_analysisimport os
@CrewBaseclass DocProcessing(): """DocProcessing crew for document analysis"""
agents_config = 'config/agents.yaml' tasks_config = 'config/tasks.yaml'
def __init__(self): """Initialize the DocProcessing crew with API key validation.""" super().__init__() # Get API key from environment variable (set at runtime) anthropic_api_key = os.getenv("ANTHROPIC_API_KEY") if not anthropic_api_key: raise ValueError("ANTHROPIC_API_KEY environment variable is required") self.llm = LLM( model="claude-3-haiku-20240307", api_key=anthropic_api_key, temperature=0, )
@agent def document_analyst(self) -> Agent: return Agent( config=self.agents_config['document_analyst'], verbose=True, tools=[landing_ai_document_analysis], llm=self.llm, )
@task def document_analysis(self) -> Task: return Task( config=self.tasks_config['document_analysis'], )
@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, )123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247# #!/usr/bin/env python# import sys# import os# import warnings# from crew import DocProcessing
# 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) # print(f"Processing file: {file_path} (type: {file_type})") # # 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)# 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()
#!/usr/bin/env pythonimport osimport tempfileimport gradio as grimport warningsfrom crew import DocProcessing
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 process_document(file, anthropic_api_key, landing_ai_api_key): """ Process the uploaded document using CrewAI. Args: file: Uploaded file from Gradio anthropic_api_key (str): Anthropic API key landing_ai_api_key (str): LandingAI API key Returns: str: Processing results or error message """ try: # Validate inputs if file is None: return "β Please upload a file first." if not anthropic_api_key.strip(): return "β Please provide your Anthropic API key." if not landing_ai_api_key.strip(): return "β Please provide your LandingAI API key." # Set environment variables securely for this session os.environ["ANTHROPIC_API_KEY"] = anthropic_api_key.strip() os.environ["LANDING_AI_API_KEY"] = landing_ai_api_key.strip() # Get file path and determine type file_path = file.name file_type = determine_file_type(file_path) print(f"Processing file: {file_path} (type: {file_type})") # Prepare inputs for CrewAI inputs = { "file_path": file_path, "file_type": file_type, } # Process with CrewAI result = DocProcessing().crew().kickoff(inputs=inputs) # Clean up environment variables for security if "ANTHROPIC_API_KEY" in os.environ: del os.environ["ANTHROPIC_API_KEY"] if "LANDING_AI_API_KEY" in os.environ: del os.environ["LANDING_AI_API_KEY"] return f"β
**Processing Complete!**\n\n{result}" except Exception as e: # Clean up environment variables even on error if "ANTHROPIC_API_KEY" in os.environ: del os.environ["ANTHROPIC_API_KEY"] if "LANDING_AI_API_KEY" in os.environ: del os.environ["LANDING_AI_API_KEY"] error_msg = f"β **Error occurred:** {str(e)}" print(error_msg) return error_msg
# Create Gradio interfacedef create_interface(): """Create and return the Gradio interface.""" with gr.Blocks( title="Document Analysis with CrewAI", theme=gr.themes.Soft(), css=""" .container { max-width: 800px; margin: auto; } .header { text-align: center; margin-bottom: 30px; } .api-section { background-color: #f8f9fa; padding: 20px; border-radius: 10px; margin-bottom: 20px; } """ ) as demo: gr.HTML(""" <div class="header"> <h1>π€ Document Analysis</h1> <p>Upload your documents for intelligent analysis using AI agents</p> </div> """) with gr.Row(): with gr.Column(): # API Keys Section gr.HTML("<div class='api-section'>") gr.Markdown("### π API Keys") gr.Markdown("Enter your API keys below. They are used securely and not stored.") anthropic_key = gr.Textbox( label="Anthropic API Key", placeholder="Enter your Anthropic API key...", type="password", info="Get your key from: https://console.anthropic.com/" ) landing_ai_key = gr.Textbox( label="LandingAI API Key", placeholder="Enter your LandingAI API key...", type="password", info="Get your key from: https://landing.ai/" ) gr.HTML("</div>") # File Upload Section gr.Markdown("### π Upload Document") file_input = gr.File( label="Select your document (.pdf, .png, .jpg, .jpeg, .bmp, .tiff)", file_types=[".pdf", ".png", ".jpg", ".jpeg", ".bmp", ".tiff"], file_count="single" ) # Process Button process_btn = gr.Button( "π Analyze Document", variant="primary", size="lg" ) with gr.Column(): # Results Section gr.Markdown("### π Analysis Results") output = gr.Textbox( label="Results", placeholder="Upload a document and click 'Analyze Document' to see results here...", lines=20, max_lines=30, show_copy_button=True ) # Examples section # Set up the event handler process_btn.click( fn=process_document, inputs=[file_input, anthropic_key, landing_ai_key], outputs=output, show_progress=True ) return demo
# Launch the applicationif __name__ == "__main__": demo = create_interface() demo.launch( server_name="0.0.0.0", # Important for HuggingFace deployment server_port=7860, # Default port for HuggingFace share=False, show_error=True )12gradiocrewai12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091# import os# import requests# from crewai.tools import tool# from dotenv import load_dotenv
# # Load environment variables# load_dotenv()
# @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) # return response.json()
import osimport requestsfrom crewai.tools import tool
@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") if not api_key: return "Error: LANDING_AI_API_KEY environment variable is not set" # API endpoint url = "https://api.va.landing.ai/v1/tools/agentic-document-analysis" try: # 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) # Check if request was successful if response.status_code == 200: return response.json() else: return f"API Error: {response.status_code} - {response.text}" except FileNotFoundError: return f"Error: File not found at path: {file_path}" except Exception as e: return f"Error processing file: {str(e)}"config/agents.yamlAdded+8
config/tasks.yamlAdded+9
crew.pyAdded+111
main.pyAdded+247
requirements.txtAdded+2
tools/custom_tool.pyAdded+91