geekphoenix's picture
Update app.py
22b79f1 verified
#!/usr/bin/env python
import os
import tempfile
import gradio as gr
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 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 interface
def 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 application
if __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
)