File size: 20,677 Bytes
41fb074
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
import gradio as gr
import os
import sqlite3
import json
import hashlib
from datetime import datetime
from typing import List, Dict, Any, Tuple, Optional
import numpy as np
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics.pairwise import cosine_similarity
import threading

from utils import (
    process_document,
    extract_axioms,
    generate_response,
    get_embedding,
    compute_similarity,
    Document,
    Axiom,
    ActivityLog
)

# Initialize database
DB_PATH = "rag_nexus.db"
conn = sqlite3.connect(DB_PATH, check_same_thread=False)
cursor = conn.cursor()

# Create tables
cursor.execute("""
CREATE TABLE IF NOT EXISTS documents (
    id TEXT PRIMARY KEY,
    name TEXT,
    content TEXT,
    size INTEGER,
    uploaded_at TEXT,
    chunk_count INTEGER
)
""")

cursor.execute("""
CREATE TABLE IF NOT EXISTS axioms (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    doc_id TEXT,
    source TEXT,
    axiom TEXT,
    confidence REAL,
    FOREIGN KEY (doc_id) REFERENCES documents (id)
)
""")

cursor.execute("""
CREATE TABLE IF NOT EXISTS activity (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    action TEXT,
    details TEXT,
    timestamp TEXT
)
""")

conn.commit()

# Thread-local storage for database connections
thread_local = threading.local()

def get_db():
    """Get thread-local database connection"""
    if not hasattr(thread_local, 'conn'):
        thread_local.conn = sqlite3.connect(DB_PATH)
    return thread_local.conn

class RAGState:
    def __init__(self):
        self.vectorizer = TfidfVectorizer(max_features=1000, stop_words='english')
        self.document_chunks = []
        self.chunk_metadata = []
        self.is_initialized = False
        
    def initialize_models(self):
        """Initialize models (simulated)"""
        if not self.is_initialized:
            # Load existing documents
            conn = get_db()
            cursor = conn.cursor()
            cursor.execute("SELECT id, content FROM documents")
            docs = cursor.fetchall()
            
            if docs:
                chunks = []
                metadata = []
                for doc_id, content in docs:
                    doc_chunks = [content[i:i+500] for i in range(0, len(content), 500)]
                    chunks.extend(doc_chunks)
                    metadata.extend([{"doc_id": doc_id, "chunk_idx": i} for i in range(len(doc_chunks))])
                
                if chunks:
                    self.vectorizer.fit(chunks)
                    self.document_chunks = chunks
                    self.chunk_metadata = metadata
            
            self.is_initialized = True

def get_state():
    """Get global state"""
    if not hasattr(get_state, 'state'):
        get_state.state = RAGState()
    return get_state.state

def log_activity(action: str, details: Dict[str, Any]):
    """Log activity to database"""
    conn = get_db()
    cursor = conn.cursor()
    cursor.execute(
        "INSERT INTO activity (action, details, timestamp) VALUES (?, ?, ?)",
        (action, json.dumps(details), datetime.now().isoformat())
    )
    conn.commit()

def get_stats():
    """Get system statistics"""
    conn = get_db()
    cursor = conn.cursor()
    
    cursor.execute("SELECT COUNT(*) FROM documents")
    doc_count = cursor.fetchone()[0]
    
    cursor.execute("SELECT COUNT(*) FROM axioms")
    axiom_count = cursor.fetchone()[0]
    
    cursor.execute("SELECT SUM(size) FROM documents")
    storage = cursor.fetchone()[0] or 0
    
    return {
        "doc_count": doc_count,
        "axiom_count": axiom_count,
        "storage_mb": round(storage / 1024 / 1024, 2)
    }

def load_documents():
    """Load all documents"""
    conn = get_db()
    cursor = conn.cursor()
    cursor.execute("SELECT id, name, size, uploaded_at FROM documents ORDER BY uploaded_at DESC")
    docs = cursor.fetchall()
    
    if not docs:
        return [["No documents found", "", "", ""]]
    
    return [[doc[1], f"{doc[2]} bytes", doc[3], doc[0]] for doc in docs]

