File size: 24,943 Bytes
203bf01
e400f2b
c76b40c
1b060e0
 
 
 
 
 
 
 
 
c76b40c
1b060e0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
20725d6
c76b40c
203bf01
f39843b
20725d6
c76b40c
203bf01
 
f39843b
203bf01
 
f39843b
 
 
 
203bf01
 
 
f39843b
203bf01
 
f39843b
 
203bf01
f39843b
 
 
203bf01
d7b9d89
203bf01
d7b9d89
f39843b
203bf01
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f39843b
203bf01
f39843b
 
 
203bf01
 
 
 
f39843b
203bf01
 
f39843b
 
203bf01
 
d7b9d89
203bf01
 
 
d7b9d89
203bf01
 
f39843b
203bf01
 
f39843b
203bf01
f39843b
203bf01
f39843b
203bf01
 
 
 
f39843b
 
 
 
 
203bf01
 
f39843b
 
203bf01
f39843b
 
203bf01
 
 
 
f39843b
 
203bf01
f39843b
 
 
203bf01
 
 
f39843b
 
203bf01
 
 
f39843b
 
 
203bf01
f39843b
203bf01
f39843b
c76b40c
 
203bf01
 
 
 
 
 
e400f2b
203bf01
f39843b
203bf01
 
f39843b
 
203bf01
f39843b
 
203bf01
 
 
 
 
 
 
 
f39843b
 
203bf01
 
 
c76b40c
f39843b
203bf01
 
f39843b
 
 
203bf01
 
 
 
 
 
 
 
d7b9d89
203bf01
c76b40c
 
1b060e0
203bf01
f39843b
203bf01
f39843b
203bf01
 
 
 
f39843b
203bf01
 
 
 
 
 
 
 
 
 
 
d7b9d89
f39843b
203bf01
 
 
f39843b
 
203bf01
 
 
 
 
 
 
 
 
 
1b060e0
 
 
 
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
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
from huggingface_hub import list_repo_files, hf_hub_download, snapshot_download
from pathlib import Path
from huggingface_hub import list_repo_files, hf_hub_download
import streamlit as st
import os
from PIL import Image
import pandas as pd
import json
from datetime import datetime
from typing import List, Dict, Any, Optional
from RAG import EnhancedMultimodalRAGSystem
from config import *

# Page config
st.set_page_config(
    page_title="DTMI UGM Academic Assistant",
    page_icon="πŸŽ“",
    layout="wide",
    initial_sidebar_state="expanded"
)
st.markdown("""
<style>
/* Main Header */
.main-header {
    background: linear-gradient(135deg, #1e3c72 0%, #2a5298 50%, #4a90e2 100%);
    padding: 2rem;
    border-radius: 15px;
    color: white;
    text-align: center;
    margin-bottom: 2rem;
    box-shadow: 0 8px 32px rgba(0,0,0,0.1);
}

.main-header h1 {
    margin-bottom: 0.5rem;
    font-size: 2.5rem;
    font-weight: 700;
}

.main-header p {
    margin: 0.3rem 0;
    opacity: 0.9;
}

/* Chat Messages - Hitam Putih Simple */
.user-message {
    background: #2d2d2d;
    color: white;
    padding: 1.2rem;
    border-radius: 15px;
    margin: 1rem 0;
    border-left: 5px solid #0084ff;
    box-shadow: 0 4px 12px rgba(0,0,0,0.2);
    animation: slideInRight 0.3s ease-out;
}

.assistant-message {
    background: #f8f9fa;
    color: #2d2d2d;
    padding: 1.2rem;
    border-radius: 15px;
    margin: 1rem 0;
    border-left: 5px solid #28a745;
    box-shadow: 0 4px 12px rgba(0,0,0,0.1);
    animation: slideInLeft 0.3s ease-out;
}

@keyframes slideInRight {
    from { transform: translateX(20px); opacity: 0; }
    to { transform: translateX(0); opacity: 1; }
}

@keyframes slideInLeft {
    from { transform: translateX(-20px); opacity: 0; }
    to { transform: translateX(0); opacity: 1; }
}

/* Example Queries */
.example-query {
    background: #fff8e1;
    color: #333;
    padding: 1rem;
    border-radius: 10px;
    margin: 0.5rem 0;
    border-left: 4px solid #ff9800;
    cursor: pointer;
    transition: all 0.3s ease;
    box-shadow: 0 2px 8px rgba(255, 152, 0, 0.1);
}

.example-query:hover {
    background: #ffecb3;
    transform: translateY(-2px);
    box-shadow: 0 4px 12px rgba(255, 152, 0, 0.2);
}

/* Source Preview */
.source-preview {
    background: #f5f5f5;
    color: #333;
    padding: 1rem;
    border-radius: 10px;
    margin: 0.5rem 0;
    font-size: 0.9em;
    border-left: 3px solid #6c757d;
}

/* Buttons */
.stButton > button {
    border-radius: 10px !important;
    font-weight: 600 !important;
    transition: all 0.3s ease !important;
}

.stButton > button:hover {
    transform: translateY(-1px) !important;
    box-shadow: 0 4px 12px rgba(0,0,0,0.15) !important;
}
.chat-container {
    height: calc(100vh - 180px);
    overflow-y: auto;
    padding: 1rem;
    border: 1px solid #e0e0e0;
    border-radius: 10px;
    background-color: #fafafa;
    margin-bottom: 1rem;
}
.fixed-input {
    position: fixed;
    bottom: 2rem;
    width: 60%;
    max-width: 800px;
    left: 50%;
    transform: translateX(-50%);
    background-color: white;
    padding: 1rem;
    border-radius: 10px;
    box-shadow: 0 4px 16px rgba(0,0,0,0.1);
    z-index: 999;
}
.spacer {
    height: 120px; /* Tambahkan spacer agar konten tak tertutup input */
}
</style>
""", unsafe_allow_html=True)


