import gradio as gr from rag import RAG # Assuming your rag.py is in the same directory import os import time # --- Configuration --- GOOGLE_API_KEY = os.getenv("GOOGLE_API_KEY") if not GOOGLE_API_KEY: raise ValueError("GOOGLE_API_KEY environment variable not set. Please set it before running the app.") COLLECTION_NAME = os.getenv("COLLECTION_NAME", "ca_documents") # --- Initialize RAG System --- try: rag = RAG(GOOGLE_API_KEY, COLLECTION_NAME) except Exception as e: print(f"Fatal Error initializing RAG system: {e}") raise # --- Initial Chat State --- welcome_message = { "role": "assistant", "content": """ 👋 **Welcome to your CA Study Assistant!** """ } initial_chat_history = [welcome_message] # --- Core Functions --- def upload_file(file): if file is None: return """

⚠️ Please select a file.

Supported formats: PDF, DOCX, TXT.

""" try: start_time = time.time() file_path = file.name success = rag.upload_document(file_path) duration = time.time() - start_time if success: return f"""

✅ Success!

{os.path.basename(file_path)} uploaded.

Processed in {duration:.2f}s

""" else: return f"""

❌ Upload Failed.

Please ensure {os.path.basename(file_path)} is a valid file.

""" except Exception as e: return f"""

❌ An Error Occurred

{str(e)}

""" def chat_with_docs(message: str, history: list): if not message or not message.strip(): return "", history history.append({"role": "user", "content": message}) answer = rag.ask_question(message) history.append({"role": "assistant", "content": answer}) return "", history def clear_chat(): return initial_chat_history, "" # --- Load Custom CSS --- with open("style.css") as f: css = f.read() # --- Gradio App Layout --- with gr.Blocks(css=css, title="CA Study Assistant", theme=gr.themes.Base(), mode="auto") as app: with gr.Column(elem_id="app-container"): gr.HTML(""" """) with gr.Tabs(elem_classes="tab-nav"): with gr.TabItem("💬 Ask Questions", id="chat_tab"): chatbot = gr.Chatbot( value=initial_chat_history, elem_id="chat-history", show_label=False, type="messages", bubble_full_width=False, ) with gr.Row(elem_id="chat-input-container"): with gr.Column(scale=10): chat_input = gr.Textbox( placeholder="Ask anything about your documents...", show_label=False, elem_id="chat-input", lines=1, max_lines=5, ) with gr.Column(scale=1, min_width=60): send_btn = gr.Button('➤', elem_id="send-btn") clear_btn = gr.Button("🗑️ Clear", elem_id="clear-btn") clear_btn.click(fn=clear_chat, outputs=[chatbot, chat_input]) with gr.TabItem("📚 Upload Documents", id="upload_tab"): with gr.Column(elem_id="upload-area"): gr.HTML("""

Upload Your Study Materials

Drag & drop or click below to select a file.

PDF DOCX TXT
""") upload_input = gr.File( label="", file_count="single", file_types=[".pdf", ".docx", ".txt"], type="filepath", ) upload_output = gr.HTML(elem_id="upload-output") upload_input.upload( fn=upload_file, inputs=[upload_input], outputs=[upload_output], api_name="upload_document" ) send_btn.click( fn=chat_with_docs, inputs=[chat_input, chatbot], outputs=[chat_input, chatbot], ) chat_input.submit( fn=chat_with_docs, inputs=[chat_input, chatbot], outputs=[chat_input, chatbot], ) if __name__ == "__main__": app.launch(share=True, debug=True)