Spaces:
Sleeping
Sleeping
File size: 5,999 Bytes
ae43d88 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 |
#!/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
) |