Spaces:
Sleeping
Sleeping
import gradio as gr | |
from markitdown import MarkItDown | |
import google.generativeai as genai | |
import tempfile | |
import os | |
from pathlib import Path | |
# Initialize MarkItDown | |
md = MarkItDown() | |
# Configure Gemini AI | |
genai.configure(api_key=os.getenv('GEMINI_KEY')) | |
model = genai.GenerativeModel('gemini-1.5-flash') | |
def process_with_markitdown(input_path): | |
"""Process file or URL with MarkItDown and return text content""" | |
try: | |
result = md.convert(input_path) | |
return result.text_content | |
except Exception as e: | |
return f"Error processing input: {str(e)}" | |
def save_uploaded_file(file): | |
"""Save uploaded file to temporary location and return path""" | |
if file is None: | |
return None | |
try: | |
temp_dir = tempfile.gettempdir() | |
temp_path = os.path.join(temp_dir, file.name) | |
with open(temp_path, 'wb') as f: | |
f.write(file.read()) | |
return temp_path | |
except Exception as e: | |
return f"Error saving file: {str(e)}" | |
async def summarize_text(text): | |
"""Summarize the input text using Gemini AI""" | |
try: | |
prompt = f"""Please provide a concise summary of the following text. Focus on the main points and key takeaways: | |
{text} | |
Summary:""" | |
response = await model.generate_content_async(prompt) | |
return response.text | |
except Exception as e: | |
return f"Error generating summary: {str(e)}" | |
async def process_input(input_text, uploaded_file=None): | |
"""Main function to process either URL or uploaded file""" | |
try: | |
if uploaded_file is not None: | |
# Handle file upload | |
temp_path = save_uploaded_file(uploaded_file) | |
if temp_path.startswith('Error'): | |
return temp_path | |
text = process_with_markitdown(temp_path) | |
# Clean up temporary file | |
try: | |
os.remove(temp_path) | |
except: | |
pass | |
elif input_text.startswith(('http://', 'https://')): | |
# Handle URL | |
text = process_with_markitdown(input_text) | |
else: | |
# Handle direct text input | |
text = input_text | |
if text.startswith('Error'): | |
return text | |
# Generate summary using Gemini AI | |
summary = await summarize_text(text) | |
return summary | |
except Exception as e: | |
return f"Error processing input: {str(e)}" | |
# Create Gradio interface with drag-and-drop | |
with gr.Blocks(css=""" | |
.upload-box { | |
border: 2px dashed #ccc; | |
border-radius: 8px; | |
padding: 20px; | |
text-align: center; | |
transition: border-color 0.3s ease; | |
} | |
.upload-box:hover, .upload-box.dragover { | |
border-color: #666; | |
} | |
""") as iface: | |
gr.Markdown("# Text Summarization Tool") | |
gr.Markdown("Enter a URL, paste text, or drag & drop a file to get a summary.") | |
with gr.Row(): | |
input_text = gr.Textbox( | |
label="Enter URL or text", | |
placeholder="Enter a URL or paste text here...", | |
scale=2 | |
) | |
with gr.Row(): | |
file_upload = gr.File( | |
label="Drop files here or click to upload", | |
file_types=[ | |
".pdf", ".docx", ".xlsx", ".csv", ".txt", ".md", | |
".html", ".htm", ".xml", ".json" | |
], | |
file_count="single", | |
scale=2, | |
elem_classes=["upload-box"] | |
) | |
with gr.Row(): | |
submit_btn = gr.Button("Summarize", variant="primary") | |
clear_btn = gr.Button("Clear") | |
output_text = gr.Textbox(label="Summary", lines=10) | |
# Add JavaScript for drag-and-drop highlighting | |
gr.JS(""" | |
function setupDragDrop() { | |
const uploadBox = document.querySelector('.upload-box'); | |
['dragenter', 'dragover'].forEach(eventName => { | |
uploadBox.addEventListener(eventName, (e) => { | |
e.preventDefault(); | |
uploadBox.classList.add('dragover'); | |
}); | |
}); | |
['dragleave', 'drop'].forEach(eventName => { | |
uploadBox.addEventListener(eventName, (e) => { | |
e.preventDefault(); | |
uploadBox.classList.remove('dragover'); | |
}); | |
}); | |
} | |
// Call setup when the page loads | |
if (document.readyState === 'complete') { | |
setupDragDrop(); | |
} else { | |
window.addEventListener('load', setupDragDrop); | |
} | |
""") | |
# Set up event handlers | |
submit_btn.click( | |
fn=process_input, | |
inputs=[input_text, file_upload], | |
outputs=output_text | |
) | |
clear_btn.click( | |
fn=lambda: (None, None, ""), | |
inputs=None, | |
outputs=[input_text, file_upload, output_text] | |
) | |
# Add examples | |
gr.Examples( | |
examples=[ | |
["https://example.com/article"], | |
["This is a sample text that needs to be summarized..."], | |
], | |
inputs=input_text genai.configure(api_key=os.getenv('GEMINI_KEY')) | |
model = genai.GenerativeModel('gemini-1.5-flash') | |
) | |
if __name__ == "__main__": | |
iface.launch() |