def load_axioms(source_filter: str = ""):
    """Load axioms with optional source filter"""
    conn = get_db()
    cursor = conn.cursor()
    
    if source_filter:
        cursor.execute("""
            SELECT a.id, a.source, a.axiom, a.confidence, d.name 
            FROM axioms a 
            JOIN documents d ON a.doc_id = d.id 
            WHERE d.name LIKE ? 
            ORDER BY a.confidence DESC
        """, (f"%{source_filter}%",))
    else:
        cursor.execute("""
            SELECT a.id, a.source, a.axiom, a.confidence, d.name 
            FROM axioms a 
            JOIN documents d ON a.doc_id = d.id 
            ORDER BY a.confidence DESC
        """)
    
    axioms = cursor.fetchall()
    
    if not axioms:
        return [["No axioms found", "", "", "", ""]]
    
    return [[ax[4], ax[1], ax[2][:100] + "...", f"{ax[3]:.2f}", str(ax[0])] for ax in axioms]

def load_activity():
    """Load recent activity"""
    conn = get_db()
    cursor = conn.cursor()
    cursor.execute("SELECT action, details, timestamp FROM activity ORDER BY timestamp DESC LIMIT 20")
    activities = cursor.fetchall()
    
    if not activities:
        return [["No activity yet", "", ""]]
    
    return [[act[0], json.loads(act[1]).get('description', ''), act[2]] for act in activities]

def process_uploaded_files(files: List[str]) -> Tuple[str, str]:
    """Process uploaded files and return status"""
    if not files:
        return "No files uploaded", "โš ๏ธ"
    
    state = get_state()
    success_count = 0
    total_count = len(files)
    
    for file_path in files:
        try:
            # Process document
            doc = process_document(file_path)
            
            # Save to database
            conn = get_db()
            cursor = conn.cursor()
            cursor.execute(
                "INSERT INTO documents (id, name, content, size, uploaded_at, chunk_count) VALUES (?, ?, ?, ?, ?, ?)",
                (doc.id, doc.name, doc.content, doc.size, doc.uploaded_at, doc.chunk_count)
            )
            
            # Extract axioms
            axioms = extract_axioms(doc.content, doc.id)
            for axiom in axioms:
                cursor.execute(
                    "INSERT INTO axioms (doc_id, source, axiom, confidence) VALUES (?, ?, ?, ?)",
                    (doc.id, axiom.source, axiom.text, axiom.confidence)
                )
            
            conn.commit()
            
            # Update vector store
            chunks = [doc.content[i:i+500] for i in range(0, len(doc.content), 500)]
            state.document_chunks.extend(chunks)
            state.chunk_metadata.extend([{"doc_id": doc.id, "chunk_idx": i} for i in range(len(chunks))])
            
            # Refit vectorizer if needed
            if state.document_chunks:
                state.vectorizer.fit(state.document_chunks)
            
            log_activity("document_uploaded", {
                "name": doc.name,
                "size": doc.size,
                "chunks": doc.chunk_count
            })
            
            success_count += 1
            
        except Exception as e:
            log_activity("upload_failed", {
                "file": os.path.basename(file_path),
                "error": str(e)
            })
    
    # Clean up temporary files
    for file_path in files:
        try:
            os.unlink(file_path)
        except:
            pass
    
    return f"Processed {success_count}/{total_count} files", "โœ…" if success_count == total_count else "โš ๏ธ"

