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
 
 
e416d59
 
 
c32cdfb
 
 
e416d59
 
c32cdfb
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
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
"""
Gradio admin interface for content management
Allows uploading documents, scraping URLs, and managing content
"""

import gradio as gr
import os
import html as html_lib
from dotenv import load_dotenv
from qdrant_client import QdrantClient, models
from src.ingestion import ingest_document
from src.scraper import process_and_store_webpage
from src.config import load_settings, save_settings

load_dotenv()

# Initialize Qdrant client
client = QdrantClient(
    url=os.getenv("QDRANT_URL"),
    api_key=os.getenv("QDRANT_API_KEY")
)
collection_name = os.getenv("QDRANT_COLLECTION", "hr-intervals")

# Create index for metadata.source to enable filtering
try:
    client.create_payload_index(
        collection_name=collection_name,
        field_name="metadata.source",
        field_schema=models.PayloadSchemaType.KEYWORD
    )
    print("βœ… Payload index for metadata.source created successfully")
except Exception as e:
    # Index might already exist or collection not found
    print(f"ℹ️ Index status: {str(e)}")


# ==================== Functions ====================

def list_all_documents():
    """
    List all uploaded documents
    
    Returns:
        HTML table string with selectable content
    """
    try:
        # Paginate through ALL points (Qdrant has 5800+ points)
        all_points = []
        offset = None
        
        while True:
            result = client.scroll(
                collection_name=collection_name,
                limit=1000,
                offset=offset,
                with_payload=True
            )
            points, next_offset = result
            all_points.extend(points)
            
            if next_offset is None:
                break
            offset = next_offset
        
        # Group by source
        docs_dict = {}
        for point in all_points:
            payload = point.payload
            # Metadata is nested inside payload
            metadata = payload.get("metadata", {})
            source = metadata.get("source", "Unknown")
            
            if source not in docs_dict:
                docs_dict[source] = {
                    "name": source,
                    "type": metadata.get("type", "Unknown"),
                    "date": metadata.get("upload_date", "Unknown"),
                    "chunks": 0
                }
            docs_dict[source]["chunks"] += 1
        
        # Create HTML table with selectable text
        if not docs_dict or (len(docs_dict) == 1 and "Unknown" in docs_dict):
            return """
            <div style="padding: 20px; text-align: center; color: #666;">
                <p>πŸ“‚ No documents yet</p>
            </div>
            """
        
        html = """
        <style>
            .docs-table {
                width: 100%;
                border-collapse: collapse;
                font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Arial, sans-serif;
                user-select: text;
                -webkit-user-select: text;
                -moz-user-select: text;
                -ms-user-select: text;
            }
            .docs-table thead {
                background-color: #f8f9fa;
            }
            .docs-table th {
                padding: 12px;
                text-align: left;
                font-weight: 600;
                border-bottom: 2px solid #dee2e6;
                user-select: text;
            }
            .docs-table td {
                padding: 12px;
                border-bottom: 1px solid #dee2e6;
                user-select: text;
                cursor: text;
            }
            .docs-table tr:hover {
                background-color: #f8f9fa;
            }
            .doc-name {
                color: #0066cc;
                word-break: break-all;
            }
        </style>
        <table class="docs-table">
            <thead>
                <tr>
                    <th>Document Name</th>
                    <th>Type</th>
                    <th>Upload Date</th>
                    <th>Chunks</th>
                </tr>
            </thead>
            <tbody>
        """
        
        for doc in docs_dict.values():
            html += f"""
                <tr>
                    <td class="doc-name">{html_lib.escape(doc['name'])}</td>
                    <td>{html_lib.escape(doc['type'])}</td>
                    <td>{html_lib.escape(doc['date'])}</td>
                    <td>{doc['chunks']}</td>
                </tr>
            """
        
        html += """
            </tbody>
        </table>
        """
        
        return html
    
    except Exception as e:
        return f"""
        <div style="padding: 20px; color: #dc3545;">
            <p>❌ Error: {str(e)}</p>
        </div>
        """


def upload_document(file, doc_type="document"):
    """
    Upload PDF or DOCX file
    
    Args:
        file: Uploaded file object
        doc_type: Type of document
        
    Returns:
        Success message
    """
    if file is None:
        return "❌ Please select a file"
    
    try:
        file_path = file.name
        
        # Ingest document
        num_chunks = ingest_document(file_path, doc_type)
        
        return f"βœ… Success!\n\nFile: {os.path.basename(file_path)}\nChunks created: {num_chunks}\nType: {doc_type}"
    
    except Exception as e:
        return f"❌ Upload failed:\n{str(e)}"


