Update app.py
Browse files12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596012 unmodified lines737475767778798081828313 unmodified lines979899100101102103104105106107108109110111112113114115116117import gradio as grimport subprocess# Function to load a model using Hugging Face Spacesdef load_model_from_space(model_name):print(f"Attempting to load {model_name}...")try:demo = gr.load(name=model_name, src="spaces")print(f"Successfully loaded {model_name}")return demoexcept Exception as e:print(f"Error loading model {model_name}: {e}")return None# Load the modelsdeepseek_r1_distill = load_model_from_space("deepseek-ai/DeepSeek-R1-Distill-Qwen-32B")deepseek_r1 = load_model_from_space("deepseek-ai/DeepSeek-R1")deepseek_r1_zero = load_model_from_space("deepseek-ai/DeepSeek-R1-Zero")# --- Chatbot function ---def chatbot(input_text, history, model_choice, system_message, max_new_tokens, temperature, top_p):history = history or []print(f"Input: {input_text}, History: {history}, Model: {model_choice}")# Choose the model based on user selectionif model_choice == "DeepSeek-R1-Distill-Qwen-32B" and deepseek_r1_distill:model_demo = deepseek_r1_distillelif model_choice == "DeepSeek-R1" and deepseek_r1:model_demo = deepseek_r1elif model_choice == "DeepSeek-R1-Zero" and deepseek_r1_zero:model_demo = deepseek_r1_zeroelse:default_response = "Model not selected or could not be loaded."history.append((input_text, default_response))return history, history, "", model_choice, system_message, max_new_tokens, temperature, top_p# Call the model's 'predict' function.try:model_output = model_demo(input_text, history, max_new_tokens, temperature, top_p, system_message, fn_index=0)except Exception as e:print(f"An error occurred: {e}")model_output= "An error occurred please check the model and try again."history.append((input_text, model_output))return history, history, "", model_choice, system_message, max_new_tokens, temperature, top_p# Check if model_output is iterable and has expected number of elementsif not isinstance(model_output, (list, tuple)) or len(model_output) < 2:error_message = "Model output does not have the expected format."history.append((input_text, error_message))return history, history, "", model_choice, system_message, max_new_tokens, temperature, top_presponse = model_output[-1][1] if model_output[-1][1] else "Model did not return a response."history.append((input_text, response))return history, history, "", model_choice, system_message, max_new_tokens, temperature, top_p# --- Gradio Interface ---with gr.Blocks(theme=gr.themes.Soft()) as demo:gr.Markdown("""# DeepSeek Chatbot12 unmodified linessubmit_btn = gr.Button("Submit", variant="primary")clear_btn = gr.ClearButton([msg, chatbot_output])# Options moved below the chat interfacewith gr.Row():with gr.Accordion("Options", open=True):model_choice = gr.Radio(choices=["DeepSeek-R1-Distill-Qwen-32B", "DeepSeek-R1", "DeepSeek-R1-Zero"],label="Choose a Model",value="DeepSeek-R1")13 unmodified linesminimum=0.10, maximum=1.00, value=0.90, label="Top-p (nucleus sampling)")# Maintain chat historychat_history = gr.State([])# Event handlingsubmit_btn.click(chatbot,[msg, chat_history, model_choice, system_message, max_new_tokens, temperature, top_p],[chatbot_output, chat_history, msg, model_choice, system_message, max_new_tokens, temperature, top_p],)msg.submit(chatbot,[msg, chat_history, model_choice, system_message, max_new_tokens, temperature, top_p],[chatbot_output, chat_history, msg, model_choice, system_message, max_new_tokens, temperature, top_p],)# Launch the demoif __name__ == "__main__":demo.launch()1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515212 unmodified lines6566676869707172737413 unmodified lines888990919293949596979899100101102103104105106107108109110111import gradio as grimport spacesimport transformers_gradiofrom functools import lru_cache# Cache model loading to optimize performance@lru_cache(maxsize=3)def load_hf_model(model_name):return gr.load(name=f"deepseek-ai/{model_name}",src=transformers_gradio.registry,api_name="/chat")# Load all models at startupMODELS = {"DeepSeek-R1-Distill-Qwen-32B": load_hf_model("DeepSeek-R1-Distill-Qwen-32B"),"DeepSeek-R1": load_hf_model("DeepSeek-R1"),"DeepSeek-R1-Zero": load_hf_model("DeepSeek-R1-Zero")}# --- Chatbot function ---def chatbot(input_text, history, model_choice, system_message, max_new_tokens, temperature, top_p):history = history or []# Get the selected model componentmodel_component = MODELS[model_choice]# Create payload for the modelpayload = {"messages": [{"role": "user", "content": input_text}],"system": system_message,"max_tokens": max_new_tokens,"temperature": temperature,"top_p": top_p}# Run inference using the selected modeltry:response = model_component(payload)assistant_response = response[-1]["content"]except Exception as e:assistant_response = f"Error: {str(e)}"history.append((input_text, assistant_response))return history, history, ""# --- Gradio Interface ---with gr.Blocks(theme=gr.themes.Soft(), title="DeepSeek Chatbot") as demo:gr.Markdown("""# DeepSeek Chatbot12 unmodified linessubmit_btn = gr.Button("Submit", variant="primary")clear_btn = gr.ClearButton([msg, chatbot_output])with gr.Row():with gr.Accordion("Options", open=True):model_choice = gr.Radio(choices=list(MODELS.keys()),label="Choose a Model",value="DeepSeek-R1")13 unmodified linesminimum=0.10, maximum=1.00, value=0.90, label="Top-p (nucleus sampling)")chat_history = gr.State([])# Event handlingsubmit_btn.click(chatbot,[msg, chat_history, model_choice, system_message, max_new_tokens, temperature, top_p],[chatbot_output, chat_history, msg])msg.submit(chatbot,[msg, chat_history, model_choice, system_message, max_new_tokens, temperature, top_p],[chatbot_output, chat_history, msg])# Add GPU support for Hugging Face Spacesdemo.fn = spaces.GPU()(demo.fn)for fn in demo.fns.values():fn.api_name = Falseif __name__ == "__main__":demo.launch()
app.py+46-52