Spaces:
Paused
Paused
Update app.py
Browse files202 unmodified lines203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326528 unmodified lines855856857858859860861862863864202 unmodified linesreturn "\n\n".join(prompts)def send_to_model(*args, **kwargs): # Correct the outputs heretry:with gr.Progress() as progress:progress(0, "Preparing to send to model...")summary, download_file = send_to_model_impl(*args, **kwargs) # Get both outputsprogress(1, "Complete!")return summary, download_file # Return both outputsexcept Exception as e:return f"Error: {str(e)}", None # Return error message and None for the filedef 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, openai_model_choice):try:if model_selection == "Clipboard only":return "Use copy/paste for processing", Noneelif model_selection == "HuggingFace Inference":if not hf_api_key:return "Error: HuggingFace API key required", Noneif not hf_model_choice:return "Error: Select a HuggingFace model", Nonemodel_id = hf_custom_model if hf_model_choice == "Custom Model" else model_registry.hf_models[hf_model_choice]try:summary = send_to_hf_inference(prompt, model_id, hf_api_key)except Exception as e:return f"Error with HuggingFace Inference: {e}", Noneelif model_selection == "Groq API":if not groq_api_key:return "Error: Groq API key required", Noneif not groq_model_choice:return "Error: Select a Groq model", Nonetry:summary = send_to_groq(prompt, groq_model_choice, groq_api_key)except Exception as e:return f"Error with Groq API: {e}", Noneelif model_selection == "OpenAI ChatGPT":if not openai_api_key:return "Error: OpenAI API key required", Nonetry:summary = send_to_openai(prompt, openai_api_key, model=openai_model_choice)except Exception as e:return f"Error with OpenAI API: {e}", Noneelse:return "Error: Invalid model selection", Nonetry: # for file operationswith tempfile.NamedTemporaryFile(mode='w+', suffix='.txt', delete=False) as f: # w+ for write and readf.write(summary)f.flush() # Ensure data is written to diskf.seek(0) # Rewind to the beginning of the filedownload_file = f.nameexcept Exception as file_error:return f"Error creating summary file: {file_error}", Nonereturn summary, download_fileexcept Exception as e: # Outer exception handlererror_msg = f"An unexpected error occurred: {str(e)}"logging.error(error_msg)return error_msg, Nonedef send_to_hf_inference(prompt: str, model_name: str, api_key: str) -> str:try:client = InferenceClient(token=api_key)response = client.text_generation(prompt,model=model_name,max_new_tokens=500,temperature=0.7,top_p=0.95,repetition_penalty=1.1)return str(response)except Exception as e:logging.error(f"Error with HF inference: {e}")return f"Error with HF inference: {e}"def send_to_groq(prompt: str, model_name: str, api_key: str) -> str:try:client = Groq(api_key=api_key)response = client.chat.completions.create(model=model_name,messages=[{"role": "user","content": prompt}],temperature=0.7,max_tokens=500,top_p=0.95)return response.choices[0].message.contentexcept 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, model: str = "gpt-3.5-turbo") -> str:try:import openaiopenai.api_key = api_keyresponse = openai.ChatCompletion.create(model=model,messages=[{"role": "system", "content": "You are a helpful assistant that provides detailed responses with examples and references where appropriate."},{"role": "user", "content": prompt}],temperature=0.7,max_tokens=500,top_p=0.95)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_text_js(element_id: str) -> str:return f"""function() {{528 unmodified linessend_to_model_btn.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, openai_model # Add openai_model as input],outputs=[summary_output, download_summary] # Correct outputs)groq_refresh_btn.click(202 unmodified lines203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349528 unmodified lines878879880881882883884885886887888889890891892893894202 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, openai_model_choice):"""Wrapper function for send_to_model_impl with proper error handling."""if not prompt:return "Error: No prompt provided", Nonetry:with gr.Progress() as progress:progress(0, "Preparing to send to model...")# Call implementation with proper error handlingsummary, download_file = send_to_model_impl(prompt=prompt,model_selection=model_selection,hf_model_choice=hf_model_choice,hf_custom_model=hf_custom_model,hf_api_key=hf_api_key,groq_model_choice=groq_model_choice,groq_api_key=groq_api_key,openai_api_key=openai_api_key,openai_model_choice=openai_model_choice)progress(1, "Complete!")return summary, download_fileexcept Exception as e:error_msg = f"Error processing request: {str(e)}"logging.error(error_msg)return error_msg, 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, openai_model_choice):"""Implementation of model sending with improved error handling."""try:if model_selection == "Clipboard only":return "Text copied to clipboard. Use paste for processing.", Noneelif model_selection == "HuggingFace Inference":if not hf_api_key:return "Error: HuggingFace API key required", Noneif not hf_model_choice:return "Error: Please select a HuggingFace model", Nonemodel_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)if summary.startswith("Error"):return summary, Noneelif model_selection == "Groq API":if not groq_api_key:return "Error: Groq API key required", Noneif not groq_model_choice:return "Error: Please select a Groq model", Nonesummary = send_to_groq(prompt, groq_model_choice, groq_api_key)if summary.startswith("Error"):return summary, Noneelif model_selection == "OpenAI ChatGPT":if not openai_api_key:return "Error: OpenAI API key required", Noneif not openai_model_choice:return "Error: Please select an OpenAI model", Nonesummary = send_to_openai(prompt, openai_api_key, model=openai_model_choice)if summary.startswith("Error"):return summary, Noneelse:return "Error: Invalid model selection", None# If we get here, we have a valid summary. Create download file.if summary and not summary.startswith("Error"):with tempfile.NamedTemporaryFile(delete=False, mode='w', suffix='.txt') as f:f.write(summary)return summary, f.namereturn summary, Noneexcept Exception as e:error_msg = f"Error in model processing: {str(e)}"logging.error(error_msg)return error_msg, Nonedef send_to_hf_inference(prompt: str, model_name: str, api_key: str) -> str:"""Send prompt to HuggingFace Inference API with better error handling."""try:client = InferenceClient(token=api_key)response = client.text_generation(prompt,model=model_name,max_new_tokens=500,temperature=0.7,top_p=0.95,repetition_penalty=1.1)return str(response)except Exception as e:logging.error(f"HuggingFace inference error: {e}")return f"Error with HuggingFace inference: {str(e)}"def send_to_groq(prompt: str, model_name: str, api_key: str) -> str:"""Send prompt to Groq API with better error handling."""try:client = Groq(api_key=api_key)response = client.chat.completions.create(model=model_name,messages=[{"role": "user","content": prompt}],temperature=0.7,max_tokens=500,top_p=0.95)return response.choices[0].message.contentexcept Exception as e:logging.error(f"Groq API error: {e}")return f"Error with Groq API: {str(e)}"def send_to_openai(prompt: str, api_key: str, model: str = "gpt-3.5-turbo") -> str:"""Send prompt to OpenAI API with better error handling."""try:import openaiopenai.api_key = api_keyresponse = openai.ChatCompletion.create(model=model,messages=[{"role": "system", "content": "You are a helpful assistant that provides detailed responses."},{"role": "user", "content": prompt}],temperature=0.7,max_tokens=500,top_p=0.95)return response.choices[0].message.contentexcept Exception as e:logging.error(f"OpenAI API error: {e}")return f"Error with OpenAI API: {str(e)}"def copy_text_js(element_id: str) -> str:return f"""function() {{528 unmodified linessend_to_model_btn.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,openai_model],outputs=[summary_output, download_summary])groq_refresh_btn.click(
app.py+119-89