def scrape_single_url(url):
    """
    Scrape single URL
    
    Args:
        url: URL to scrape
        
    Returns:
        Success message
    """
    if not url:
        return "❌ Please enter a URL"
    
    try:
        num_chunks = process_and_store_webpage(url)
        return f"βœ… Success!\n\nURL: {url}\nChunks created: {num_chunks}"
    
    except Exception as e:
        return f"❌ Scraping failed:\n{str(e)}"


def scrape_multiple_urls(urls_text):
    """
    Scrape multiple URLs
    
    Args:
        urls_text: URLs separated by newlines
        
    Returns:
        Summary of results
    """
    if not urls_text:
        return "❌ Please enter URLs (one per line)"
    
    urls = [url.strip() for url in urls_text.split('\n') if url.strip()]
    
    results = []
    success_count = 0
    fail_count = 0
    
    for url in urls:
        try:
            num_chunks = process_and_store_webpage(url)
            results.append(f"βœ… {url}: {num_chunks} chunks")
            success_count += 1
        except Exception as e:
            results.append(f"❌ {url}: {str(e)}")
            fail_count += 1
    
    summary = f"πŸ“Š Summary: {success_count} succeeded, {fail_count} failed\n\n"
    return summary + "\n".join(results)


def delete_document(source_name):
    """
    Delete document by source name
    
    Args:
        source_name: Name or URL of the source
        
    Returns:
        Success message
    """
    if not source_name:
        return "❌ Please enter document name or URL"
    
    try:
        client.delete(
            collection_name=collection_name,
            points_selector=models.FilterSelector(
                filter=models.Filter(
                    must=[
                        models.FieldCondition(
                            key="metadata.source",
                            match=models.MatchValue(value=source_name)
                        )
                    ]
                )
            )
        )
        
        return f"βœ… Successfully deleted all content from:\n{source_name}"
    
    except Exception as e:
        return f"❌ Deletion failed:\n{str(e)}"


def get_current_settings():
    """Load current settings and return as individual values for the UI."""
    s = load_settings()
    return (
        s["disclaimer"],
        s["welcome_message"],
        s["bot_avatar_url"],
        s["primary_color"],
        s["secondary_color"],
        s["font_family"],
    )


def save_chatbot_settings(disclaimer, welcome_message, bot_avatar_url, primary_color, secondary_color, font_family):
    """Save chatbot settings to config file."""
    try:
        s = load_settings()
        s["disclaimer"] = disclaimer
        s["welcome_message"] = welcome_message
        s["bot_avatar_url"] = bot_avatar_url
        s["primary_color"] = primary_color
        s["secondary_color"] = secondary_color
        s["font_family"] = font_family
        save_settings(s)
        return "βœ… Settings saved! Restart the chatbot space for changes to take effect."
    except Exception as e:
        return f"❌ Failed to save: {str(e)}"


# ==================== Gradio Interface (5.49) ====================

