File size: 4,867 Bytes
599f736
 
 
 
 
ee0877c
599f736
ee0877c
 
 
 
 
 
 
 
599f736
 
 
 
 
ee0877c
 
599f736
ee0877c
 
599f736
ee0877c
 
 
 
 
599f736
 
 
 
 
 
ee0877c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
599f736
 
ee0877c
 
 
599f736
ee0877c
 
599f736
 
ee0877c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
599f736
ee0877c
 
599f736
ee0877c
 
 
599f736
 
 
 
 
 
 
ee0877c
 
599f736
 
 
 
 
 
 
 
 
 
ee0877c
 
 
 
 
 
 
 
 
 
 
 
 
 
599f736
ee0877c
599f736
ee0877c
 
599f736
ee0877c
 
 
 
 
599f736
 
 
ee0877c
599f736
 
 
ee0877c
599f736
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
import gradio as gr
from pathlib import Path
import asyncio
import google.generativeai as genai
import os
import logging
from dotenv import load_dotenv
from typing import Optional, Tuple

from flashcard import FlashcardSet
from chat_agent import (
    chat_agent,
    ChatDeps,
    ChatResponse
)

# Load environment variables
load_dotenv()
genai.configure(api_key=os.environ["GEMINI_API_KEY"])

async def process_message(message: dict, history: list, current_flashcards: Optional[FlashcardSet]) -> Tuple[str, list, Optional[FlashcardSet]]:
    """Process uploaded files and chat messages"""
    
    # Get any text provided with the upload as system prompt
    user_text = message.get("text", "").strip()
    
    # Create chat dependencies
    deps = ChatDeps(
        message=user_text,
        current_flashcards=current_flashcards
    )
    
    # Handle file uploads
    if message.get("files"):
        for file_path in message["files"]:
            if file_path.endswith('.pdf'):
                try:
                    with open(file_path, "rb") as pdf_file:
                        deps.pdf_data = pdf_file.read()
                        deps.system_prompt = user_text if user_text else None
                    
                    # Let chat agent handle the PDF upload
                    result = await chat_agent.run("Process this PDF upload", deps=deps)
                    
                    if result.data.should_generate_flashcards:
                        # Update current flashcards
                        current_flashcards = result.data.flashcards
                    
                    history.append([
                        f"Uploaded: {Path(file_path).name}" + 
                        (f"\nWith instructions: {user_text}" if user_text else ""),
                        result.data.response
                    ])
                    return "", history, current_flashcards
                except Exception as e:
                    error_msg = f"Error processing PDF: {str(e)}"
                    logging.error(error_msg)
                    history.append([f"Uploaded: {Path(file_path).name}", error_msg])
                    return "", history, current_flashcards
            else:
                history.append([f"Uploaded: {Path(file_path).name}", "Please upload a PDF file."])
                return "", history, current_flashcards
    
    # Handle text messages
    if user_text:
        try:
            result = await chat_agent.run(user_text, deps=deps)
            
            # Update flashcards if modified
            if result.data.should_modify_flashcards:
                current_flashcards = result.data.flashcards
            
            history.append([user_text, result.data.response])
            return "", history, current_flashcards
        except Exception as e:
            error_msg = f"Error processing request: {str(e)}"
            logging.error(error_msg)
            history.append([user_text, error_msg])
            return "", history, current_flashcards
    
    history.append(["", "Please upload a PDF file or send a message."])
    return "", history, current_flashcards

async def clear_chat():
    """Reset the conversation and clear current flashcards"""
    return None, None, None

# Create Gradio interface
with gr.Blocks(title="PDF Flashcard Generator") as demo:
    gr.Markdown("""
    # ๐Ÿ“š PDF Flashcard Generator
    Upload a PDF document and get AI-generated flashcards to help you study!
    
    You can provide custom instructions along with your PDF upload to guide the flashcard generation.
    
    Powered by Google's Gemini AI
    """)
    
    chatbot = gr.Chatbot(
        label="Flashcard Generation Chat",
        bubble_full_width=False,
        show_copy_button=True,
        height=600
    )
    
    # Session state for flashcards
    current_flashcards = gr.State(value=None)
    
    with gr.Row():
        chat_input = gr.MultimodalTextbox(
            label="Upload PDF or type a message",
            placeholder="Drop a PDF file here. You can also add instructions for how the flashcards should be generated...",
            file_types=[".pdf", "application/pdf", "pdf"],
            show_label=False,
            sources=["upload"],
            scale=20,
            min_width=100
        )
        clear_btn = gr.Button("๐Ÿ—‘๏ธ", variant="secondary", scale=1, min_width=50)

    chat_input.submit(
        fn=process_message,
        inputs=[chat_input, chatbot, current_flashcards],
        outputs=[chat_input, chatbot, current_flashcards]
    )
    
    clear_btn.click(
        fn=clear_chat,
        inputs=[],
        outputs=[chat_input, chatbot, current_flashcards]
    )

if __name__ == "__main__":
    logging.basicConfig(level=logging.INFO)
    demo.launch(
        share=False,
        server_name="0.0.0.0",
        server_port=7860
    )