Spaces:
Sleeping
Sleeping
Update app.py
Browse files2 unmodified lines3456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555 unmodified lines61626364656667686970717273747576777879804 unmodified lines858687888990913 unmodified lines95969798991001011026 unmodified lines1091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861872 unmodified lines1901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392 unmodified lines2422432442452462472482492502512522532541 unmodified line2562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942 unmodified linesimport gradio as grfrom transformers import AutoTokenizer, AutoModelForCausalLMMODEL_NAME = "Qwen/Qwen2.5-1.5B-Instruct"# -----------------------------# MODEL# -----------------------------tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME)model = AutoModelForCausalLM.from_pretrained(MODEL_NAME,torch_dtype="auto",device_map="auto",)SYSTEM_PROMPT = """You are FVB AI, the official AI assistant of FutureVidyabox.Your role:- Help FutureVidyabox students, staff, and customers.- Explain educational topics clearly.- Help with mathematics, science, computers, programming, and general education.- Generate and explain programming code.- Help debug programming problems.- Help with FutureVidyabox customer-support questions when the required information is available.Personality:- Friendly- Helpful- Clear- Patient- Professional- Concise when appropriate- Give step-by-step explanations when usefulImportant:- Do not invent FutureVidyabox information.- Do not invent prices, policies, services, contact information, or company facts.- If you do not know something, say that you do not have enough information.- For programming questions, provide useful and properly formatted code.- For educational questions, explain concepts clearly.You are FVB AI, not ChatGPT."""# -----------------------------# AI FUNCTION# -----------------------------@spaces.GPU(duration=45)def fvb_ai(message, history):5 unmodified lines}]# Add previous conversationfor item in history:if isinstance(item, dict):role = item.get("role")content = item.get("content")if role in ["user", "assistant"] and isinstance(content, str):messages.append({"role": role,"content": content})# Add current messagemessages.append({"role": "user","content": message4 unmodified linesadd_generation_prompt=True,tokenize=True,return_dict=True,return_tensors="pt",).to(model.device)with torch.inference_mode():3 unmodified linesmax_new_tokens=512,do_sample=True,temperature=0.7,top_p=0.8,repetition_penalty=1.1,)new_tokens = outputs[0][inputs["input_ids"].shape[-1]:]6 unmodified linesreturn response.strip()# -----------------------------# CUSTOM CSS# -----------------------------css = """/* Main page */body {background: #f7f9fc;}.gradio-container {max-width: 1200px !important;margin: auto !important;}/* Header */.fvb-header {text-align: center;padding: 25px 10px 10px 10px;}.fvb-logo {font-size: 34px;font-weight: 800;letter-spacing: -1px;}.fvb-subtitle {color: #6b7280;font-size: 15px;margin-top: 5px;}/* Chat */.chatbox {border-radius: 18px !important;border: 1px solid #e5e7eb !important;}/* Input */textarea {border-radius: 14px !important;}/* Buttons */button {border-radius: 12px !important;}/* Footer */.fvb-footer {text-align: center;color: #8a8f98;font-size: 12px;padding: 15px;}"""# -----------------------------# UI# -----------------------------with gr.Blocks(title="FVB AI",css=css,theme=gr.themes.Soft(primary_hue="blue",2 unmodified lines)) as demo:gr.HTML("""<div class="fvb-header"><div class="fvb-logo">FutureVidyabox AI</div><div class="fvb-subtitle">Your educational and customer-support AI assistant</div></div>""")chatbot = gr.Chatbot(label="FVB AI",height=520,show_label=True,elem_classes="chatbox")with gr.Row():message = gr.Textbox(placeholder="Ask FVB AI anything...",label="",scale=8,lines=2)send = gr.Button("Send",variant="primary",scale=1)with gr.Row():clear = gr.Button("Clear Chat")gr.HTML("""<div class="fvb-footer">2 unmodified lines""")# -------------------------# SEND# -------------------------def respond(message_text, chat_history):if not message_text.strip():return "", chat_historyanswer = fvb_ai(1 unmodified linechat_history)chat_history = chat_history + [{"role": "user","content": message_text},{"role": "assistant","content": answer}]return "", chat_historysend.click(respond,inputs=[message, chatbot],outputs=[message, chatbot])message.submit(respond,inputs=[message, chatbot],outputs=[message, chatbot])clear.click(lambda: [],outputs=[chatbot])# -----------------------------# START# -----------------------------demo.launch()2 unmodified lines3456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960615 unmodified lines676869707172737475767778798081828384858687884 unmodified lines939495969798993 unmodified lines1031041051061071081091106 unmodified lines1171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172 unmodified lines2202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003012 unmodified lines3043053063073083093103113123133143153161 unmodified line3183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833842 unmodified linesimport gradio as grfrom transformers import AutoTokenizer, AutoModelForCausalLM# =========================================================# MODEL# =========================================================MODEL_NAME = "Qwen/Qwen2.5-1.5B-Instruct"tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME)model = AutoModelForCausalLM.from_pretrained(MODEL_NAME,torch_dtype="auto",device_map="auto")# =========================================================# FVB AI PERSONALITY# =========================================================SYSTEM_PROMPT = """You are FVB AI, the AI assistant created for FutureVidyabox.You help students, staff and customers with:- Education- Science- Mathematics- Computer science- Programming- Coding- General questions- FutureVidyabox customer supportYou are friendly, helpful, clear and patient.For students:- Explain difficult topics simply.- Give step-by-step explanations when useful.- Adapt explanations to the student's level.For programming:- Provide working example code.- Explain the code.- Help find and fix errors.IMPORTANT:Never invent FutureVidyabox company information.If you don't know a FutureVidyabox-specific fact, say that you don't have enough information.You are FVB AI."""# =========================================================# AI FUNCTION# =========================================================@spaces.GPU(duration=45)def fvb_ai(message, history):5 unmodified lines}]# Add conversation historyif history:for item in history:if isinstance(item, dict):role = item.get("role")content = item.get("content")if role in ["user", "assistant"] and isinstance(content, str):messages.append({"role": role,"content": content})# Current questionmessages.append({"role": "user","content": message4 unmodified linesadd_generation_prompt=True,tokenize=True,return_dict=True,return_tensors="pt").to(model.device)with torch.inference_mode():3 unmodified linesmax_new_tokens=512,do_sample=True,temperature=0.7,top_p=0.9,repetition_penalty=1.1)new_tokens = outputs[0][inputs["input_ids"].shape[-1]:]6 unmodified linesreturn response.strip()# =========================================================# CUSTOM DESIGN# =========================================================css = """body {background: #f7f9fc;}.gradio-container {max-width: 1150px !important;margin: auto !important;}/* HEADER */.fvb-header {text-align: center;padding-top: 25px;padding-bottom: 15px;}.fvb-title {font-size: 38px;font-weight: 800;letter-spacing: -1px;}.fvb-subtitle {font-size: 15px;color: #6b7280;margin-top: 5px;}/* CHAT */.fvb-chat {border-radius: 18px !important;border: 1px solid #e5e7eb !important;}/* MESSAGE BOX */#message-box textarea {border-radius: 15px !important;font-size: 16px !important;}/* SEND BUTTON */#send-button {border-radius: 14px !important;min-height: 55px !important;font-weight: 600 !important;}/* SUGGESTIONS */.suggestion-btn {border-radius: 22px !important;background: white !important;border: 1px solid #dfe3e8 !important;font-size: 14px !important;white-space: nowrap !important;}.suggestion-btn:hover {background: #f3f6fa !important;}/* CLEAR */#clear-button {border-radius: 12px !important;}/* FOOTER */.fvb-footer {text-align: center;color: #8a8f98;font-size: 12px;padding: 20px;}"""# =========================================================# USER INTERFACE# =========================================================with gr.Blocks(title="FUTUREVIDYABOX.AI",css=css,theme=gr.themes.Soft(primary_hue="blue",2 unmodified lines)) as demo:# HEADERgr.HTML("""<div class="fvb-header"><div class="fvb-title">FUTUREVIDYABOX.AI</div><div class="fvb-subtitle">Your educational and AI assistant</div></div>""")# CHATchatbot = gr.Chatbot(label="FVB AI",type="messages",height=500,elem_classes="fvb-chat")# INPUT + SENDwith gr.Row():message = gr.Textbox(placeholder="Ask FVB AI anything...",show_label=False,lines=2,scale=8,elem_id="message-box")send = gr.Button("↑",variant="primary",scale=1,elem_id="send-button")# =====================================================# SUGGESTION BUTTONS# =====================================================gr.Markdown("### Try asking")with gr.Row():suggestion1 = gr.Button("SOME SOURCES OF INDIAN HISTORY",elem_classes="suggestion-btn")suggestion2 = gr.Button("TEACH ME ABOUT COMPUTER AI",elem_classes="suggestion-btn")suggestion3 = gr.Button("EXPLAIN PYTHON PROGRAMMING",elem_classes="suggestion-btn")suggestion4 = gr.Button("HELP ME WITH MY HOMEWORK",elem_classes="suggestion-btn")# CLEARclear = gr.Button("Clear chat",elem_id="clear-button")# FOOTERgr.HTML("""<div class="fvb-footer">2 unmodified lines""")# =====================================================# CHAT FUNCTION# =====================================================def respond(message_text, chat_history):if not message_text or not message_text.strip():return "", chat_historyanswer = fvb_ai(1 unmodified linechat_history)new_history = list(chat_history)new_history.append({"role": "user","content": message_text})new_history.append({"role": "assistant","content": answer})return "", new_history# NORMAL SENDsend.click(respond,inputs=[message, chatbot],outputs=[message, chatbot])# ENTER TO SENDmessage.submit(respond,inputs=[message, chatbot],outputs=[message, chatbot])# =====================================================# SUGGESTION BUTTONS# =====================================================suggestion1.click(lambda: "Some sources of Indian history",outputs=message)suggestion2.click(lambda: "Teach me about computer AI",outputs=message)suggestion3.click(lambda: "Explain Python programming",outputs=message)suggestion4.click(lambda: "Help me with my homework",outputs=message)# CLEAR CHATclear.click(lambda: [],outputs=chatbot)# =========================================================# START# =========================================================demo.launch()
app.py+193-103