def generate_rag_response(query: str, use_axioms: bool, use_context: bool) -> Tuple[str, str]:
    """Generate response using RAG"""
    if not query.strip():
        return "Please enter a query", ""
    
    state = get_state()
    state.initialize_models()
    
    # Retrieve context
    context = ""
    retrieved_docs = []
    
    if use_context and state.document_chunks:
        try:
            query_vec = state.vectorizer.transform([query])
            doc_vecs = state.vectorizer.transform(state.document_chunks)
            similarities = cosine_similarity(query_vec, doc_vecs).flatten()
            
            # Get top 3 chunks
            top_indices = np.argsort(similarities)[-3:][::-1]
            
            for idx in top_indices:
                if similarities[idx] > 0.1:
                    chunk = state.document_chunks[idx]
                    doc_id = state.chunk_metadata[idx]["doc_id"]
                    conn = get_db()
                    cursor = conn.cursor()
                    cursor.execute("SELECT name FROM documents WHERE id = ?", (doc_id,))
                    doc_name = cursor.fetchone()[0]
                    
                    context += f"\n\n--- From {doc_name} ---\n{chunk}"
                    retrieved_docs.append(f"{doc_name} (similarity: {similarities[idx]:.2f})")
        except:
            context = ""
            retrieved_docs = ["No relevant context found"]
    
    # Get axioms
    axioms = []
    if use_axioms:
        conn = get_db()
        cursor = conn.cursor()
        cursor.execute("SELECT axiom FROM axioms ORDER BY RANDOM() LIMIT 5")
        axioms = [row[0] for row in cursor.fetchall()]
    
    # Generate response
    response = generate_response(query, context, axioms)
    
    # Log activity
    log_activity("response_generated", {
        "query": query[:100],
        "used_axioms": use_axioms,
        "used_context": use_context
    })
    
    # Format context info
    context_info = "\n".join(retrieved_docs) if retrieved_docs else "No context retrieved"
    
    return response, context_info

def clear_all_data():
    """Clear all data from database"""
    conn = get_db()
    cursor = conn.cursor()
    cursor.execute("DELETE FROM documents")
    cursor.execute("DELETE FROM axioms")
    cursor.execute("DELETE FROM activity")
    conn.commit()
    
    # Reset state
    state = get_state()
    state.document_chunks = []
    state.chunk_metadata = []
    
    log_activity("data_cleared", {"all": True})
    
    return "All data cleared successfully", "โœ…"

def export_axioms():
    """Export axioms as JSON"""
    conn = get_db()
    cursor = conn.cursor()
    cursor.execute("""
        SELECT d.name as document, a.source, a.axiom, a.confidence 
        FROM axioms a 
        JOIN documents d ON a.doc_id = d.id
    """)
    axioms = [{"document": row[0], "source": row[1], "axiom": row[2], "confidence": row[3]} 
              for row in cursor.fetchall()]
    
    if not axioms:
        return "No axioms to export", "โš ๏ธ"
    
    filename = f"axioms_export_{datetime.now().strftime('%Y%m%d_%H%M%S')}.json"
    with open(filename, 'w') as f:
        json.dump(axioms, f, indent=2)
    
    log_activity("axioms_exported", {"count": len(axioms), "file": filename})
    
    return f"Exported {len(axioms)} axioms to {filename}", "โœ…"

# Initialize app state on load
def initialize_app():
    state = get_state()
    state.initialize_models()
    return "โœ… Models initialized"

