Spaces:
Paused
Paused
Update app.py
Browse files78 unmodified lines7980818283848572 unmodified lines158159160161162163164165166167168169170171172173174373 unmodified lines54854955054355155255355456 unmodified lines611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647156 unmodified lines8048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129137 unmodified lines921922923783784785786924925926163 unmodified lines10901091109295695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710931094109510961097109810991100102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046110111021103110411051106110711081109111011111112104810491050105110521053105410551056105710581059106010611062106310641065106610671068106911131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183107111841185107310741075107610771078107910801081108211861187118811891190119111921084119311941086108710881089119511961197119811991200120112021203120412051091120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132954 unmodified lines1384138513861196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126913871388138997 unmodified lines148714881489149014911492149314941495149614971498149915001501150215031504150515061 unmodified line15081509151013801511151215135 unmodified lines151915201521139215221523152415251526152778 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 file return gr.HTML(html_template), "Text copied to clipboard. Use paste for processing.", download_file return 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 lines logging.error(f"Error in send_to_model_impl: {error_msg}") return f"Error: {error_msg}", None def send_to_qwq(prompt: str): """Send prompt to QwQ API.""" try: from gradio_client import Client client = Client("Qwen/QwQ-32B-preview") # Call the add_text endpoint result = client.predict( _input={"files":[], "text": prompt}, _chatbot=[], api_name="/add_text" ) # Call the agent_run endpoint response = 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 QwQ if model_name == "Qwen/QwQ-32B-preview": return send_to_qwq(prompt) def _send(): # Check token limits first is_within_limits, error_msg = check_token_limits(prompt, model_name)156 unmodified lines return 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_options gr.update(visible=False), # groq_options gr.update(visible=True), # openai_options gr.update(visible=False), # cohere_options gr.update(visible=False), # glhf_options gr.update(value=ctx_size), # context_size gr.update(interactive=True), # send_model_btn gr.Dropdown(choices=model_choices, value=first_model), # openai_model gr.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_options gr.update(visible=False), # groq_options gr.update(visible=False), # openai_options gr.update(visible=False), # cohere_options gr.update(visible=False), # glhf_options gr.update(value=ctx_size), # context_size gr.update(interactive=True), # send_model_btn gr.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_options gr.update(visible=True), # groq_options gr.update(visible=False), # openai_options gr.update(visible=False), # cohere_options gr.update(visible=False), # glhf_options gr.update(value=ctx_size), # context_size gr.update(interactive=True), # send_model_btn gr.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_options gr.update(visible=False), # groq_options gr.update(visible=False), # openai_options gr.update(visible=True), # cohere_options gr.update(visible=False), # glhf_options gr.update(value=ctx_size), # context_size gr.update(interactive=True), # send_model_btn gr.Dropdown(choices=[]), # not used gr.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_options gr.update(visible=False), # groq_options gr.update(visible=False), # openai_options gr.update(visible=False), # cohere_options gr.update(visible=True), # glhf_options gr.update(value=ctx_size), # context_size gr.update(interactive=True), # send_model_btn gr.Dropdown(choices=[]), # not used gr.update(visible=False) # hf_custom_model visibility ] # Default return for "Clipboard only" or other options return [ gr.update(visible=False), # hf_options gr.update(visible=False), # groq_options gr.update(visible=False), # openai_options gr.update(visible=False), # cohere_options gr.update(visible=False), # glhf_options gr.update(value=4096), # context_size gr.update(interactive=False), # send_model_btn gr.Dropdown(choices=[]), # not used gr.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 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 Processing with 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 used 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()), # Use model_registry.groq_models value=list(model_registry.groq_models.keys())[0] if model_registry.groq_models else None, # Set a default value if available label="Groq Model" ) groq_api_key = gr.Textbox( label="π Groq API Key", type="password" ) groq_refresh_btn = gr.Button("π Refresh Groq Models") # Add refresh button 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()) + ["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 with gr.Row(): with gr.Column(scale=1): model_choice = gr.Radio( choices=list(MODEL_CONTEXT_SIZES.keys()), value="Clipboard only", label="π€ Provider Selection" )
# Add visibility toggle def 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 container with 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" ) # Model-specific option containers 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" ) 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;"> <button onclick=" try { // Try all possible selectors for the prompt textarea 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'); 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 Row with gr.Row(): # Copy to Clipboard button with robust fallbacks copy_button = gr.HTML(""" <div style="text-align: center; margin: 10px;"> <button onclick=" 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 Prompt & Open ChatGPT'; this.textContent = 'π Copy to Clipboard'; }, 2000); }, 500); }) .catch(err => { console.error('Modern copy failed:', err); // Fallback method promptArea.select(); document.execCommand('copy'); this.textContent = 'β
Copied! Opening ChatGPT...'; setTimeout(() => { window.open('https://chat.openai.com/', '_blank'); }) .catch(err => { console.error('Modern copy failed:', err); promptArea.select(); document.execCommand('copy'); this.textContent = 'β
Copied using fallback!'; setTimeout(() => { this.textContent = 'π Copy Prompt & Open ChatGPT'; this.textContent = 'π Copy to Clipboard'; }, 2000); }, 500); }); } else { this.textContent = 'β No prompt found. Generate one first.'; }); } 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 Prompt & Open ChatGPT'; 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 implementation chatgpt_button = gr.HTML(""" <div style="text-align: center; margin: 10px;"> <button onclick=" 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 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") } 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 handling gr.HTML(""" <script> // Enable/disable send button based on selection document.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 section with 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 row with gr.Row(): copy_summary_btn = gr.Button("π Copy Summary", size="sm") download_summary = gr.File(label="π₯ Download Summary")
# Status display clipboard_status = gr.HTML(elem_id="clipboard_status") # Hidden components for file handling download_files = gr.Files(label="π₯ Downloads", visible=False)54 unmodified lines 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 = 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_options gr.update(visible=False), # groq_options gr.update(visible=True), # openai_options gr.update(visible=False), # cohere_options gr.update(visible=False), # glhf_options gr.update(value=ctx_size), # context_size gr.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_options gr.update(visible=False), # groq_options gr.update(visible=False), # openai_options gr.update(visible=False), # cohere_options gr.update(visible=False), # glhf_options gr.update(value=ctx_size), # context_size gr.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_options gr.update(visible=True), # groq_options gr.update(visible=False), # openai_options gr.update(visible=False), # cohere_options gr.update(visible=False), # glhf_options gr.update(value=ctx_size), # context_size gr.Dropdown(choices=model_choices, value=model_choices[0] if model_choices else None) ] elif choice == "Cohere API": return [ gr.update(visible=False), # hf_options gr.update(visible=False), # groq_options gr.update(visible=False), # openai_options gr.update(visible=True), # cohere_options gr.update(visible=False), # glhf_options gr.update(value=ctx_size), # context_size gr.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 completely gr.update(visible=False), # groq_options gr.update(visible=False), # openai_options gr.update(visible=False), # cohere_options gr.update(visible=True), # glhf_options gr.update(value=ctx_size), # context_size gr.Dropdown(choices=[]) # not used ]
# Default return for "Clipboard only" or other options return [ gr.update(visible=False), # hf_options gr.update(visible=False), # groq_options gr.update(visible=False), # openai_options gr.update(visible=False), # cohere_options gr.update(visible=False), # glhf_options gr.update(value=4096), # context_size gr.Dropdown(choices=[]) # not used ] # PDF Processing Handlers def handle_pdf_process(pdf, fmt, ctx_size): # Remove md_eng parameter97 unmodified lines outputs=[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 handling snippet_selector.change( handle_snippet_selection,1 unmodified line outputs=[progress_status, generated_prompt, download_snippet] # Connect download_snippet )
# Model selection # Model selection model_choice.change( handle_model_selection,5 unmodified lines cohere_options, glhf_options, context_size, openai_model send_to_model_btn, hf_model, # For updating model choices hf_custom_model # Add this to update custom model visibility ] )
app.py+383-251