Spaces:
Paused
Paused
Update app.py
Browse files30 unmodified lines3132333435363738394041424398 unmodified lines14214314414514614731 unmodified lines1791801811821831841851861871881891901911921931941951961971981992002012022032046 unmodified lines21121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125220 unmodified lines27327427527627727827928028128228328449 unmodified lines33433533633733833930 unmodified lines3703713723733743753767 unmodified lines38438538638738838939021 unmodified lines41241341441541641741841942042142242342442542642742822 unmodified lines45145245345445545645745845946046146246346446546646746846947047147230 unmodified linesself.groq_models = self._fetch_groq_models()def _fetch_groq_models(self) -> Dict[str, str]:"""Fetch available Groq models"""try:headers = {"Authorization": f"Bearer {os.getenv('GROQ_API_KEY')}","Content-Type": "application/json"}response = requests.get("https://api.groq.com/openai/v1/models", headers=headers)if response.status_code == 200:models = response.json().get("data", [])return {model["id"]: model["id"] for model in models}98 unmodified linesreturn "\n\n".join(prompts)def send_to_hf_inference(prompt: str, model_name: str, api_key: str) -> str:"""Send prompt to HuggingFace using Inference API"""try:31 unmodified linesreturn f"Error with Groq API: {e}"def copy_to_clipboard(text: str) -> str:"""Copy text to clipboard"""return "Text copied to clipboard!"def open_chatgpt() -> str:"""Open ChatGPT in browser"""webbrowser.open('https://chat.openai.com/')return "Opening ChatGPT in browser..."def process_pdf(pdf, fmt, ctx_size, snippet_num, prompt, model_selection,hf_model_choice, hf_custom_model, hf_api_key,groq_model_choice, groq_api_key) -> Tuple[str, str, str, List[str]]:"""Process PDF and generate summary"""try:if not pdf:return "Please upload a PDF file.", "", "", []# Extract texttext = extract_text_from_pdf(pdf.name)if text.startswith("Error"):return text, "", "", []# Format contentformatted_text = format_content(text, fmt)6 unmodified linesfull_prompt = build_prompts(snippets, default_prompt, prompt, snippet_num)if isinstance(full_prompt, str) and full_prompt.startswith("Error"):return full_prompt, "", "", []# Process with selected modelif model_selection == "HuggingFace Inference":if not hf_api_key:return "HuggingFace API key required.", full_prompt, "", []model_id = hf_custom_model if hf_model_choice == "Custom Model" else model_registry.hf_models[hf_model_choice]summary = send_to_hf_inference(full_prompt, model_id, hf_api_key)elif model_selection == "Groq API":if not groq_api_key:return "Groq API key required.", full_prompt, "", []summary = send_to_groq(full_prompt, groq_model_choice, groq_api_key)else: # OpenAI ChatGPTsummary = "Please use the Copy Prompt button and paste into ChatGPT."# Save files for downloadfiles_to_download = []with tempfile.NamedTemporaryFile(delete=False, mode='w', suffix='.txt') as prompt_file:prompt_file.write(full_prompt)files_to_download.append(prompt_file.name)if summary != "Please use the Copy Prompt button and paste into ChatGPT.":with tempfile.NamedTemporaryFile(delete=False, mode='w', suffix='.txt') as summary_file:summary_file.write(summary)files_to_download.append(summary_file.name)return "Processing complete!", full_prompt, summary, files_to_downloadexcept Exception as e:logging.error(f"Error processing PDF: {e}")return f"Error processing PDF: {str(e)}", "", "", []# Main Interfacewith gr.Blocks(theme=gr.themes.Default()) as demo:20 unmodified lineslabel="π Output Format")gr.Markdown("### Context Window Size")with gr.Row():context_buttons = []for size_name, size_value in CONTEXT_SIZES.items():btn = gr.Button(size_name)context_buttons.append((btn, size_value))context_size = gr.Slider(minimum=1000,49 unmodified linestype="password")# Right Column - Outputwith gr.Column(scale=1):process_button = gr.Button("π Process PDF", variant="primary")30 unmodified linesdef toggle_model_options(choice):return (gr.update(visible=choice == "HuggingFace Inference"),gr.update(visible=choice == "Groq API"))def refresh_groq_models_list():7 unmodified linesmodel_choice.change(toggle_model_options,inputs=[model_choice],outputs=[hf_options, groq_options])for btn, size_value in context_buttons:21 unmodified linesformat_type,context_size,snippet_number,custom_prompt,model_choice,hf_model,hf_custom_model,hf_api_key,groq_model,groq_api_key],outputs=[progress_status,generated_prompt,summary_output,download_files]22 unmodified lines1. Upload a PDF document2. Choose output format and context window size3. Select snippet number (default: 1) or enter custom prompt4. Select your preferred model:- OpenAI ChatGPT: Manual copy/paste workflow- HuggingFace Inference: Direct API integration- Groq API: High-performance inference5. Click 'Process PDF' to generate summary6. Use 'Copy Prompt' and 'Open ChatGPT' for manual processing7. Download generated files as needed### βοΈ Features:- Support for multiple PDF formats- Flexible text formatting options- Predefined context window sizes (4K to 200K)- Multiple model integrations- Copy to clipboard functionality- Direct ChatGPT integration- Downloadable outputs""")# Launch the interface30 unmodified lines3132333435363738394041424344454647484998 unmodified lines14814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418531 unmodified lines2172182192202212222232242252262272282292302312322332342352362372382392402412422436 unmodified lines25025125225325425525625725825926026126226326426526620 unmodified lines28728828929029129229329429529629729829930030130230330449 unmodified lines35435535635735835936036136236336436536630 unmodified lines3973983994004014024034047 unmodified lines41241341441541641741821 unmodified lines44044144244344444544644744844945045145245345445545645745845946046146246346446546646746846922 unmodified lines49249349449549649749849950050150250350430 unmodified linesself.groq_models = self._fetch_groq_models()def _fetch_groq_models(self) -> Dict[str, str]:"""Fetch available Groq models with proper error handling"""try:groq_api_key = os.getenv('GROQ_API_KEY')if not groq_api_key:logging.warning("No GROQ_API_KEY found in environment")return self._get_default_groq_models()headers = {"Authorization": f"Bearer {groq_api_key}","Content-Type": "application/json"}response = requests.get("https://api.groq.com/openai/v1/models", headers=headers)if response.status_code == 200:models = response.json().get("data", [])return {model["id"]: model["id"] for model in models}98 unmodified linesreturn "\n\n".join(prompts)def send_to_model(prompt, model_selection, hf_model_choice, hf_custom_model, hf_api_key,groq_model_choice, groq_api_key, openai_api_key):"""Send prompt to selected model"""try:if model_selection == "HuggingFace Inference":if not hf_api_key:return "HuggingFace API key required.", []model_id = hf_custom_model if hf_model_choice == "Custom Model" else model_registry.hf_models[hf_model_choice]summary = send_to_hf_inference(prompt, model_id, hf_api_key)elif model_selection == "Groq API":if not groq_api_key:return "Groq API key required.", []summary = send_to_groq(prompt, groq_model_choice, groq_api_key)elif model_selection == "OpenAI ChatGPT":if not openai_api_key:return "OpenAI API key required.", []# Implement OpenAI API call here# Save summary for downloadwith tempfile.NamedTemporaryFile(delete=False, mode='w', suffix='.txt') as summary_file:summary_file.write(summary)return summary, [summary_file.name]except Exception as e:logging.error(f"Error sending to model: {e}")return f"Error sending to model: {str(e)}", []def send_to_hf_inference(prompt: str, model_name: str, api_key: str) -> str:"""Send prompt to HuggingFace using Inference API"""try:31 unmodified linesreturn f"Error with Groq API: {e}"def copy_to_clipboard(text: str) -> str:"""Copy text to clipboard using JavaScript"""return """navigator.clipboard.writeText(text).then(() => gradioApp().querySelector('#progress_status').value = 'Copied to clipboard!').catch(() => gradioApp().querySelector('#progress_status').value = 'Failed to copy');"""def open_chatgpt() -> None:"""Open ChatGPT in new browser tab"""return """window.open('https://chat.openai.com/', '_blank');"""def process_pdf(pdf, fmt, ctx_size, snippet_num, prompt):"""Generate prompt from PDF without model processing"""try:if not pdf:return "Please upload a PDF file.", "", []# Extract texttext = extract_text_from_pdf(pdf.name)if text.startswith("Error"):return text, "", []# Format contentformatted_text = format_content(text, fmt)6 unmodified linesfull_prompt = build_prompts(snippets, default_prompt, prompt, snippet_num)if isinstance(full_prompt, str) and full_prompt.startswith("Error"):return full_prompt, "", []# Save prompt for downloadwith tempfile.NamedTemporaryFile(delete=False, mode='w', suffix='.txt') as prompt_file:prompt_file.write(full_prompt)return "Prompt generated!", full_prompt, [prompt_file.name]except Exception as e:logging.error(f"Error processing PDF: {e}")return f"Error processing PDF: {str(e)}", "", []# Main Interfacewith gr.Blocks(theme=gr.themes.Default()) as demo:20 unmodified lineslabel="π Output Format")gr.Markdown("### Context Size")with gr.Row():for size_name, size_value in CONTEXT_SIZES.items():gr.Button(size_name,size="sm", # Make buttons smallerscale=1 # Equal scaling).click(lambda v=size_value: v,None,context_size)context_size = gr.Slider(minimum=1000,49 unmodified linestype="password")# In the UI section, add OpenAI API key input:with gr.Column(visible=False) as openai_options:openai_api_key = gr.Textbox(label="π OpenAI API Key",type="password")# Right Column - Outputwith gr.Column(scale=1):process_button = gr.Button("π Process PDF", variant="primary")30 unmodified linesdef toggle_model_options(choice):return (gr.update(visible=choice == "HuggingFace Inference"),gr.update(visible=choice == "Groq API"),gr.update(visible=choice == "OpenAI ChatGPT"))def refresh_groq_models_list():7 unmodified linesmodel_choice.change(toggle_model_options,inputs=[model_choice],outputs=[hf_options, groq_options, openai_options])for btn, size_value in context_buttons:21 unmodified linesformat_type,context_size,snippet_number,custom_prompt],outputs=[progress_status,generated_prompt,download_files])# Add a new button for sending to modelsend_button = gr.Button("π Send to Model", variant="primary")send_button.click(send_to_model,inputs=[generated_prompt,model_choice,hf_model,hf_custom_model,hf_api_key,groq_model,groq_api_key,openai_api_key],outputs=[summary_output,download_files]22 unmodified lines1. Upload a PDF document2. Choose output format and context window size3. Select snippet number (default: 1) or enter custom prompt4. Select your preferred model in case you want to proceed directly (or continue with 5):- OpenAI ChatGPT: Manual copy/paste workflow- HuggingFace Inference: Direct API integration- Groq API: High-performance inference5. Click 'Process PDF' to generate summary6. Use 'Copy Prompt' and, optionally, 'Open ChatGPT' for manual processing7. Download generated files as needed""")# Launch the interface
app.py+98-66