Spaces:
Paused
Paused
Update app.py
Browse files78 unmodified lines79808182838472 unmodified lines157158159160161162163164165166373 unmodified lines54054154254354454554656 unmodified lines603604605606607608609610156 unmodified lines7677687697707717727 unmodified lines780781782783784785786787788789163 unmodified lines953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113854 unmodified lines1193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127297 unmodified lines1370137113721373137413751 unmodified line13771378137913801381138213835 unmodified lines138913901391139213931394139578 unmodified lines"openGPT-X/Teuken-7B-instruct-research-v0.4": 4096,"Qwen/Qwen2.5-7B-Instruct": 131072,"tiiuae/falcon-7b-instruct": 8192,},"Groq API": {"gemma2-9b-it": 8192,72 unmodified lines"Nous-Hermes": "NousResearch/Nous-Hermes-2-Mixtral-8x7B-DPO", # works well"Zephyr 7B": "HuggingFaceH4/zephyr-7b-beta", # works"Phi-3.5 Mini": "microsoft/Phi-3.5-mini-instruct", # works but poor results"Gemma 2 2B": "google/gemma-2-2b-it", # works but often busy"GPT2": "openai-community/gpt2", # works with token limits"Phi-2": "microsoft/phi-2", # works with token limits"TinyLlama 1.1B": "TinyLlama/TinyLlama-1.1B-Chat-v1.0", # works with token limits"DeepSeek Coder V2 (Pro)": "deepseek-ai/DeepSeek-Coder-V2-Instruct", # needs API key"Meta Llama 3.1 70B (Pro)": "meta-llama/Meta-Llama-3.1-70B-Instruct", # needs API key"Aya 23-35B (Pro)": "CohereForAI/aya-23-35B", # needs API key373 unmodified lines# 1. HTML component for clipboard action# 2. A success message for summary output# 3. The download filereturn gr.HTML(html_template), "Text copied to clipboard. Use paste for processing.", download_file# Get the summary based on model selection56 unmodified lineslogging.error(f"Error in send_to_model_impl: {error_msg}")return f"Error: {error_msg}", Nonedef send_to_hf_inference(prompt: str, model_name: str, api_key: str = None, use_rate_limit: bool = False) -> str:"""Send prompt to HuggingFace Inference API."""def _send():# Check token limits firstis_within_limits, error_msg = check_token_limits(prompt, model_name)156 unmodified linesreturn False, f"Prompt too long (estimated {estimated_tokens} tokens). This model supports max {max_tokens} tokens."return True, ""def copy_text_js(element_id: str) -> str:return f"""function() {{let textarea = document.getElementById('{element_id}');7 unmodified lines}}}}"""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:163 unmodified lines# Tab 3: Model Processingwith gr.Tab("3οΈβ£ Model Processing"):with gr.Row():with gr.Column(scale=1):model_choice = gr.Radio(choices=list(MODEL_CONTEXT_SIZES.keys()),value="Clipboard only",label="π€ Provider Selection")with gr.Column(visible=False) as openai_options:openai_model = gr.Dropdown(choices=list(MODEL_CONTEXT_SIZES["OpenAI ChatGPT"].keys()),value="gpt-3.5-turbo",label="OpenAI Model")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="Mistral 7B",allow_custom_value=True)hf_custom_model = gr.Textbox( # This needs to be defined before being usedlabel="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()), # Use model_registry.groq_modelsvalue=list(model_registry.groq_models.keys())[0] if model_registry.groq_models else None, # Set a default value if availablelabel="Groq Model")groq_api_key = gr.Textbox(label="π Groq API Key",type="password")groq_refresh_btn = gr.Button("π Refresh Groq Models") # Add refresh buttonwith gr.Column(visible=False) as glhf_options:glhf_api_key = gr.Textbox(label="π GLHF API Key",type="password")glhf_model = gr.Dropdown(choices=list(MODEL_CONTEXT_SIZES["GLHF API"].keys()) + ["Custom Model"],value="mistralai/Mistral-7B-Instruct-v0.3",label="Model Selection")glhf_custom_model = gr.Textbox(label="Custom Model ID (owner/model format)",placeholder="e.g., mistralai/Mixtral-8x7B-Instruct-v0.2",visible=False)# Add visibility toggledef toggle_glhf_custom_model(choice):return gr.update(visible=choice == "Custom Model")glhf_model.change(toggle_glhf_custom_model,inputs=[glhf_model],outputs=[glhf_custom_model])# Update Cohere options containerwith gr.Column(visible=False) as cohere_options:cohere_api_key = gr.Textbox(label="π Cohere API Key (optional - needed for some models)",type="password")cohere_model = gr.Dropdown(choices=["command-r-plus-08-2024","command-r-plus-04-2024","command-r","command","command-light"],value="command-r-plus-08-2024",label="Cohere Model")send_to_model_btn = gr.Button("π Send to Model", variant="primary")with gr.Row():chatgpt_button = gr.HTML("""<div style="text-align: center; margin: 10px;"><buttononclick="try {// Try all possible selectors for the prompt textareaconst promptArea =document.querySelector('#generated_prompt textarea') ||document.querySelector('textarea#generated_prompt') ||document.querySelector('.generated_prompt textarea') ||Array.from(document.querySelectorAll('textarea')).find(el => el.value.includes('Summarize'));if (promptArea && promptArea.value) {navigator.clipboard.writeText(promptArea.value).then(() => {this.textContent = 'β Copied! Opening ChatGPT...';setTimeout(() => {window.open('https://chat.openai.com/', '_blank');setTimeout(() => {this.textContent = 'π Copy Prompt & Open ChatGPT';}, 2000);}, 500);}).catch(err => {console.error('Modern copy failed:', err);// Fallback methodpromptArea.select();document.execCommand('copy');this.textContent = 'β Copied! Opening ChatGPT...';setTimeout(() => {window.open('https://chat.openai.com/', '_blank');setTimeout(() => {this.textContent = 'π Copy Prompt & Open ChatGPT';}, 2000);}, 500);});} else {this.textContent = 'β No prompt found. Generate one first.';setTimeout(() => {this.textContent = 'π Copy Prompt & Open ChatGPT';}, 2000);}} catch (err) {console.error('Copy error:', err);this.textContent = 'β Copy failed. Try again.';setTimeout(() => {this.textContent = 'π Copy Prompt & Open ChatGPT';}, 2000);}"style="padding: 10px 20px;background-color: #2C3E50;color: white;border: none;border-radius: 5px;font-weight: bold;cursor: pointer;transition: background-color 0.3s ease;"onmouseover="this.style.backgroundColor='#34495E'"onmouseout="this.style.backgroundColor='#2C3E50'">π Copy Prompt & Open ChatGPT</button></div>""")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():download_summary = gr.File(label="π₯ Download Summary")with gr.Row():clipboard_status = gr.HTML(elem_id="clipboard_status")# Hidden components for file handlingdownload_files = gr.Files(label="π₯ Downloads", visible=False)54 unmodified linesdef 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 = MODEL_CONTEXT_SIZES.get(choice, {})if isinstance(ctx_size, dict):first_model = list(ctx_size.keys())[0]ctx_size = ctx_size[first_model]if choice == "OpenAI ChatGPT":model_choices = list(MODEL_CONTEXT_SIZES["OpenAI ChatGPT"].keys())return [gr.update(visible=False), # hf_optionsgr.update(visible=False), # groq_optionsgr.update(visible=True), # openai_optionsgr.update(visible=False), # cohere_optionsgr.update(visible=False), # glhf_optionsgr.update(value=ctx_size), # context_sizegr.Dropdown(choices=model_choices, value=first_model) # openai_model]elif choice == "HuggingFace Inference":model_choices = list(model_registry.hf_models.keys())return [gr.update(visible=True), # hf_optionsgr.update(visible=False), # groq_optionsgr.update(visible=False), # openai_optionsgr.update(visible=False), # cohere_optionsgr.update(visible=False), # glhf_optionsgr.update(value=ctx_size), # context_sizegr.Dropdown(choices=model_choices, value="Mistral 7B") # Update default value]elif choice == "Groq API":model_choices = list(model_registry.groq_models.keys())return [gr.update(visible=False), # hf_optionsgr.update(visible=True), # groq_optionsgr.update(visible=False), # openai_optionsgr.update(visible=False), # cohere_optionsgr.update(visible=False), # glhf_optionsgr.update(value=ctx_size), # context_sizegr.Dropdown(choices=model_choices, value=model_choices[0] if model_choices else None)]elif choice == "Cohere API":return [gr.update(visible=False), # hf_optionsgr.update(visible=False), # groq_optionsgr.update(visible=False), # openai_optionsgr.update(visible=True), # cohere_optionsgr.update(visible=False), # glhf_optionsgr.update(value=ctx_size), # context_sizegr.Dropdown(choices=[]) # not used]elif choice == "GLHF API":# Always show HuggingFace models for GLHF since they're used in both cases# model_choices = list(model_registry.hf_models.keys())return [gr.update(visible=False), # hf_options - hide completelygr.update(visible=False), # groq_optionsgr.update(visible=False), # openai_optionsgr.update(visible=False), # cohere_optionsgr.update(visible=True), # glhf_optionsgr.update(value=ctx_size), # context_sizegr.Dropdown(choices=[]) # not used]# Default return for "Clipboard only" or other optionsreturn [gr.update(visible=False), # hf_optionsgr.update(visible=False), # groq_optionsgr.update(visible=False), # openai_optionsgr.update(visible=False), # cohere_optionsgr.update(visible=False), # glhf_optionsgr.update(value=4096), # context_sizegr.Dropdown(choices=[]) # not used]# PDF Processing Handlersdef handle_pdf_process(pdf, fmt, ctx_size): # Remove md_eng parameter97 unmodified linesoutputs=[progress_status, generated_prompt, download_prompt])# Snippet handlingsnippet_selector.change(handle_snippet_selection,1 unmodified lineoutputs=[progress_status, generated_prompt, download_snippet] # Connect download_snippet)# Model selection# Model selectionmodel_choice.change(handle_model_selection,5 unmodified linescohere_options,glhf_options,context_size,openai_model])78 unmodified lines7980818283848572 unmodified lines158159160161162163164165166167168169170171172173174373 unmodified lines54854955055155255355456 unmodified lines611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647156 unmodified lines8048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129137 unmodified lines921922923924925926163 unmodified lines10901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132954 unmodified lines13841385138613871388138997 unmodified lines148714881489149014911492149314941495149614971498149915001501150215031504150515061 unmodified line1508150915101511151215135 unmodified lines15191520152115221523152415251526152778 unmodified lines"openGPT-X/Teuken-7B-instruct-research-v0.4": 4096,"Qwen/Qwen2.5-7B-Instruct": 131072,"tiiuae/falcon-7b-instruct": 8192,"Qwen/QwQ-32B-preview": 32768, # Add QwQ model},"Groq API": {"gemma2-9b-it": 8192,72 unmodified lines"Nous-Hermes": "NousResearch/Nous-Hermes-2-Mixtral-8x7B-DPO", # works well"Zephyr 7B": "HuggingFaceH4/zephyr-7b-beta", # works"Phi-3.5 Mini": "microsoft/Phi-3.5-mini-instruct", # works but poor results"Phi-3 Mini 4K": "microsoft/phi-3-mini-4k-instruct", # good for small context"Phi-3 Mini 128K": "microsoft/Phi-3-mini-128k-instruct", # good for large context"Gemma 2 2B": "google/gemma-2-2b-it", # works but often busy"GPT2": "openai-community/gpt2", # works with token limits"Phi-2": "microsoft/phi-2", # works with token limits"TinyLlama 1.1B": "TinyLlama/TinyLlama-1.1B-Chat-v1.0", # works with token limits"DeepSeek Coder V2": "deepseek-ai/DeepSeek-Coder-V2-Instruct", # good for code"Falcon-7B": "tiiuae/falcon-7b-instruct", # reliable"Qwen 2.5 7B": "Qwen/Qwen2.5-7B-Instruct", # good performance"QwQ 32B Preview": "Qwen/QwQ-32B-preview", # special handling# Models requiring API key"DeepSeek Coder V2 (Pro)": "deepseek-ai/DeepSeek-Coder-V2-Instruct", # needs API key"Meta Llama 3.1 70B (Pro)": "meta-llama/Meta-Llama-3.1-70B-Instruct", # needs API key"Aya 23-35B (Pro)": "CohereForAI/aya-23-35B", # needs API key373 unmodified lines# 1. HTML component for clipboard action# 2. A success message for summary output# 3. The download filereturn gr.HTML(html_template), "Use Copy Text to Clipboard button below, then paste where you like.", download_file# Get the summary based on model selection56 unmodified lineslogging.error(f"Error in send_to_model_impl: {error_msg}")return f"Error: {error_msg}", Nonedef send_to_qwq(prompt: str):"""Send prompt to QwQ API."""try:from gradio_client import Clientclient = Client("Qwen/QwQ-32B-preview")# Call the add_text endpointresult = client.predict(_input={"files":[], "text": prompt},_chatbot=[],api_name="/add_text")# Call the agent_run endpointresponse = client.predict(_chatbot=result[1],api_name="/agent_run")return response[0].get('text', 'No response from QwQ')except Exception as e:logging.error(f"QwQ API error: {e}")return f"Error with QwQ API: {str(e)}"def send_to_hf_inference(prompt: str, model_name: str, api_key: str = None, use_rate_limit: bool = False) -> str:"""Send prompt to HuggingFace Inference API."""# Special handling for QwQif model_name == "Qwen/QwQ-32B-preview":return send_to_qwq(prompt)def _send():# Check token limits firstis_within_limits, error_msg = check_token_limits(prompt, model_name)156 unmodified linesreturn False, f"Prompt too long (estimated {estimated_tokens} tokens). This model supports max {max_tokens} tokens."return True, ""def copy_to_clipboard(text):return gr.HTML(f"""<script>navigator.clipboard.writeText(`{text}`).then(function() {{const btn = document.querySelector('button:contains("Copy to Clipboard")');btn.textContent = 'β Copied!';setTimeout(() => btn.textContent = 'π Copy to Clipboard', 2000);}},function(err) {{console.error('Failed to copy:', err);const btn = document.querySelector('button:contains("Copy to Clipboard")');btn.textContent = 'β Failed to copy';setTimeout(() => btn.textContent = 'π Copy to Clipboard', 2000);}});</script>""")def handle_model_selection(choice):"""Handle model selection and update UI"""ctx_size = MODEL_CONTEXT_SIZES.get(choice, {})if isinstance(ctx_size, dict):first_model = list(ctx_size.keys())[0]ctx_size = ctx_size[first_model]if choice == "OpenAI ChatGPT":model_choices = list(MODEL_CONTEXT_SIZES["OpenAI ChatGPT"].keys())return [gr.update(visible=False), # hf_optionsgr.update(visible=False), # groq_optionsgr.update(visible=True), # openai_optionsgr.update(visible=False), # cohere_optionsgr.update(visible=False), # glhf_optionsgr.update(value=ctx_size), # context_sizegr.update(interactive=True), # send_model_btngr.Dropdown(choices=model_choices, value=first_model), # openai_modelgr.update(visible=False) # hf_custom_model visibility]elif choice == "HuggingFace Inference":model_choices = list(MODEL_CONTEXT_SIZES["HuggingFace Inference"].keys())return [gr.update(visible=True), # hf_optionsgr.update(visible=False), # groq_optionsgr.update(visible=False), # openai_optionsgr.update(visible=False), # cohere_optionsgr.update(visible=False), # glhf_optionsgr.update(value=ctx_size), # context_sizegr.update(interactive=True), # send_model_btngr.Dropdown(choices=model_choices, value="mistralai/Mistral-7B-Instruct-v0.3"),gr.update(visible=False) # hf_custom_model initially hidden]elif choice == "Groq API":model_choices = list(model_registry.groq_models.keys())return [gr.update(visible=False), # hf_optionsgr.update(visible=True), # groq_optionsgr.update(visible=False), # openai_optionsgr.update(visible=False), # cohere_optionsgr.update(visible=False), # glhf_optionsgr.update(value=ctx_size), # context_sizegr.update(interactive=True), # send_model_btngr.Dropdown(choices=model_choices, value=model_choices[0] if model_choices else None),gr.update(visible=False) # hf_custom_model visibility]elif choice == "Cohere API":return [gr.update(visible=False), # hf_optionsgr.update(visible=False), # groq_optionsgr.update(visible=False), # openai_optionsgr.update(visible=True), # cohere_optionsgr.update(visible=False), # glhf_optionsgr.update(value=ctx_size), # context_sizegr.update(interactive=True), # send_model_btngr.Dropdown(choices=[]), # not usedgr.update(visible=False) # hf_custom_model visibility]elif choice == "GLHF API":model_choices = list(MODEL_CONTEXT_SIZES["GLHF API"].keys())return [gr.update(visible=False), # hf_optionsgr.update(visible=False), # groq_optionsgr.update(visible=False), # openai_optionsgr.update(visible=False), # cohere_optionsgr.update(visible=True), # glhf_optionsgr.update(value=ctx_size), # context_sizegr.update(interactive=True), # send_model_btngr.Dropdown(choices=[]), # not usedgr.update(visible=False) # hf_custom_model visibility]# Default return for "Clipboard only" or other optionsreturn [gr.update(visible=False), # hf_optionsgr.update(visible=False), # groq_optionsgr.update(visible=False), # openai_optionsgr.update(visible=False), # cohere_optionsgr.update(visible=False), # glhf_optionsgr.update(value=4096), # context_sizegr.update(interactive=False), # send_model_btngr.Dropdown(choices=[]), # not usedgr.update(visible=False) # hf_custom_model visibility]def copy_text_js(element_id: str) -> str:return f"""function() {{let textarea = document.getElementById('{element_id}');7 unmodified lines}}}}"""def process_pdf(pdf, fmt, ctx_size):"""Process PDF and return text and snippets"""try:163 unmodified lines# Tab 3: Model Processingwith gr.Tab("3οΈβ£ Model Processing"):with gr.Row():with gr.Column(scale=1):model_choice = gr.Radio(choices=list(MODEL_CONTEXT_SIZES.keys()),value="Clipboard only",label="π€ Provider Selection")# Model-specific option containerswith gr.Column(visible=False) as openai_options:openai_model = gr.Dropdown(choices=list(MODEL_CONTEXT_SIZES["OpenAI ChatGPT"].keys()),value="gpt-3.5-turbo",label="OpenAI Model")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_CONTEXT_SIZES["HuggingFace Inference"].keys()),label="π§ HuggingFace Model",value="mistralai/Mistral-7B-Instruct-v0.3",allow_custom_value=True)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()),value=list(model_registry.groq_models.keys())[0] if model_registry.groq_models else None,label="Groq Model")groq_api_key = gr.Textbox(label="π Groq API Key",type="password")groq_refresh_btn = gr.Button("π Refresh Groq Models")with gr.Column(visible=False) as glhf_options:glhf_api_key = gr.Textbox(label="π GLHF API Key",type="password")glhf_model = gr.Dropdown(choices=list(MODEL_CONTEXT_SIZES["GLHF API"].keys()),value="mistralai/Mistral-7B-Instruct-v0.3",label="Model Selection")with gr.Column(visible=False) as cohere_options:cohere_api_key = gr.Textbox(label="π Cohere API Key",type="password")cohere_model = gr.Dropdown(choices=list(MODEL_CONTEXT_SIZES["Cohere API"].keys()),value="command-r-plus-08-2024",label="Cohere Model")# Action Buttons Rowwith gr.Row():# Copy to Clipboard button with robust fallbackscopy_button = gr.HTML("""<div style="text-align: center; margin: 10px;"><buttononclick="try {const promptArea =document.querySelector('#generated_prompt textarea') ||document.querySelector('textarea#generated_prompt') ||document.querySelector('.generated_prompt textarea') ||Array.from(document.querySelectorAll('textarea')).find(el => el.value.includes('Summarize'));if (promptArea && promptArea.value) {navigator.clipboard.writeText(promptArea.value).then(() => {this.textContent = 'β Copied!';setTimeout(() => {this.textContent = 'π Copy to Clipboard';}, 2000);}).catch(err => {console.error('Modern copy failed:', err);promptArea.select();document.execCommand('copy');this.textContent = 'β Copied using fallback!';setTimeout(() => {this.textContent = 'π Copy to Clipboard';}, 2000);});} else {this.textContent = 'β No text found';setTimeout(() => {this.textContent = 'π Copy to Clipboard';}, 2000);}} catch (err) {console.error('Copy error:', err);this.textContent = 'β Copy failed';setTimeout(() => {this.textContent = 'π Copy to Clipboard';}, 2000);}"style="padding: 10px 20px;background-color: #2C3E50;color: white;border: none;border-radius: 5px;font-weight: bold;cursor: pointer;transition: background-color 0.3s ease;"onmouseover="this.style.backgroundColor='#34495E'"onmouseout="this.style.backgroundColor='#2C3E50'">π Copy to Clipboard</button></div>""")send_to_model_btn = gr.Button("π Send to Model", variant="primary", interactive=False)# Restore the robust ChatGPT button implementationchatgpt_button = gr.HTML("""<div style="text-align: center; margin: 10px;"><buttononclick="try {const promptArea =document.querySelector('#generated_prompt textarea') ||document.querySelector('textarea#generated_prompt') ||document.querySelector('.generated_prompt textarea') ||Array.from(document.querySelectorAll('textarea')).find(el => el.value.includes('Summarize'));if (promptArea && promptArea.value) {navigator.clipboard.writeText(promptArea.value).then(() => {this.textContent = 'β Copied! Opening ChatGPT...';setTimeout(() => {window.open('https://chat.openai.com/', '_blank');setTimeout(() => {this.textContent = 'π Copy & Open ChatGPT';}, 2000);}, 500);}).catch(err => {console.error('Modern copy failed:', err);promptArea.select();document.execCommand('copy');this.textContent = 'β Copied! Opening ChatGPT...';setTimeout(() => {window.open('https://chat.openai.com/', '_blank');setTimeout(() => {this.textContent = 'π Copy & Open ChatGPT';}, 2000);}, 500);});} else {this.textContent = 'β No prompt found. Generate one first.';setTimeout(() => {this.textContent = 'π Copy & Open ChatGPT';}, 2000);}} catch (err) {console.error('Copy error:', err);this.textContent = 'β Copy failed. Try again.';setTimeout(() => {this.textContent = 'π Copy & Open ChatGPT';}, 2000);}"style="padding: 10px 20px;background-color: #2C3E50;color: white;border: none;border-radius: 5px;font-weight: bold;cursor: pointer;transition: background-color 0.3s ease;"onmouseover="this.style.backgroundColor='#34495E'"onmouseout="this.style.backgroundColor='#2C3E50'">π Copy & Open ChatGPT</button></div>""")# JavaScript for model choice handlinggr.HTML("""<script>// Enable/disable send button based on selectiondocument.querySelector('input[name="model_choice"]').addEventListener('change', function(e) {const sendButton = document.querySelector('button:contains("Send to Model")');if (sendButton) {sendButton.disabled = (e.target.value === 'Clipboard only');}});</script>""")# Summary sectionwith gr.Column(scale=1):summary_output = gr.Textbox(label="π Summary",lines=15,max_lines=50,show_copy_button=True,elem_id="summary_output")# Summary actions rowwith gr.Row():copy_summary_btn = gr.Button("π Copy Summary", size="sm")download_summary = gr.File(label="π₯ Download Summary")# Status displayclipboard_status = gr.HTML(elem_id="clipboard_status")# Hidden components for file handlingdownload_files = gr.Files(label="π₯ Downloads", visible=False)54 unmodified linesdef handle_groq_model_change(model_name):"""Handle Groq model selection change"""return update_context_size("Groq API", model_name)# PDF Processing Handlersdef handle_pdf_process(pdf, fmt, ctx_size): # Remove md_eng parameter97 unmodified linesoutputs=[progress_status, generated_prompt, download_prompt])# copy_button.click(# fn=copy_to_clipboard,# inputs=[generated_prompt],# outputs=[clipboard_status]# )# copy_summary_btn.click(# fn=None,# inputs=[],# outputs=[],# _js=copy_summary_js# )# Snippet handlingsnippet_selector.change(handle_snippet_selection,1 unmodified lineoutputs=[progress_status, generated_prompt, download_snippet] # Connect download_snippet)# Model selectionmodel_choice.change(handle_model_selection,5 unmodified linescohere_options,glhf_options,context_size,send_to_model_btn,hf_model, # For updating model choiceshf_custom_model # Add this to update custom model visibility])
app.py+383-251