File size: 10,821 Bytes
b34efa5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
"""
Gradio app for Norwegian RAG chatbot.
Provides a web interface for interacting with the chatbot.
"""

import os
import gradio as gr
import tempfile
from typing import List, Dict, Any, Tuple, Optional

from ..api.huggingface_api import HuggingFaceAPI
from ..document_processing.processor import DocumentProcessor
from ..rag.retriever import Retriever
from ..rag.generator import Generator

class ChatbotApp:
    """
    Gradio app for Norwegian RAG chatbot.
    """
    
    def __init__(
        self,
        api_client: Optional[HuggingFaceAPI] = None,
        document_processor: Optional[DocumentProcessor] = None,
        retriever: Optional[Retriever] = None,
        generator: Optional[Generator] = None,
        title: str = "Norwegian RAG Chatbot",
        description: str = "En chatbot basert på Retrieval-Augmented Generation (RAG) for norsk språk."
    ):
        """
        Initialize the chatbot app.
        
        Args:
            api_client: HuggingFaceAPI client
            document_processor: Document processor
            retriever: Retriever for finding relevant chunks
            generator: Generator for creating responses
            title: App title
            description: App description
        """
        # Initialize components
        self.api_client = api_client or HuggingFaceAPI()
        self.document_processor = document_processor or DocumentProcessor(api_client=self.api_client)
        self.retriever = retriever or Retriever(api_client=self.api_client)
        self.generator = generator or Generator(api_client=self.api_client)
        
        # App settings
        self.title = title
        self.description = description
        
        # Initialize Gradio app
        self.app = self._build_interface()
    
    def _build_interface(self) -> gr.Blocks:
        """
        Build the Gradio interface.
        
        Returns:
            Gradio Blocks interface
        """
        with gr.Blocks(title=self.title) as app:
            gr.Markdown(f"# {self.title}")
            gr.Markdown(self.description)
            
            with gr.Tabs():
                # Chat tab
                with gr.Tab("Chat"):
                    chatbot = gr.Chatbot(height=500)
                    
                    with gr.Row():
                        msg = gr.Textbox(
                            placeholder="Skriv din melding her...",
                            show_label=False,
                            scale=9
                        )
                        submit_btn = gr.Button("Send", scale=1)
                    
                    with gr.Accordion("Avanserte innstillinger", open=False):
                        temperature = gr.Slider(
                            minimum=0.1,
                            maximum=1.0,
                            value=0.7,
                            step=0.1,
                            label="Temperatur"
                        )
                    
                    clear_btn = gr.Button("Tøm chat")
                    
                    # Set up event handlers
                    submit_btn.click(
                        fn=self._respond,
                        inputs=[msg, chatbot, temperature],
                        outputs=[msg, chatbot]
                    )
                    
                    msg.submit(
                        fn=self._respond,
                        inputs=[msg, chatbot, temperature],
                        outputs=[msg, chatbot]
                    )
                    
                    clear_btn.click(
                        fn=lambda: None,
                        inputs=None,
                        outputs=chatbot,
                        queue=False
                    )
                
                # Document upload tab
                with gr.Tab("Last opp dokumenter"):
                    with gr.Row():
                        with gr.Column(scale=2):
                            file_output = gr.File(label="Opplastede dokumenter")
                            upload_button = gr.UploadButton(
                                "Klikk for å laste opp dokument",
                                file_types=["pdf", "txt", "html"],
                                file_count="multiple"
                            )
                        
                        with gr.Column(scale=3):
                            documents_list = gr.Dataframe(
                                headers=["Dokument ID", "Filnavn", "Dato", "Chunks"],
                                label="Dokumentliste",
                                interactive=False
                            )
                    
                    process_status = gr.Textbox(label="Status", interactive=False)
                    refresh_btn = gr.Button("Oppdater dokumentliste")
                    
                    # Set up event handlers
                    upload_button.upload(
                        fn=self._process_uploaded_files,
                        inputs=[upload_button],
                        outputs=[process_status, documents_list]
                    )
                    
                    refresh_btn.click(
                        fn=self._get_documents_list,
                        inputs=None,
                        outputs=[documents_list]
                    )
                
                # Embed tab
                with gr.Tab("Integrer"):
                    gr.Markdown("## Integrer chatboten på din nettside")
                    
                    with gr.Row():
                        with gr.Column():
                            gr.Markdown("### iFrame-kode")
                            iframe_code = gr.Code(
                                label="iFrame",
                                language="html",
                                value='<iframe src="https://huggingface.co/spaces/username/norwegian-rag-chatbot" width="100%" height="500px"></iframe>'
                            )
                        
                        with gr.Column():
                            gr.Markdown("### JavaScript Widget")
                            js_code = gr.Code(
                                label="JavaScript",
                                language="html",
                                value='<script src="https://huggingface.co/spaces/username/norwegian-rag-chatbot/widget.js"></script>'
                            )
                    
                    gr.Markdown("### Forhåndsvisning")
                    gr.Markdown("*Forhåndsvisning vil være tilgjengelig etter at chatboten er distribuert til Hugging Face Spaces.*")
            
            gr.Markdown("---")
            gr.Markdown("Bygget med [Hugging Face](https://huggingface.co/) og [Gradio](https://gradio.app/)")
        
        return app
    
    def _respond(
        self,
        message: str,
        chat_history: List[Tuple[str, str]],
        temperature: float
    ) -> Tuple[str, List[Tuple[str, str]]]:
        """
        Generate a response to the user message.
        
        Args:
            message: User message
            chat_history: Chat history
            temperature: Temperature for text generation
            
        Returns:
            Empty message and updated chat history
        """
        if not message:
            return "", chat_history
        
        # Add user message to chat history
        chat_history.append((message, None))
        
        try:
            # Retrieve relevant chunks
            retrieved_chunks = self.retriever.retrieve(message)
            
            # Generate response
            response = self.generator.generate(
                query=message,
                retrieved_chunks=retrieved_chunks,
                temperature=temperature
            )
            
            # Update chat history with response
            chat_history[-1] = (message, response)
        except Exception as e:
            # Handle errors
            error_message = f"Beklager, det oppstod en feil: {str(e)}"
            chat_history[-1] = (message, error_message)
        
        return "", chat_history
    
    def _process_uploaded_files(
        self,
        files: List[tempfile._TemporaryFileWrapper]
    ) -> Tuple[str, List[List[str]]]:
        """
        Process uploaded files.
        
        Args:
            files: List of uploaded files
            
        Returns:
            Status message and updated documents list
        """
        if not files:
            return "Ingen filer lastet opp.", self._get_documents_list()
        
        processed_files = []
        
        for file in files:
            try:
                # Process the document
                document_id = self.document_processor.process_document(file.name)
                processed_files.append(os.path.basename(file.name))
            except Exception as e:
                return f"Feil ved behandling av {os.path.basename(file.name)}: {str(e)}", self._get_documents_list()
        
        if len(processed_files) == 1:
            status = f"Fil behandlet: {processed_files[0]}"
        else:
            status = f"{len(processed_files)} filer behandlet: {', '.join(processed_files)}"
        
        return status, self._get_documents_list()
    
    def _get_documents_list(self) -> List[List[str]]:
        """
        Get list of processed documents.
        
        Returns:
            List of document information
        """
        documents = self.document_processor.get_all_documents()
        
        # Format for dataframe
        documents_list = []
        for doc_id, metadata in documents.items():
            filename = metadata.get("filename", "N/A")
            processed_date = metadata.get("processed_date", "N/A")
            chunk_count = metadata.get("chunk_count", 0)
            
            documents_list.append([doc_id, filename, processed_date, chunk_count])
        
        return documents_list
    
    def launch(self, **kwargs):
        """
        Launch the Gradio app.
        
        Args:
            **kwargs: Additional arguments for gr.launch()
        """
        self.app.launch(**kwargs)


def create_app():
    """
    Create and configure the chatbot app.
    
    Returns:
        Configured ChatbotApp instance
    """
    # Initialize API client
    api_client = HuggingFaceAPI()
    
    # Initialize components
    document_processor = DocumentProcessor(api_client=api_client)
    retriever = Retriever(api_client=api_client)
    generator = Generator(api_client=api_client)
    
    # Create app
    app = ChatbotApp(
        api_client=api_client,
        document_processor=document_processor,
        retriever=retriever,
        generator=generator
    )
    
    return app