Update app.py
Browse files12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364import gradio as grfrom huggingface_hub import InferenceClient"""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("HuggingFaceH4/zephyr-7b-beta")def respond(message,history: list[tuple[str, str]],system_message,max_tokens,temperature,top_p,):messages = [{"role": "system", "content": system_message}]for val in history:if val[0]:messages.append({"role": "user", "content": val[0]})if val[1]:messages.append({"role": "assistant", "content": val[1]})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,):token = message.choices[0].delta.contentresponse += tokenyield response"""For information on how to customize the ChatInterface, peruse the gradio docs: https://www.gradio.app/docs/chatinterface"""demo = gr.ChatInterface(respond,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)",),],)if __name__ == "__main__":demo.launch()1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586import gradio as grfrom fuzzywuzzy import processfrom transformers import pipeline# 1) Our 20 dental terms:dental_terms = {"cavity": "A cavity is a hole in a tooth caused by decay.","gingivitis": "Gingivitis is the inflammation of the gums, often caused by plaque buildup.","implant": "A dental implant is a surgical component that interfaces with the jawbone to support a dental prosthesis.","orthodontics": "Orthodontics is a branch of dentistry that corrects teeth and jaw alignment issues.","plaque": "Plaque is a sticky, colorless film of bacteria that forms on teeth.","enamel": "Enamel is the hard, outer surface layer of your teeth that protects against decay.","braces": "Braces are orthodontic devices used to straighten teeth and correct bite issues.","root canal": "A root canal is a treatment to repair and save a badly damaged or infected tooth.","crown": "A crown is a dental cap placed over a tooth to restore its shape, size, and strength.","veneers": "Veneers are thin shells placed over the front of teeth to improve appearance.","halitosis": "Halitosis is chronic bad breath caused by bacteria or other factors.","periodontitis": "Periodontitis is a serious gum infection that damages gums and can destroy the jawbone.","denture": "Dentures are removable appliances that replace missing teeth and surrounding tissues.","bridge": "A dental bridge is a fixed prosthetic device that replaces missing teeth.","tartar": "Tartar is hardened plaque that forms on teeth and can only be removed by a dentist.","x-ray": "A dental x-ray is an imaging technique used to view the inside of teeth and surrounding tissues.","flossing": "Flossing is the process of cleaning between your teeth with dental floss.","sealant": "A sealant is a protective coating applied to teeth to prevent decay.","bitewing": "A bitewing is a type of dental x-ray that shows the upper and lower back teeth.","occlusion": "Occlusion refers to the alignment and contact between teeth when the jaws close."}# 2) Set up a Transformer-based text generation pipeline# (You can choose any model on Hugging Face; "gpt2" is just an example.)generation_pipeline = pipeline("text-generation", model="gpt2")def chatbot_response(message, history):"""A hybrid response function:- Check if the user query matches a known dental term (direct or fuzzy).- If not matched, use a transformer model to generate an open-ended response."""print(f"User Input: {message}")print(f"Chat History: {history}")# Lowercase for simpler matchinginput_lower = message.lower()# 1) Check for exact matchif input_lower in dental_terms:response = dental_terms[input_lower]print(f"Exact Match Response: {response}")return response# 2) Fuzzy matching for approximate matchesclosest_match, score = process.extractOne(input_lower, dental_terms.keys())print(f"Closest Match: {closest_match}, Score: {score}")if score >= 80:# We suspect the user intended a known termreturn f"Did you mean '{closest_match}'? {dental_terms[closest_match]}"else:# 3) If no good match, let transformer-based AI handle it# We'll generate a short text response.generated = generation_pipeline(message,max_length=100, # adjust as needednum_return_sequences=1,do_sample=True,top_p=0.9,top_k=50)ai_response = generated[0]["generated_text"]# Optionally, you might want to trim the prompt out of the generated text,# but here we'll just return it as is.print(f"Transformer-based response: {ai_response}")return ai_response# 3) Gradio ChatInterface (or you can use gr.Interface)demo = gr.ChatInterface(fn=chatbot_response,title="Hybrid Dental Terminology Chatbot",description=("Enter a dental term to get its definition (20 known terms). ""If the term isn't recognized, a transformer-based model will respond."))if __name__ == "__main__":demo.launch()
app.py+72-50