Spaces:
Paused
Paused
Update app.py
Browse files264 unmodified lines265266267268269270271272273274275276277278279280281282283284285286287288294 unmodified lines5835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196203 unmodified lines6246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576583 unmodified lines6626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007012 unmodified lines70470570670770870971071171271371471571671771871972072172272319 unmodified lines7437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757769 unmodified lines7867877887897907917927937947957967977987998008018028038043 unmodified lines808809810811812813814264 unmodified lineslogging.error(f"Error with OpenAI API: {e}")return f"Error with OpenAI API: {e}"def copy_to_clipboard(element_id: str) -> str:return f"""() => {{try {{const text = document.querySelector('#{element_id} textarea').value;navigator.clipboard.writeText(text);return "Copied to clipboard!";}} catch (e) {{console.error(e);return "Failed to copy to clipboard";}}}}"""def open_chatgpt_old() -> str:webbrowser.open_new_tab('https://chat.openai.com')return "Opening ChatGPT in new tab"def open_chatgpt() -> str:"""Open ChatGPT in new browser tab"""return """window.open('https://chat.openai.com/', '_blank');"""294 unmodified linesdef handle_model_selection(choice):"""Handle model selection and update UI"""ctx_size = get_model_context_size(choice)return {hf_options: gr.update(visible=choice == "HuggingFace Inference"),groq_options: gr.update(visible=choice == "Groq API"),openai_options: gr.update(visible=choice == "OpenAI ChatGPT"),context_size: gr.update(value=ctx_size)}# PDF Processing Handlersdef handle_pdf_process(pdf, fmt, ctx_size):"""Process PDF and update UI state"""if not pdf:return {progress_status: "Please upload a PDF file.",processed_text: "",pdf_content: "",snippets: [],snippet_selector: gr.update(choices=[], value=None),download_files: None}try:# Extract and format texttext = extract_text_from_pdf(pdf.name)if text.startswith("Error"):return {progress_status: text,processed_text: "",pdf_content: "",snippets: [],snippet_selector: gr.update(choices=[], value=None),download_files: None}formatted_text = format_content(text, fmt)snippets_list = split_into_snippets(formatted_text, ctx_size)3 unmodified linesf.write(formatted_text)download_file = f.namereturn {progress_status: f"PDF processed successfully! Generated {len(snippets_list)} snippets.",processed_text: formatted_text,pdf_content: formatted_text,snippets: snippets_list,snippet_selector: gr.update(choices=update_snippet_choices(snippets_list), value="Snippet 1 of " + str(len(snippets_list))),download_files: [download_file]}except Exception as e:error_msg = f"Error processing PDF: {str(e)}"logging.error(error_msg)return {progress_status: error_msg,processed_text: "",pdf_content: "",snippets: [],snippet_selector: gr.update(choices=[], value=None),download_files: None}def handle_snippet_selection(choice, snippets_list):"""Handle snippet selection and update prompt"""if not snippets_list:return {progress_status: "No snippets available.",generated_prompt: "",download_files: None}try:idx = get_snippet_index(choice)3 unmodified lineswith tempfile.NamedTemporaryFile(delete=False, mode='w', suffix='.txt') as f:f.write(selected_snippet)return {progress_status: f"Selected snippet {idx + 1}",generated_prompt: selected_snippet,download_files: [f.name]}except Exception as e:error_msg = f"Error selecting snippet: {str(e)}"logging.error(error_msg)return {progress_status: error_msg,generated_prompt: "",download_files: None}# Copy button handlersdef copy_text_js(element_id: str) -> str:return f"""() => {{const text = document.querySelector('#{element_id} textarea').value;navigator.clipboard.writeText(text);return "Copied to clipboard!";}}"""def handle_prompt_generation(snippet_text, template, snippet_choice, snippets_list):"""Generate prompt from selected snippet"""if not snippet_text or not snippets_list:return {progress_status: "No text available for prompt generation.",generated_prompt: "",download_files: None}try:idx = get_snippet_index(snippet_choice)prompt = generate_prompt(snippets_list[idx], template or "Summarize the following text:")2 unmodified lineswith tempfile.NamedTemporaryFile(delete=False, mode='w', suffix='.txt') as f:f.write(prompt)return {progress_status: "Prompt generated successfully!",generated_prompt: prompt,download_files: [f.name]}except Exception as e:error_msg = f"Error generating prompt: {str(e)}"logging.error(error_msg)return {progress_status: error_msg,generated_prompt: "",download_files: None}def handle_copy_action(text):"""Handle copy to clipboard action"""19 unmodified linesgenerate_prompt_btn.click(handle_prompt_generation,inputs=[generated_prompt, custom_prompt, snippet_selector, snippets],outputs={progress_status: progress_status,generated_prompt: generated_prompt,download_files: download_files})# Snippet handlingsnippet_selector.change(handle_snippet_selection,inputs=[snippet_selector, snippets],outputs={progress_status: progress_status,generated_prompt: generated_prompt,download_files: download_files})# Model selectionmodel_choice.change(handle_model_selection,inputs=[model_choice],outputs={hf_options: hf_options,groq_options: groq_options,openai_options: openai_options,context_size: context_size})hf_model.change(9 unmodified lines)# Context size buttons"""for size_name, size_value in CONTEXT_SIZES.items():gr.Button(size_name, size="sm").click(update_context_size,inputs=[],outputs=context_size).success(lambda s=size_value: int(s),None,context_size) """# Download handlersfor btn, content in [(download_full_text, pdf_content),(download_snippet, generated_prompt),3 unmodified linesbtn.click(lambda x: [x] if x else None,inputs=[content],outputs=download_files)# Copy button handlers264 unmodified lines265266267268269270271272273274275276277278279280281282283284285286287294 unmodified lines5825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186193 unmodified lines6236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566573 unmodified lines6616626636646656666676686696706716726736746756766776786796806816826836846856866872 unmodified lines69069169269369469569669769869970070119 unmodified lines7217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537549 unmodified lines7647657667677687697707717727737747757767777787797807813 unmodified lines785786787788789790791264 unmodified lineslogging.error(f"Error with OpenAI API: {e}")return f"Error with OpenAI API: {e}"def copy_text_js(element_id: str) -> str:return f"""() => {{try {{const elem = document.querySelector('#{element_id} textarea');if (!elem) throw new Error('Element not found');const text = elem.value;if (!text) throw new Error('No text to copy');navigator.clipboard.writeText(text);return "Copied to clipboard!";}} catch (e) {{console.error(e);return "Failed to copy: " + e.message;}}}}"""def open_chatgpt() -> str:"""Open ChatGPT in new browser tab"""return """window.open('https://chat.openai.com/', '_blank');"""294 unmodified linesdef handle_model_selection(choice):"""Handle model selection and update UI"""ctx_size = get_model_context_size(choice)return (gr.update(visible=choice == "HuggingFace Inference"), # hf_optionsgr.update(visible=choice == "Groq API"), # groq_optionsgr.update(visible=choice == "OpenAI ChatGPT"), # openai_optionsgr.update(value=ctx_size) # context_size)# PDF Processing Handlersdef handle_pdf_process(pdf, fmt, ctx_size):"""Process PDF and update UI state"""if not pdf:return ("Please upload a PDF file.", # progress_status"", # processed_text"", # pdf_content[], # snippetsgr.update(choices=[], value=None), # snippet_selectorNone # download_files)try:# Extract and format texttext = extract_text_from_pdf(pdf.name)if text.startswith("Error"):return (text,"","",[],gr.update(choices=[], value=None),None)formatted_text = format_content(text, fmt)snippets_list = split_into_snippets(formatted_text, ctx_size)3 unmodified linesf.write(formatted_text)download_file = f.namereturn (f"PDF processed successfully! Generated {len(snippets_list)} snippets.",formatted_text,formatted_text,snippets_list,gr.update(choices=update_snippet_choices(snippets_list), value="Snippet 1 of " + str(len(snippets_list))),[download_file])except Exception as e:error_msg = f"Error processing PDF: {str(e)}"logging.error(error_msg)return (error_msg,"","",[],gr.update(choices=[], value=None),None)def handle_snippet_selection(choice, snippets_list):"""Handle snippet selection and update prompt"""if not snippets_list:return ("No snippets available.", # progress_status"", # generated_promptNone # download_files)try:idx = get_snippet_index(choice)3 unmodified lineswith tempfile.NamedTemporaryFile(delete=False, mode='w', suffix='.txt') as f:f.write(selected_snippet)return (f"Selected snippet {idx + 1}",selected_snippet,[f.name])except Exception as e:error_msg = f"Error selecting snippet: {str(e)}"logging.error(error_msg)return (error_msg,"",None)# Copy button handlersdef handle_prompt_generation(snippet_text, template, snippet_choice, snippets_list):"""Generate prompt from selected snippet"""if not snippet_text or not snippets_list:return "No text available for prompt generation.", "", Nonetry:idx = get_snippet_index(snippet_choice)prompt = generate_prompt(snippets_list[idx], template or "Summarize the following text:")2 unmodified lineswith tempfile.NamedTemporaryFile(delete=False, mode='w', suffix='.txt') as f:f.write(prompt)return "Prompt generated successfully!", prompt, [f.name]except Exception as e:error_msg = f"Error generating prompt: {str(e)}"logging.error(error_msg)return error_msg, "", Nonedef handle_copy_action(text):"""Handle copy to clipboard action"""19 unmodified linesgenerate_prompt_btn.click(handle_prompt_generation,inputs=[generated_prompt, custom_prompt, snippet_selector, snippets],outputs=[progress_status,generated_prompt,download_files])# Snippet handlingsnippet_selector.change(handle_snippet_selection,inputs=[snippet_selector, snippets],outputs=[progress_status,generated_prompt,download_files])# Model selectionmodel_choice.change(handle_model_selection,inputs=[model_choice],outputs=[hf_options,groq_options,openai_options,context_size])hf_model.change(9 unmodified lines)# Context size buttonsfor size_name, size_value in CONTEXT_SIZES.items():gr.Button(size_name,size="sm",scale=1).click(lambda v=size_value: gr.update(value=v),None,context_size)# Download handlers (simplified)for btn, content in [(download_full_text, pdf_content),(download_snippet, generated_prompt),3 unmodified linesbtn.click(lambda x: [x] if x else None,inputs=[content],outputs=[download_files])# Copy button handlers
app.py+88-111