Spaces:
Sleeping
Sleeping
Update app.py
Browse files12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970import gradio as grfrom huggingface_hub import InferenceClientdef respond(message,history: list[dict[str, str]],system_message,max_tokens,temperature,top_p,hf_token: gr.OAuthToken,):"""For more information on `huggingface_hub` Inference API support, please check the docs: https://huggingface.co/docs/huggingface_hub/v0.22.2/en/guides/inference"""client = InferenceClient(token=hf_token.token, model="openai/gpt-oss-20b")messages = [{"role": "system", "content": system_message}]messages.extend(history)messages.append({"role": "user", "content": message})response = ""for message in client.chat_completion(messages,max_tokens=max_tokens,stream=True,temperature=temperature,top_p=top_p,):choices = message.choicestoken = ""if len(choices) and choices[0].delta.content:token = choices[0].delta.contentresponse += tokenyield response"""For information on how to customize the ChatInterface, peruse the gradio docs: https://www.gradio.app/docs/chatinterface"""chatbot = gr.ChatInterface(respond,type="messages",additional_inputs=[gr.Textbox(value="You are a friendly Chatbot.", label="System message"),gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"),gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),gr.Slider(minimum=0.1,maximum=1.0,value=0.95,step=0.05,label="Top-p (nucleus sampling)",),],)with gr.Blocks() as demo:with gr.Sidebar():gr.LoginButton()chatbot.render()if __name__ == "__main__":demo.launch()1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586# app.pyimport gradio as grimport torchfrom transformers import pipeline, AutoProcessor, AutoModelForVision2Seq# -------------------# Load Whisper (STT) from Hugging Face# -------------------stt_pipe = pipeline("automatic-speech-recognition",model="openai/whisper-small", # Replace with your uploaded Whisper model repodevice=0 if torch.cuda.is_available() else -1)# -------------------# Load ChatDOC model# -------------------chatdoc_model_id = "username/CHATDOCMODEL" # replace with your uploaded repodevice = "cuda" if torch.cuda.is_available() else "cpu"dtype = torch.float16 if device == "cuda" else torch.float32processor = AutoProcessor.from_pretrained(chatdoc_model_id, trust_remote_code=True)chatdoc_model = AutoModelForVision2Seq.from_pretrained(chatdoc_model_id,torch_dtype=dtype).to(device)# -------------------# Chat function# -------------------def chat_with_doc(audio, message, history=[]):transcript = ""if audio is not None:result = stt_pipe(audio)transcript = result["text"]user_msg = message or transcriptif not user_msg.strip():return history, "No input detected."history.append([user_msg, None])# System prompt (simplified for demo)system_prompt = "You are a medical doctor interviewing a patient. Respond helpfully."dialogue = "\n".join([f"Patient: {u}\nDoctor: {b}" for u, b in history if u and b])prompt = f"{system_prompt}\n\nConversation:\n{dialogue}\nPatient: {user_msg}\nDoctor:"inputs = processor(text=prompt, images=None, return_tensors="pt").to(device)with torch.inference_mode():outputs = chatdoc_model.generate(**inputs,max_new_tokens=200,do_sample=True,temperature=0.7)input_len = inputs["input_ids"].shape[1]gen_tokens = outputs[:, input_len:]response = processor.batch_decode(gen_tokens, skip_special_tokens=True)[0].strip()history[-1][1] = responsereturn history, response# -------------------# Gradio UI# -------------------with gr.Blocks(title="ChatDOC") as demo:gr.Markdown("# 🩺 ChatDOC + Whisper\nTalk or type your symptoms.")chatbot = gr.Chatbot(height=400)msg = gr.Textbox(placeholder="Type your symptoms...")mic = gr.Audio(sources=["microphone"], type="filepath", label="🎤 Speak your symptoms")clear_btn = gr.Button("Clear Chat")state = gr.State([])def respond(audio, text, history):return chat_with_doc(audio, text, history)msg.submit(respond, [mic, msg, state], [chatbot, msg, state])mic.change(respond, [mic, msg, state], [chatbot, msg, state])clear_btn.click(lambda: ([], "", []), None, [chatbot, msg, state])if __name__ == "__main__":demo.launch()
app.py+79-63