@st.cache_resource
def initialize_rag_system():
    try:
        return EnhancedMultimodalRAGSystem()
    except Exception as e:
        st.error(f"❌ Error initializing RAG system: {e}")
        st.stop()


def display_example_queries():
    """Display clickable example queries"""
    st.markdown("### πŸ’‘ Contoh Pertanyaan")

    for category, queries in EXAMPLE_QUERIES.items():
        with st.expander(f"{category}", expanded=True):
            for query in queries:
                if st.button(f"πŸ’¬ {query}", key=f"example_{hash(query)}", use_container_width=True):
                    st.session_state.user_input = query
                    st.rerun()


def display_tables_in_chat(table_data: List[Dict]):
    """Display tables directly in chat"""
    if not table_data:
        return

    st.markdown("### πŸ“Š Tabel Data")

    for i, table_info in enumerate(table_data, 1):
        with st.expander(f"πŸ“Š {table_info['title']} (Hal. {table_info['page']}, {table_info['year']})", expanded=True):

            # Table metadata
            col1, col2, col3 = st.columns(3)
            with col1:
                st.metric("πŸ“„ Halaman", table_info['page'])
            with col2:
                st.metric("πŸ“… Tahun", table_info['year'])
            with col3:
                st.metric("πŸ“Š Score", f"{table_info['score']:.3f}")
            # Display table data
            try:
                if table_info.get("data_type") == "dataframe" and isinstance(table_info["data"], pd.DataFrame):
                    st.dataframe(table_info["data"], use_container_width=True)
                    # Download CSV
                    csv_data = table_info["data"].to_csv(index=False)
                    st.download_button(
                        label="πŸ’Ύ Download CSV",
                        data=csv_data,
                        file_name=f"table_{i}_{datetime.now().strftime('%Y%m%d_%H%M%S')}.csv",
                        mime="text/csv"
                    )

                elif table_info.get("data_type") == "json":
                    st.json(table_info["data"])

                    # Download JSON
                    json_str = json.dumps(table_info["data"], indent=2, ensure_ascii=False)
                    st.download_button(
                        label="πŸ’Ύ Download JSON",
                        data=json_str,
                        file_name=f"data_{i}_{datetime.now().strftime('%Y%m%d_%H%M%S')}.json",
                        mime="application/json"
                    )

                # Show description
                if table_info.get('description'):
                    st.markdown("**πŸ“ Deskripsi:**")
                    st.text(table_info['description'])

            except Exception as e:
                st.error(f"❌ Error displaying table: {e}")