with gr.Blocks(
    title="HR Intervals - Admin Panel", 
    theme=gr.themes.Soft()
) as demo:
    
    gr.Markdown("# πŸ“ HR Intervals - Knowledge Base Management")
    gr.Markdown("Manage documents and web content for the AI assistant")
    
    with gr.Tabs():
        
        # Tab 1: View Documents
        with gr.Tab("πŸ“‹ View Documents"):
            gr.Markdown("### Current documents in knowledge base")
            gr.Markdown("πŸ’‘ *Tip: You can select and copy any text from the table below*")
            
            refresh_btn = gr.Button("πŸ”„ Refresh List", variant="primary")
            
            docs_table = gr.HTML(
                label="Documents"
            )
            
            refresh_btn.click(list_all_documents, outputs=docs_table)
            demo.load(list_all_documents, outputs=docs_table)
        
        # Tab 2: Upload Documents
        with gr.Tab("⬆️ Upload Documents"):
            gr.Markdown("### Upload PDF or DOCX files")
            
            file_input = gr.File(
                label="Select File (PDF or DOCX)",
                file_types=[".pdf", ".docx"]
            )
            
            doc_type_input = gr.Radio(
                choices=["document", "policy", "guide", "article"],
                value="document",
                label="Document Type"
            )
            
            upload_btn = gr.Button("πŸ“€ Upload", variant="primary", size="lg")
            upload_output = gr.Textbox(label="Upload Result", lines=5)
            
            upload_btn.click(
                upload_document,
                inputs=[file_input, doc_type_input],
                outputs=upload_output
            )
        
        # Tab 3: Scrape URLs
        with gr.Tab("🌐 Scrape Web Pages"):
            gr.Markdown("### Scrape content from URLs")
            
            with gr.Row():
                with gr.Column():
                    gr.Markdown("#### Single URL")
                    url_input = gr.Textbox(
                        label="Enter URL",
                        placeholder="https://example.com/article"
                    )
                    scrape_btn = gr.Button("πŸ” Scrape", variant="primary")
                    scrape_output = gr.Textbox(label="Result", lines=4)
                    
                    scrape_btn.click(
                        scrape_single_url,
                        inputs=url_input,
                        outputs=scrape_output
                    )
                
                with gr.Column():
                    gr.Markdown("#### Batch URLs")
                    urls_input = gr.Textbox(
                        label="Enter multiple URLs (one per line)",
                        placeholder="https://example.com/page1\nhttps://example.com/page2",
                        lines=6
                    )
                    batch_btn = gr.Button("πŸ” Batch Scrape", variant="primary")
                    batch_output = gr.Textbox(label="Batch Results", lines=8)
                    
                    batch_btn.click(
                        scrape_multiple_urls,
                        inputs=urls_input,
                        outputs=batch_output
                    )
        
        # Tab 4: Delete Documents
        with gr.Tab("πŸ—‘οΈ Delete Documents"):
            gr.Markdown("### Delete documents or web pages")
            gr.Markdown("⚠️ **Warning**: This operation cannot be undone!")
            
            delete_input = gr.Textbox(
                label="Document Name or URL",
                placeholder="e.g., hiring_policy.pdf or https://example.com/article"
            )
            
            delete_btn = gr.Button("πŸ—‘οΈ Delete", variant="stop", size="lg")
            delete_output = gr.Textbox(label="Delete Result", lines=3)
            
            delete_btn.click(
                delete_document,
                inputs=delete_input,
                outputs=delete_output
            )
        
        # Tab 5: Chatbot Settings
        with gr.Tab("βš™οΈ Chatbot Settings"):
            gr.Markdown("### Chatbot Appearance & Text Settings")
            gr.Markdown("Changes take effect after the chatbot space restarts.")

            with gr.Row():
                with gr.Column():
                    setting_primary_color = gr.ColorPicker(label="Primary Color (buttons, links)")
                    setting_secondary_color = gr.ColorPicker(label="Secondary Color (background)")
                    setting_font = gr.Textbox(label="Font Family", placeholder="Arial, sans-serif")
                    setting_avatar = gr.Textbox(label="Bot Avatar Image URL", placeholder="https://...")

                with gr.Column():
                    setting_disclaimer = gr.Textbox(label="Disclaimer Text (Markdown)", lines=6)
                    setting_welcome = gr.Textbox(label="Welcome Message (Markdown)", lines=8)

            save_settings_btn = gr.Button("πŸ’Ύ Save Settings", variant="primary", size="lg")
            settings_output = gr.Textbox(label="Result", lines=2)

            save_settings_btn.click(
                save_chatbot_settings,
                inputs=[setting_disclaimer, setting_welcome, setting_avatar,
                        setting_primary_color, setting_secondary_color, setting_font],
                outputs=settings_output
            )

            demo.load(
                get_current_settings,
                outputs=[setting_disclaimer, setting_welcome, setting_avatar,
                         setting_primary_color, setting_secondary_color, setting_font]
            )

        # Tab 6: Help
        with gr.Tab("ℹ️ Help"):
            gr.Markdown("""
            ### Usage Guide
            
            #### πŸ“‹ View Documents
            - Shows all uploaded documents and web pages
            - Displays document type, upload date, and number of chunks
            - Click "Refresh" to see the latest status
            
            #### ⬆️ Upload Documents
            - Supports PDF and DOCX formats
            - Documents are automatically split into chunks (~1000 characters each)
            - You can categorize documents by type
            
            #### 🌐 Scrape Web Pages
            - Enter full URLs (including https://)
            - Supports single or batch scraping
            - Content is automatically converted to Markdown format
            
            #### πŸ—‘οΈ Delete Documents
            - Enter exact filename or URL
            - Deletes all chunks from that source
            - **Warning**: Cannot be undone!
            - **Tip**: To update a document, delete it first then upload the new version
            
            ---
            
            ### Advanced Management
            
            For detailed vector database management, visit:
            [Qdrant Cloud Dashboard](https://cloud.qdrant.io)
            
            ### Technical Support
            
            If you encounter issues, please contact the development team.
            """)


if __name__ == "__main__":
    admin_user = os.getenv("ADMIN_USERNAME", "admin")
    admin_pass = os.getenv("ADMIN_PASSWORD", "hr-intervals-2026")

    demo.launch(
        server_name="0.0.0.0",
        server_port=7861,
        share=False,
        auth=(admin_user, admin_pass),
    )