import gradio as gr from end_to_end_class import EndToEndRAG rag_instance: EndToEndRAG | None = None def respond( message, history: list[dict[str, str]], system_message, max_tokens, temperature, top_p, image_url: str, 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 """ global rag_instance if rag_instance is None: try: token_value = hf_token.token if hf_token and hasattr(hf_token, "token") else None rag_instance = EndToEndRAG.default(hf_token=token_value) except Exception as e: yield f"Failed to initialize RAG pipeline: {e}" return # Configure generation params per request rag_instance.max_new_tokens = int(max_tokens) rag_instance.temperature = float(temperature) user_text = message if isinstance(message, str) else str(message) img_input = image_url if isinstance(image_url, str) and image_url.strip() else None # Build a Persian prompt aligned with the notebook style sys_prefix = system_message if isinstance(system_message, str) and system_message.strip() else "تو یک دستیار پاسخ‌گوی دقیق به زبان فارسی هستی." user_desc_parts = [] if user_text and user_text.strip(): user_desc_parts.append(f"پرسش متنی: {user_text.strip()}") if img_input: user_desc_parts.append(f"لینک تصویر: {img_input}") prompt = ( f"{sys_prefix} " "از زمینهٔ زیر برای پاسخ استفاده کن و اگر کافی نبود، صراحتاً اعلام کن. " "از حدس‌زدن بپرهیز و در صورت امکان به منبع اشاره کن.\n\n" f"جزئیات ورودی کاربر:\n- {' | '.join(user_desc_parts) if user_desc_parts else 'نامشخص'}\n\n" "پاسخ نهایی فارسی، موجز و مستدل:" ) try: answer = rag_instance.query(text=prompt, image_url=img_input) yield answer except Exception as e: yield f"Error while generating answer: {e}" """ 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="تو یک دستیار پاسخ‌گوی دقیق به زبان فارسی هستی.", label="System message"), gr.Slider(minimum=1, maximum=2048, value=256, step=1, label="Max new tokens"), gr.Slider(minimum=0.0, maximum=2.0, value=0.2, step=0.1, label="Temperature"), gr.Slider( minimum=0.1, maximum=1.0, value=0.95, step=0.05, label="Top-p (unused)", ), gr.Textbox(value="", label="Image URL (optional)"), ], ) with gr.Blocks() as demo: with gr.Sidebar(): gr.LoginButton() chatbot.render() if __name__ == "__main__": demo.launch()