# Create Gradio interface
with gr.Blocks() as demo:
    gr.Markdown(
        """
        # ๐Ÿ”ฎ RAG Nexus
        ### Intelligent Document Analysis & Axiom Extraction System
        **Built with anycoder** | [View on Hugging Face](https://huggingface.co/spaces/akhaliq/anycoder)
        """
    )
    
    # Status bar
    with gr.Row():
        status_text = gr.Textbox("Initializing...", label="System Status", scale=4)
        init_btn = gr.Button("๐Ÿ”„ Reinitialize", scale=1)
    
    # Tabs
    with gr.Tabs() as tabs:
        # Upload Tab
        with gr.TabItem("๐Ÿ“ค Upload", id="upload"):
            gr.Markdown("### Upload Documents for Analysis")
            
            file_output = gr.File(
                label="Drop files here or click to browse",
                file_count="multiple",
                file_types=[".txt", ".md", ".pdf", ".doc", ".docx"]
            )
            
            upload_btn = gr.Button("๐Ÿš€ Process Files", variant="primary")
            upload_status = gr.Textbox(label="Upload Status", interactive=False)
            
            with gr.Accordion("๐Ÿ“‹ Upload Queue", open=False):
                upload_queue = gr.Dataframe(
                    headers=["File", "Status", "Size (bytes)"],
                    datatype=["str", "str", "number"],
                    label="Processed Files"
                )
        
        # Documents Tab
        with gr.TabItem("๐Ÿ“š Documents", id="documents"):
            gr.Markdown("### Indexed Documents")
            
            with gr.Row():
                doc_search = gr.Textbox(
                    placeholder="Search documents...",
                    label="Search",
                    scale=3
                )
                clear_docs_btn = gr.Button("๐Ÿ—‘๏ธ Clear All", variant="stop", scale=1)
            
            documents_table = gr.Dataframe(
                headers=["Name", "Size", "Uploaded", "ID"],
                datatype=["str", "str", "str", "str"],
                label="Documents",
                wrap=True
            )
            
            doc_search.change(
                fn=lambda search: load_documents(),
                inputs=doc_search,
                outputs=documents_table,
                api_visibility="private"
            )
        
        # Axioms Tab
        with gr.TabItem("โšก Axioms", id="axioms"):
            gr.Markdown("### Extracted Axioms")
            
            with gr.Row():
                axiom_search = gr.Textbox(
                    placeholder="Search axioms...",
                    label="Search",
                    scale=2
                )
                axiom_filter = gr.Dropdown(
                    choices=[],
                    label="Filter by Document",
                    scale=1
                )
                export_axioms_btn = gr.Button("๐Ÿ’พ Export JSON", scale=1)
            
            axioms_table = gr.Dataframe(
                headers=["Document", "Source", "Axiom", "Confidence", "ID"],
                datatype=["str", "str", "str", "number", "str"],
                label="Axioms",
                wrap=True
            )
            
            export_status = gr.Textbox(label="Export Status", interactive=False)
        
        # Generate Tab
        with gr.TabItem("๐Ÿค– Generate", id="generate"):
            gr.Markdown("### Intelligent Response Generation")
            
            query_input = gr.Textbox(
                label="Enter your query",
                placeholder="Ask anything about your documents... (e.g., 'What are the fundamental principles based on the uploaded documents?')",
                lines=4,
                max_lines=8
            )
            
            with gr.Row():
                use_axioms = gr.Checkbox(label="Use Axioms", value=True)
                use_context = gr.Checkbox(label="Use Context (RAG)", value=True)
            
            generate_btn = gr.Button("๐Ÿš€ Generate Response", variant="primary")
            
            with gr.Group():
                response_output = gr.Markdown(
                    label="Generated Response",
                    show_copy_button=True
                )
                
                with gr.Accordion("๐Ÿ“š Retrieved Context & Axioms", open=False):
                    context_output = gr.Textbox(
                        label="Retrieved Documents",
                        lines=5,
                        interactive=False
                    )
            
            query_stats = gr.Textbox(
                label="Query Statistics",
                interactive=False,
                visible=False
            )
        
        # Analytics Tab
        with gr.TabItem("๐Ÿ“Š Analytics", id="analytics"):
            gr.Markdown("### System Analytics")
            
            with gr.Row():
                with gr.Column():
                    doc_count_label = gr.Label(value="0", label="๐Ÿ“„ Documents", show_label=True)
                with gr.Column():
                    axiom_count_label = gr.Label(value="0", label="โšก Axioms", show_label=True)
                with gr.Column():
                    storage_label = gr.Label(value="0MB", label="๐Ÿ’พ Storage Used", show_label=True)
            
            with gr.Accordion("๐Ÿ“ˆ Recent Activity", open=True):
                activity_log = gr.Dataframe(
                    headers=["Action", "Details", "Timestamp"],
                    datatype=["str", "str", "str"],
                    label="Activity Log",
                    wrap=True,
                    max_height=300
                )
    
    # Event handlers
    init_btn.click(
        fn=initialize_app,
        outputs=status_text,
        api_visibility="private"
    )
    
    # Upload events
    def process_and_update(files):
        if not files:
            return "No files selected", []
        
        # Process files
        status, icon = process_uploaded_files(files)
        
        # Create queue table
        queue_data = []
        for f in files:
            name = os.path.basename(f)
            size = os.path.getsize(f) if os.path.exists(f) else 0
            queue_data.append([name, "โœ… Processed", size])
        
        return f"{icon} {status}", queue_data
    
    upload_btn.click(
        fn=process_and_update,
        inputs=file_output,
        outputs=[upload_status, upload_queue],
        api_visibility="private"
    ).then(
        fn=load_documents,
        outputs=documents_table
    ).then(
        fn=lambda: load_axioms(),
        outputs=axioms_table
    ).then(
        fn=get_stats,
        outputs=[doc_count_label, axiom_count_label, storage_label]
    ).then(
        fn=load_activity,
        outputs=activity_log
    )
    
    # Documents tab events
    def refresh_documents():
        docs = load_documents()
        # Update filter choices
        return docs
    
    tabs.change(
        fn=refresh_documents,
        outputs=documents_table,
        api_visibility="private"
    )
    
    clear_docs_btn.click(
        fn=clear_all_data,
        outputs=[status_text],
        api_visibility="private"
    ).then(
        fn=load_documents,
        outputs=documents_table
    ).then(
        fn=lambda: load_axioms(),
        outputs=axioms_table
    ).then(
        fn=get_stats,
        outputs=[doc_count_label, axiom_count_label, storage_label]
    )
    
    # Axioms tab events
    def update_axiom_filter():
        conn = get_db()
        cursor = conn.cursor()
        cursor.execute("SELECT DISTINCT name FROM documents")
        docs = [row[0] for row in cursor.fetchall()]
        return gr.Dropdown(choices=[""] + docs)
    
    tabs.change(
        fn=update_axiom_filter,
        outputs=axiom_filter,
        api_visibility="private"
    )
    
    axiom_filter.change(
        fn=lambda filter_val: load_axioms(filter_val or ""),
        inputs=axiom_filter,
        outputs=axioms_table,
        api_visibility="private"
    )
    
    export_axioms_btn.click(
        fn=export_axioms,
        outputs=[export_status],
        api_visibility="private"
    )
    
    # Generate tab events
    generate_btn.click(
        fn=generate_rag_response,
        inputs=[query_input, use_axioms, use_context],
        outputs=[response_output, context_output],
        api_visibility="private"
    ).then(
        fn=load_activity,
        outputs=activity_log
    )
    
    # Load initial data
    demo.load(
        fn=initialize_app,
        outputs=status_text,
        api_visibility="private"
    ).then(
        fn=load_documents,
        outputs=documents_table
    ).then(
        fn=lambda: load_axioms(),
        outputs=axioms_table
    ).then(
        fn=get_stats,
        outputs=[doc_count_label, axiom_count_label, storage_label]
    ).then(
        fn=load_activity,
        outputs=activity_log
    ).then(
        fn=update_axiom_filter,
        outputs=axiom_filter
    )

# Launch with Gradio 6 theme
demo.launch(
    theme=gr.themes.Soft(
        primary_hue="indigo",
        secondary_hue="violet",
        neutral_hue="slate",
        font=gr.themes.GoogleFont("Inter"),
        text_size="lg",
        spacing_size="lg",
        radius_size="md"
    ).set(
        button_primary_background_fill="*primary_600",
        button_primary_background_fill_hover="*primary_700",
        block_title_text_weight="600",
        block_background_fill="*neutral_50"
    ),
    footer_links=[{"label": "Built with anycoder", "url": "https://huggingface.co/spaces/akhaliq/anycoder"}],
    show_error=True,
    max_threads=40
)