def display_single_image_compact(img_info: Dict, index: int):
    """Display single image in compact format - CLEAN VERSION"""
    try:
        image_path = img_info["path"]

        # Check if file exists
        if not os.path.exists(image_path):
            st.error(f"❌ Gambar {index} tidak ditemukan")
            return

        # Load and display image
        image = Image.open(image_path)

        # Display image with nice styling
        st.image(image,
                 caption=f"πŸ“– {img_info.get('title', 'Gambar')} - Hal. {img_info.get('page', 'N/A')} ({img_info.get('year', 'N/A')})",
                 use_container_width=True)

        # Compact metadata
        col1, col2 = st.columns(2)
        with col1:
            st.metric("πŸ“Š Relevance Score", f"None")
            # {img_info.get('score', 0):.2f}")
        with col2:
            st.metric("πŸ“ Ukuran", f"{image.width}Γ—{image.height}px")

        # Expandable details
        with st.expander(f"πŸ“ Detail Gambar {index}", expanded=False):
            if img_info.get('description'):
                st.markdown("**πŸ“„ Deskripsi:**")
                st.text(img_info['description'])
            if img_info.get('caption'):
                st.markdown("**πŸ’¬ Caption:**")
                st.text(img_info['caption'])

    except Exception as e:
        st.error(f"❌ Error loading image {index}: {str(e)}")


def display_single_image_full(img_info: Dict):
    """Display single image in full format - CLEAN VERSION"""
    try:
        image_path = img_info["path"]

        if not os.path.exists(image_path):
            st.error("❌ Gambar tidak ditemukan")
            return

        # Load image
        image = Image.open(image_path)

        # Display with title
        st.markdown(f"### πŸ–ΌοΈ {img_info.get('title', 'Gambar')}")

        # Create columns for image and metadata
        col1, col2 = st.columns([3, 1])

        with col1:
            st.image(image, use_column_width=True)

        with col2:
            st.markdown("**πŸ“‹ Informasi Gambar**")
            st.metric("πŸ“„ Halaman", img_info.get('page', 'N/A'))
            st.metric("πŸ“… Tahun", img_info.get('year', 'N/A'))
            # st.metric("πŸ“Š Score", f"{img_info.get('score', 0):.3f}")
            st.metric("πŸ“ Dimensi", f"{image.width} Γ— {image.height}")

            # Download button
            with open(image_path, "rb") as file:
                st.download_button(
                    label="πŸ’Ύ Download Gambar",
                    data=file.read(),
                    file_name=os.path.basename(image_path),
                    mime="image/png",
                    use_container_width=True
                )

        # Description below image
        if img_info.get('description'):
            st.markdown("**πŸ“ Deskripsi Gambar:**")
            st.info(img_info['description'])

        if img_info.get('caption'):
            st.markdown("**πŸ’¬ Caption:**")
            st.info(img_info['caption'])

    except Exception as e:
        st.error(f"❌ Error loading image: {str(e)}")


def display_images_in_chat(image_data: List[Dict], show_details: bool = True):
    """Display images directly in chat - CLEAN VERSION"""
    if not image_data:
        return

    st.markdown("### πŸ–ΌοΈ Gambar Terkait")
    if len(image_data) == 1:
        st.markdown(f"*Ditemukan 1 gambar relevan*")
    else:
        st.markdown(f"*Ditemukan {len(image_data)} gambar relevan*")
    if len(image_data) > 1:
        cols = st.columns(min(len(image_data), 2))  # Max 2 columns
        for i, img_info in enumerate(image_data):
            with cols[i % 2]:
                display_single_image_compact(img_info, i+1)
    else:
        display_single_image_full(image_data[0])


