Spaces:
Paused
Paused
Update app.py
Browse files21 unmodified lines222324252627120 unmodified lines1481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951967 unmodified lines2042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422431 unmodified line2452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074088 unmodified lines4174184194204214224234244254264274282 unmodified lines43143243343443543643743843944044144244344444544644744844945045145245345445545645745845946011 unmodified lines47247347447547647747847948048148248348448548648748848949049149221 unmodified lines"200K": 200000}class ModelRegistry:def __init__(self):self.hf_models = {120 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:client = InferenceClient(api_key=api_key)messages = [{"role": "user", "content": prompt}]completion = client.chat.completions.create(model=model_name,messages=messages,max_tokens=500)return completion.choices[0].message.contentexcept Exception as e:logging.error(f"Error with HF inference: {e}")return f"Error with HF inference: {e}"7 unmodified lines}data = {"model": model_name,"messages": [{"role": "user", "content": prompt}]}response = requests.post("https://api.groq.com/openai/v1/chat/completions",headers=headers,json=data)return response.json()["choices"][0]["message"]["content"]except Exception as e:logging.error(f"Error with Groq API: {e}")return 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)1 unmodified line# Split into snippetssnippets = split_into_snippets(formatted_text, ctx_size)# Build promptsdefault_prompt = "Summarize the following text:"full_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:# Store context size valuecontext_size_value = gr.State(value=32000)# Headergr.Markdown("# 📄 Smart PDF Summarizer")gr.Markdown("Upload a PDF document and get AI-powered summaries using various AI models.")# Main Contentwith gr.Row():# Left Column - Input Optionswith gr.Column(scale=1):pdf_input = gr.File(label="📁 Upload PDF",file_types=[".pdf"])with gr.Row():format_type = gr.Radio(choices=["txt", "md", "html"],value="txt",label="📝 Output Format")# First define the slidercontext_size = gr.Slider(minimum=1000,maximum=200000,step=1000,value=32000,label="📏 Custom Context Size")# Then define the context size buttonsgr.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,maximum=200000,step=1000,value=32000,label="📏 Custom Context Size")snippet_number = gr.Number(label="🔢 Snippet Number",value=1,precision=0)custom_prompt = gr.Textbox(label="✍️ Custom Prompt",placeholder="Enter your custom prompt here...",lines=2)model_choice = gr.Radio(choices=["OpenAI ChatGPT", "HuggingFace Inference", "Groq API"],value="OpenAI ChatGPT",label="🤖 Model Selection")with gr.Column(visible=False) as hf_options:hf_model = gr.Dropdown(choices=list(model_registry.hf_models.keys()),label="🔧 HuggingFace Model",value="Phi-3 Mini 128k")hf_custom_model = gr.Textbox(label="Custom Model ID",placeholder="Enter custom model ID...",visible=False)hf_api_key = gr.Textbox(label="🔑 HuggingFace API Key",type="password")with gr.Column(visible=False) as groq_options:groq_model = gr.Dropdown(choices=list(model_registry.groq_models.keys()),label="🔧 Groq Model",value=list(model_registry.groq_models.keys())[0])groq_refresh_btn = gr.Button("🔄 Refresh Models")groq_api_key = gr.Textbox(label="🔑 Groq API Key",type="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")progress_status = gr.Textbox(label="📊 Progress",interactive=False)generated_prompt = gr.Textbox(label="📋 Generated Prompt",lines=10)with gr.Row():copy_prompt_button = gr.Button("📋 Copy Prompt")open_chatgpt_button = gr.Button("🌐 Open ChatGPT")summary_output = gr.Textbox(label="📝 Summary",lines=15)with gr.Row():copy_summary_button = gr.Button("📋 Copy Summary")download_files = gr.Files(label="📥 Download Files")# Event Handlersdef update_context_size(size):return gr.update(value=size)def toggle_model_options(choice):return (8 unmodified linesdef toggle_custom_model(model_name):return gr.update(visible=model_name == "Custom Model")# Connect event handlersmodel_choice.change(toggle_model_options,inputs=[model_choice],outputs=[hf_options, groq_options, openai_options])hf_model.change(2 unmodified linesoutputs=[hf_custom_model])groq_refresh_btn.click(refresh_groq_models_list,outputs=[groq_model])process_button.click(process_pdf,inputs=[pdf_input,format_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,11 unmodified lines])copy_prompt_button.click(copy_to_clipboard,inputs=[generated_prompt],outputs=[progress_status])copy_summary_button.click(copy_to_clipboard,inputs=[summary_output],outputs=[progress_status])open_chatgpt_button.click(open_chatgpt,outputs=[progress_status])# Instructions21 unmodified lines22232425262728293031323334353637120 unmodified lines1581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172187 unmodified lines2262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013021 unmodified line3043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565578 unmodified lines5665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757762 unmodified lines77978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583611 unmodified lines84884985085185285385485585621 unmodified lines"200K": 200000}MODEL_CONTEXT_SIZES = {"OpenAI ChatGPT": 4096,"HuggingFace Inference": 4096,"Groq API": {"llama-3.1-70b-versatile": 32768,"mixtral-8x7b-32768": 32768,"llama-3.1-8b-instant": 8192}}class ModelRegistry:def __init__(self):self.hf_models = {120 unmodified linesreturn "\n\n".join(prompts)def send_to_model(*args, **kwargs):try:with gr.Progress() as progress:progress(0, "Preparing to send to model...")result = send_to_model_impl(*args, **kwargs)progress(1, "Complete!")return resultexcept Exception as e:return f"Error: {str(e)}", Nonedef send_to_model_impl(prompt, model_selection, hf_model_choice, hf_custom_model, hf_api_key,groq_model_choice, groq_api_key, openai_api_key):"""Implementation of send to model functionality"""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.", []summary = send_to_openai(prompt, openai_api_key)else:return "Invalid model selection.", []if summary.startswith("Error"):return summary, []# Save summary for downloadwith tempfile.NamedTemporaryFile(delete=False, mode='w', suffix='.txt') as f:f.write(summary)return summary, [f.name]def send_to_hf_inference(prompt: str, model_name: str, api_key: str) -> str:"""Send prompt to HuggingFace using Inference API"""try:client = InferenceClient(token=api_key)response = client.text_generation(prompt,model=model_name,max_new_tokens=500,temperature=0.7,details=True, # Get full response detailsstream=False # Don't stream output)return response.generated_text # Return just the generated textexcept Exception as e:logging.error(f"Error with HF inference: {e}")return f"Error with HF inference: {e}"7 unmodified lines}data = {"model": model_name,"messages": [{"role": "user", "content": prompt}],"temperature": 0.7,"max_tokens": 500}response = requests.post("https://api.groq.com/openai/v1/chat/completions",headers=headers,json=data)if response.status_code != 200:return f"Error: Groq API returned status {response.status_code}"response_json = response.json()if "choices" not in response_json or not response_json["choices"]:return "Error: No response from Groq API"return response_json["choices"][0]["message"]["content"]except Exception as e:logging.error(f"Error with Groq API: {e}")return f"Error with Groq API: {e}"def send_to_openai(prompt: str, api_key: str) -> str:"""Send prompt to OpenAI API"""try:import openaiopenai.api_key = api_keyresponse = openai.ChatCompletion.create(model="gpt-3.5-turbo",messages=[{"role": "user", "content": prompt}],temperature=0.7,max_tokens=500)return response.choices[0].message.contentexcept Exception as e:logging.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');"""def process_pdf(pdf, fmt, ctx_size):"""Process PDF and return text and snippets"""try:if not pdf:return "Please upload a PDF file.", "", [], None# Extract texttext = extract_text_from_pdf(pdf.name)if text.startswith("Error"):return text, "", [], None# Format contentformatted_text = format_content(text, fmt)1 unmodified line# Split into snippetssnippets = split_into_snippets(formatted_text, ctx_size)# Save full text for downloadwith tempfile.NamedTemporaryFile(delete=False, mode='w', suffix='.txt') as text_file:text_file.write(formatted_text)snippet_choices = [f"Snippet {i+1} of {len(snippets)}" for i in range(len(snippets))]return ("PDF processed successfully!",formatted_text,snippets,snippet_choices,[text_file.name])except Exception as e:logging.error(f"Error processing PDF: {e}")return f"Error processing PDF: {str(e)}", "", [], Nonedef generate_prompt(text, template, snippet_idx=None):"""Generate prompt from text or selected snippet"""try:if not text:return "No text available.", "", Nonedefault_prompt = "Summarize the following text:"prompt_template = template if template else default_promptif isinstance(text, list):# If text is list of snippetsif snippet_idx is not None:if 0 <= snippet_idx < len(text):content = text[snippet_idx]else:return "Invalid snippet index.", "", Noneelse:content = "\n\n".join(text)else:content = textprompt = f"{prompt_template}\n---\n{content}\n---"# Save prompt for downloadwith tempfile.NamedTemporaryFile(delete=False, mode='w', suffix='.txt') as prompt_file:prompt_file.write(prompt)return "Prompt generated!", prompt, [prompt_file.name]except Exception as e:logging.error(f"Error generating prompt: {e}")return f"Error generating prompt: {str(e)}", "", Nonedef download_file(content: str, prefix: str = "file") -> List[str]:"""Create a downloadable file with content and better error handling"""if not content:return []try:with tempfile.NamedTemporaryFile(delete=False, mode='w', suffix='.txt', prefix=prefix) as f:f.write(content)return [f.name]except Exception as e:logging.error(f"Error creating download file: {e}")return []# Main Interfacewith gr.Blocks(theme=gr.themes.Default()) as demo:# State variablespdf_content = gr.State("")snippets = gr.State([])# Headergr.Markdown("# 📄 Smart PDF Summarizer")gr.Markdown("Upload a PDF document and get AI-powered summaries using various AI models.")with gr.Tabs() as tabs:# Tab 1: PDF Processingwith gr.Tab("1️⃣ PDF Processing"):with gr.Row():with gr.Column(scale=1):pdf_input = gr.File(label="📁 Upload PDF",file_types=[".pdf"])format_type = gr.Radio(choices=["txt", "md", "html"],value="txt",label="📝 Output Format")context_size = gr.Slider(minimum=1000,maximum=200000,step=1000,value=4096,label="Context Size")with gr.Row():for size_name, size_value in CONTEXT_SIZES.items():gr.Button(size_name,size="sm",scale=1).click(lambda v=size_value: v, # SimplifiedNone,context_size)process_button = gr.Button("🔍 Process PDF", variant="primary")with gr.Column(scale=1):progress_status = gr.Textbox(label="Status",interactive=False,show_label=True,visible=True # Ensure error messages are always visible)processed_text = gr.Textbox(label="Processed Text",lines=10,max_lines=50,show_copy_button=True)download_full_text = gr.Button("📥 Download Full Text")# Tab 2: Snippet Selectionwith gr.Tab("2️⃣ Snippet Selection"):with gr.Row():with gr.Column(scale=1):snippet_selector = gr.Dropdown(label="Select Snippet",choices=[],interactive=True)custom_prompt = gr.Textbox(label="✍️ Custom Prompt Template",placeholder="Enter your custom prompt here...",lines=2)generate_prompt_btn = gr.Button("Generate Prompt", variant="primary")with gr.Column(scale=1):generated_prompt = gr.Textbox(label="📋 Generated Prompt",lines=10,max_lines=50,show_copy_button=True,elem_id="generated_prompt" # Add this)with gr.Row():copy_prompt_button = gr.Button("📋 Copy Prompt")download_prompt = gr.Button("📥 Download Prompt")download_snippet = gr.Button("📥 Download Selected Snippet")# Tab 3: Model Processingwith gr.Tab("3️⃣ Model Processing"):with gr.Row():with gr.Column(scale=1):model_choice = gr.Radio(choices=["OpenAI ChatGPT", "HuggingFace Inference", "Groq API"],value="OpenAI ChatGPT",label="🤖 Model Selection")with gr.Column(visible=False) as openai_options:openai_api_key = gr.Textbox(label="🔑 OpenAI API Key",type="password")with gr.Column(visible=False) as hf_options:hf_model = gr.Dropdown(choices=list(model_registry.hf_models.keys()),label="🔧 HuggingFace Model",value="Phi-3 Mini 128k")hf_custom_model = gr.Textbox(label="Custom Model ID",visible=False)hf_api_key = gr.Textbox(label="🔑 HuggingFace API Key",type="password")with gr.Column(visible=False) as groq_options:groq_model = gr.Dropdown(choices=list(model_registry.groq_models.keys()),label="🔧 Groq Model")groq_refresh_btn = gr.Button("🔄 Refresh Models")groq_api_key = gr.Textbox(label="🔑 Groq API Key",type="password")send_to_model_btn = gr.Button("🚀 Send to Model", variant="primary")open_chatgpt_button = gr.Button("🌐 Open ChatGPT")with gr.Column(scale=1):summary_output = gr.Textbox(label="📝 Summary",lines=15,max_lines=50,show_copy_button=True,elem_id="summary_output" # Add this)with gr.Row():copy_summary_button = gr.Button("📋 Copy Summary")download_summary = gr.Button("📥 Download Summary")# Hidden components for file handlingdownload_files = gr.Files(label="📥 Downloads", visible=False)# Event Handlersdef update_context_size(size: int) -> None:"""Update context size slider with validation"""if not isinstance(size, (int, float)):size = 4096 # Default sizereturn gr.update(value=int(size))def get_model_context_size(choice: str, groq_model: str = None) -> int:"""Get context size for model with better defaults"""if choice == "Groq API" and groq_model:return MODEL_CONTEXT_SIZES["Groq API"].get(groq_model, 4096)elif choice == "OpenAI ChatGPT":return 4096elif choice == "HuggingFace Inference":return 4096return 32000 # Safe defaultdef update_snippet_choices(snippets_list: List[str]) -> List[str]:"""Create formatted snippet choices"""return [f"Snippet {i+1} of {len(snippets_list)}" for i in range(len(snippets_list))]def get_snippet_index(choice: str) -> int:"""Extract snippet index from choice string"""if not choice:return 0try:return int(choice.split()[1]) - 1except:return 0def toggle_model_options(choice):return (8 unmodified linesdef toggle_custom_model(model_name):return gr.update(visible=model_name == "Custom Model")def handle_model_change(choice):"""Handle model selection change"""return (gr.update(visible=choice == "HuggingFace Inference"),gr.update(visible=choice == "Groq API"),gr.update(visible=choice == "OpenAI ChatGPT"),update_context_size(choice))def handle_groq_model_change(model_name):"""Handle Groq model selection change"""return update_context_size("Groq API", model_name)def 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)# Create downloadable full textwith tempfile.NamedTemporaryFile(delete=False, mode='w', suffix='.txt') as f:f.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)selected_snippet = snippets_list[idx]# Create downloadable snippetwith 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:")# Create downloadable promptwith 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"""return {progress_status: gr.update(value="Text copied to clipboard!", visible=True)}# Connect all event handlers# Core event handlersprocess_button.click(handle_pdf_process,inputs=[pdf_input, format_type, context_size],outputs=dict(progress_status=progress_status,processed_text=processed_text,pdf_content=pdf_content,snippets=snippets,snippet_selector=snippet_selector,download_files=download_files))generate_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(2 unmodified linesoutputs=[hf_custom_model])groq_model.change(handle_groq_model_change,inputs=[groq_model],outputs=[context_size])# 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),(download_prompt, generated_prompt),(download_summary, summary_output)]:btn.click(lambda x: [x] if x else None,inputs=[content],outputs=download_files)# Copy button handlersfor btn, elem_id in [(copy_prompt_button, "generated_prompt"),(copy_summary_button, "summary_output")]:btn.click(fn=None,_js=copy_text_js(elem_id),outputs=progress_status)# ChatGPT handleropen_chatgpt_button.click(fn=None,_js="() => { window.open('https://chat.openai.com/', '_blank'); return 'Opened ChatGPT in new tab'; }",outputs=progress_status)# Model processingsend_to_model_btn.click(send_to_model,inputs=[generated_prompt,11 unmodified lines])groq_refresh_btn.click(refresh_groq_models_list,outputs=[groq_model])# Instructions
app.py+585-221