def enhanced_chat_interface():
    if 'messages' not in st.session_state:
        st.session_state.messages = []
    if 'user_input' not in st.session_state:
        st.session_state.user_input = ""
    rag_system = initialize_rag_system()
    st.markdown("""
    <div class="main-header">
        <h1>πŸŽ“ DTMI UGM Academic Assistant</h1>
        <p>Asisten Cerdas Multimodal untuk Informasi Akademik DTMI UGM</p>
        <p>πŸ’¬ Tanyakan apapun tentang kurikulum, silabus, gambar, dan tabel data</p>
    </div>
    """, unsafe_allow_html=True)

    # Sidebar with controls
    with st.sidebar:
        st.markdown("### βš™οΈ Pengaturan")

        # Content type preferences
        st.markdown("### 🎯 Preferensi Konten")
        content_preferences = []
        for content_type, description in CONTENT_TYPE_DESCRIPTIONS.items():
            if st.checkbox(description, key=f"pref_{content_type}"):
                content_preferences.append(content_type)

        # Retrieval settings
        st.markdown("### πŸ” Pengaturan Pencarian")
        max_results = st.slider("Jumlah Konteks Maksimal", 5, 20, 10)

        # Display settings
        st.markdown("### 🎭 Tampilan")
        show_images_inline = st.checkbox("πŸ–ΌοΈ Tampilkan Gambar", value=True)
        show_tables_inline = st.checkbox("πŸ“Š Tampilkan Tabel", value=True)
        compact_mode = st.checkbox("πŸ“± Mode Kompak", value=False)

        # Chat statistics
        if st.session_state.messages:
            st.markdown("### πŸ“Š Statistik")
            total_messages = len(st.session_state.messages)
            st.metric("πŸ’¬ Total Pesan", total_messages)
            st.metric("πŸ—£οΈ Percakapan", total_messages // 2)

        # Clear chat
        if st.button("πŸ—‘οΈ Hapus Chat", type="secondary", use_container_width=True):
            st.session_state.messages = []
            st.rerun()

    # Main chat area
    col1, col2 = st.columns([3, 1] if not compact_mode else [1, 0])

    with col1:
        # Display chat history

        for message in st.session_state.messages:
            if message["role"] == "user":
                st.markdown(f"""
                <div class="user-message">
                    <strong>πŸ‘€ Anda:</strong><br>
                    {message["content"]}
                </div>
                """, unsafe_allow_html=True)
            else:
                st.markdown(f"""
                <div class="assistant-message">
                    <strong>πŸ€– Assistant:</strong><br>
                    {message["content"]}
                </div>
                """, unsafe_allow_html=True)

                # 🎯 DISPLAY MULTIMODAL CONTENT
                if "result_data" in message:
                    result_data = message["result_data"]

                    # Show quick stats if has multimodal content
                    if result_data.get("has_images") or result_data.get("has_tables"):
                        st.markdown("---")  # Separator

                        col_stats1, col_stats2, col_stats3 = st.columns(3)
                        with col_stats1:
                            st.metric("πŸ–ΌοΈ Gambar", len(result_data.get("image_data", [])))
                        with col_stats2:
                            st.metric("πŸ“Š Tabel", len(result_data.get("table_data", [])))
                        with col_stats3:
                            st.metric("πŸ“š Sumber", result_data.get("total_sources", 0))

                    # πŸ–ΌοΈ DISPLAY IMAGES
                    if show_images_inline and result_data.get("has_images"):
                        display_images_in_chat(result_data.get("image_data", []))

                    # πŸ“Š DISPLAY TABLES
                    if show_tables_inline and result_data.get("has_tables"):
                        display_tables_in_chat(result_data.get("table_data", []))

                # Collapsible sources
                if "sources" in message and message["sources"]:
                    with st.expander("πŸ“š Lihat Sumber Informasi", expanded=False):
                        for i, source in enumerate(message["sources"][:3], 1):
                            content_type = source['metadata']['content_type']
                            year = source['metadata'].get('year', 'N/A')
                            page = source['metadata'].get('page', 'N/A')

                            st.markdown(f"""
                            **πŸ“‹ Sumber {i}:** {CONTENT_TYPE_DESCRIPTIONS.get(content_type, content_type)}  
                            **πŸ“… Tahun:** {year} | **πŸ“„ Halaman:** {page}  
                            **πŸ“ Preview:** {source['content'][:150]}...
                            """)
                            st.markdown("---")

        # Chat input
        user_input = st.chat_input(
            "πŸ’¬ Tanyakan tentang kurikulum, gambar, tabel, atau informasi lainnya...", key="chat_input")

        # Handle example query selection
        if st.session_state.user_input:
            user_input = st.session_state.user_input
            st.session_state.user_input = ""

        # πŸš€ PROCESS USER INPUT
        if user_input:
            # Add user message
            st.session_state.messages.append({"role": "user", "content": user_input})

            # Show loading
            with st.spinner("πŸ” Mencari informasi relevan..."):
                try:
                    result_data = rag_system.query(
                        user_input,
                        k=max_results,
                        content_filter=content_preferences if content_preferences else None
                    )

                    # Save assistant message with complete data
                    assistant_message = {
                        "role": "assistant",
                        "content": result_data["answer"],
                        "sources": result_data["sources"],
                        "result_data": result_data
                    }

                    st.session_state.messages.append(assistant_message)

                except Exception as e:
                    st.error(f"❌ Terjadi kesalahan: {e}")
                    st.session_state.messages.append({
                        "role": "assistant",
                        "content": "Maaf, terjadi kesalahan dalam memproses pertanyaan Anda. Silakan coba lagi."
                    })

            st.rerun()

    # Sidebar dengan example queries (only if not compact)
    if not compact_mode:
        with col2:
            display_example_queries()

            # Quick actions
            st.markdown("### ⚑ Aksi Cepat")

            quick_actions = [
                ("πŸ–ΌοΈ Cari Gambar", "Tampilkan gambar formulir atau diagram"),
                ("πŸ“Š Lihat Tabel", "Tabel kurikulum semester 1"),
                ("πŸŽ“ Info Program", "Informasi program studi teknik mesin"),
                ("πŸ“š Silabus", "Silabus mata kuliah wajib")
            ]

            for label, query in quick_actions:
                if st.button(label, use_container_width=True):
                    st.session_state.user_input = query
                    st.rerun()
            if st.session_state.messages:
                st.markdown("### πŸ“€ Export")
                if st.button("πŸ’Ύ Download Chat", use_container_width=True):
                    chat_export = ""
                    for msg in st.session_state.messages:
                        role = "User" if msg["role"] == "user" else "Assistant"
                        chat_export += f"**{role}:** {msg['content']}\n\n"

                    st.download_button(
                        label="πŸ“„ Download Markdown",
                        data=chat_export,
                        file_name=f"chat_dtmi_{datetime.now().strftime('%Y%m%d_%H%M%S')}.md",
                        mime="text/markdown",
                        use_container_width=True
                    )


REPO_ID = "wicaksonolxn/dataoptim"
REPO_TYPE = "dataset"
LOCALROOT = Path("./repo_data")  # Changed to a specific subfolder
MARKER = LOCALROOT / ".hf_mirror_complete"


def ensure_cache_dir():
    cache_dir = Path.home() / ".cache" / "huggingface"
    try:
        cache_dir.mkdir(parents=True, exist_ok=True)
        test_file = cache_dir / "test_write"
        test_file.touch()
        test_file.unlink()
        return True
    except Exception as e:
        st.warning(f"Cannot create cache dir at {cache_dir}: {e}")
        # Try alternative cache location
        alt_cache = Path("./cache/huggingface")
        try:
            alt_cache.mkdir(parents=True, exist_ok=True)
            os.environ["HF_HOME"] = str(alt_cache.parent)
            return True
        except Exception as e2:
            st.error(f"Cannot create alternative cache: {e2}")
            return False


def mirror_repo_fixed(repo_id: str, repo_type: str, local_root: Path) -> bool:
    try:
        if not ensure_cache_dir():
            return False

        # Ensure local root exists
        local_root.mkdir(parents=True, exist_ok=True)

        st.write(f"⏬ Downloading repository '{repo_id}' to {local_root}")
        downloaded_path = snapshot_download(
            repo_id=repo_id,
            repo_type=repo_type,
            local_dir=str(local_root),
            local_dir_use_symlinks=False,
            resume_download=True,
            force_download=False,
        )

        # Create completion marker
        MARKER.touch()
        st.success(f"βœ… Repository downloaded successfully to {downloaded_path}")
        return True

    except Exception as e:
        st.error(f"❌ Error downloading repository: {e}")
        return False


def mirror_repo_file_by_file(repo_id: str, repo_type: str, local_root: Path) -> bool:
    """
    Alternative file-by-file download method - more control but slower
    """
    try:
        # Ensure cache directory exists
        if not ensure_cache_dir():
            return False

        # Get list of files
        remote_files = list_repo_files(repo_id=repo_id, repo_type=repo_type)

        if not remote_files:
            st.error(f"No files found in repository '{repo_id}'")
            return False

        st.write(f"⏬ Copying **{len(remote_files)}** files from Hugging Face Hub...")
        bar = st.progress(0.0)

        # Ensure local root exists
        local_root.mkdir(parents=True, exist_ok=True)

        for i, remote_file in enumerate(remote_files, 1):
            try:
                # Download to local_root directly
                downloaded_file = hf_hub_download(
                    repo_id=repo_id,
                    filename=remote_file,
                    repo_type=repo_type,
                    local_dir=str(local_root),  # Download directly to target directory
                    local_dir_use_symlinks=False,
                    force_download=False,
                    resume_download=True,
                )

                # Update progress
                bar.progress(i / len(remote_files))

            except Exception as file_error:
                st.warning(f"Failed to download {remote_file}: {file_error}")
                continue

        # Create completion marker
        MARKER.touch()
        st.success("βœ… Download completed – all files are now local.")
        return True

    except Exception as e:
        st.error(f"❌ Error in file-by-file download: {e}")
        return False


def verify_download(local_root: Path) -> dict:
    """Verify the downloaded repository structure"""
    if not local_root.exists():
        return {"status": "missing", "files": 0, "size": 0}

    files = list(local_root.rglob("*"))
    file_count = len([f for f in files if f.is_file()])
    total_size = sum(f.stat().st_size for f in files if f.is_file())

    return {
        "status": "exists",
        "files": file_count,
        "size": total_size,
        "size_mb": round(total_size / (1024 * 1024), 2)
    }


@st.cache_resource(show_spinner=False)
def ensure_repo_mirrored() -> bool:
    """
    Ensure repository is mirrored locally with better error handling
    """
    # Check if already mirrored
    if MARKER.exists():
        verification = verify_download(LOCALROOT)
        if verification["files"] > 0:
            st.success(
                f"βœ… Repository already available locally ({verification['files']} files, {verification['size_mb']} MB)")
            return True
        else:
            # Marker exists but no files - remove marker and re-download
            MARKER.unlink()

    # Show current status
    verification = verify_download(LOCALROOT)
    if verification["status"] == "exists" and verification["files"] > 0:
        st.info(f"πŸ”„ Found partial download ({verification['files']} files). Resuming...")

    # Try snapshot download first (recommended)
    st.info("πŸš€ Attempting full repository download...")
    if mirror_repo_fixed(REPO_ID, REPO_TYPE, LOCALROOT):
        return True

    # Fallback to file-by-file if snapshot fails
    st.warning("⚠️ Snapshot download failed. Trying file-by-file download...")
    if mirror_repo_file_by_file(REPO_ID, REPO_TYPE, LOCALROOT):
        return True

    # If both methods fail
    st.error("❌ All download methods failed. Please check your internet connection and repository access.")
    return False


def cleanup_partial_download():
    """Clean up partial downloads and reset"""
    if LOCALROOT.exists():
        import shutil
        shutil.rmtree(LOCALROOT)
    if MARKER.exists():
        MARKER.unlink()
    st.success("πŸ—‘οΈ Cleaned up partial downloads")

# Enhanced main function with better error handling


def main():
    """Main function with robust repository handling"""

    # Add cleanup option in sidebar for debugging
    with st.sidebar:
        st.markdown("### πŸ”§ Debug Options")
        if st.button("πŸ—‘οΈ Clean & Re-download"):
            cleanup_partial_download()
            st.rerun()

        # Show download status
        verification = verify_download(LOCALROOT)
        if verification["status"] == "exists":
            st.success(f"πŸ“ Local files: {verification['files']}")
            st.success(f"πŸ’Ύ Size: {verification['size_mb']} MB")
    try:
        if ensure_repo_mirrored():
            enhanced_chat_interface()
        else:
            st.error("❌ Failed to download repository. Please try again or check your connection.")
            if st.button("πŸ”„ Retry Download"):
                st.rerun()

    except Exception as e:
        st.error(f"❌ Critical error in main(): {e}")
        st.info("πŸ’‘ Try using the 'Clean & Re-download' button in the sidebar")


def get_repo_info():
    try:
        files = list_repo_files(repo_id=REPO_ID, repo_type=REPO_TYPE)
        return {
            "total_files": len(files),
            "file_types": list(set(Path(f).suffix for f in files if Path(f).suffix)),
            "sample_files": files[:5]
        }
    except Exception as e:
        return {"error": str(e)}


if __name__ == "__main__":
    main()