-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.py
More file actions
1108 lines (1023 loc) · 46.1 KB
/
server.py
File metadata and controls
1108 lines (1023 loc) · 46.1 KB
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
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import argparse, sqlite3, os, re
from flask import Flask, request, render_template_string, redirect, url_for, flash, jsonify
TEMPLATE = """
<!doctype html>
<title>Inchive</title>
<style>
* { box-sizing: border-box; }
body {
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
margin: 0; padding: 0;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
min-height: 100vh;
line-height: 1.6;
}
.container {
max-width: 1400px; margin: 0 auto; background: white;
min-height: 100vh; box-shadow: 0 0 50px rgba(0,0,0,0.1);
}
.header {
background: linear-gradient(135deg, #1e3a8a 0%, #3730a3 100%);
color: white; padding: 24px 32px;
box-shadow: 0 4px 20px rgba(0,0,0,0.1);
}
.header h1 { margin: 0; font-size: 28px; font-weight: 700; }
.header .subtitle { opacity: 0.9; font-size: 16px; margin-top: 4px; }
.content { padding: 32px; }
.search-section {
background: #f8fafc; padding: 32px; border-radius: 16px;
margin-bottom: 32px; box-shadow: 0 2px 8px rgba(0,0,0,0.04);
}
.search-row { display: flex; gap: 16px; align-items: center; margin-bottom: 20px; flex-wrap: wrap; }
.search-input {
flex: 1; min-width: 300px; padding: 16px 20px; font-size: 18px;
border: 2px solid #e2e8f0; border-radius: 12px;
transition: all 0.2s; background: white;
}
.search-input:focus{
outline: none; border-color: #3b82f6;
box-shadow: 0 0 0 4px rgba(59,130,246,0.1); transform: translateY(-1px);
}
.search-btn {
padding: 16px 32px; font-size: 18px; font-weight: 600;
background: linear-gradient(135deg, #3b82f6 0%, #1d4ed8 100%);
color: white; border: none; border-radius: 12px; cursor: pointer;
transition: all 0.2s; box-shadow: 0 4px 12px rgba(59,130,246,0.3);
}
.search-btn:hover{
transform: translateY(-2px);
box-shadow: 0 6px 20px rgba(59,130,246,0.4);
}
.controls{
display:flex; gap:20px; align-items:center; flex-wrap:wrap;
padding: 20px; background: white; border-radius: 12px;
box-shadow: 0 1px 3px rgba(0,0,0,0.1);
}
.control-group { display: flex; align-items: center; gap: 8px; }
.control-group label { font-weight: 500; color: #374151; white-space: nowrap; }
.control-group input, .control-group select {
padding: 8px 12px; border: 1px solid #d1d5db; border-radius: 8px;
font-size: 14px; transition: border-color 0.2s;
}
.control-group input:focus, .control-group select:focus {
outline: none; border-color: #3b82f6;
}
.checkbox-label { display: flex; align-items: center; gap: 8px; cursor: pointer; }
.result{
border: 1px solid #e5e7eb; padding: 24px; margin: 20px 0;
border-radius: 16px; background: white;
box-shadow: 0 2px 12px rgba(0,0,0,0.06);
transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}
.result:hover{
transform: translateY(-4px);
box-shadow: 0 8px 25px rgba(0,0,0,0.12);
border-color: #3b82f6;
}
.result-header { display: flex; justify-content: space-between; align-items: flex-start; margin-bottom: 16px; }
.result-title { font-size: 20px; font-weight: 700; color: #111827; margin: 0; }
.result-title a { color: inherit; text-decoration: none; }
.result-title a:hover { color: #3b82f6; }
.result-meta { display: flex; gap: 12px; flex-wrap: wrap; align-items: center; margin-bottom: 16px; }
.pill{
padding: 6px 14px; border-radius: 20px; font-size: 13px;
font-weight: 600; text-transform: uppercase; letter-spacing: 0.5px;
border: 1px solid; cursor: pointer; transition: all 0.2s;
}
.pill:hover { transform: translateY(-1px); box-shadow: 0 2px 8px rgba(0,0,0,0.15); }
.pill.anthropic {
background: linear-gradient(135deg, #dbeafe 0%, #bfdbfe 100%);
color: #1e40af; border-color: #93c5fd;
}
.pill.chatgpt {
background: linear-gradient(135deg, #dcfce7 0%, #bbf7d0 100%);
color: #166534; border-color: #86efac;
}
.pill.default {
background: linear-gradient(135deg, #f3f4f6 0%, #e5e7eb 100%);
color: #374151; border-color: #d1d5db;
}
.result-content { font-size: 16px; line-height: 1.7; color: #374151; margin-bottom: 16px; }
.expand-context { margin-top: 16px; padding: 16px; background: #f8fafc; border-radius: 12px; border: 1px solid #e2e8f0; }
.context-message { margin-bottom: 16px; padding: 12px; border-radius: 8px; }
.context-message.current { background: #fef3c7; border: 2px solid #f59e0b; }
.context-message.user { background: #eff6ff; }
.context-message.assistant { background: #f0fdf4; }
.context-header { font-weight: 600; margin-bottom: 8px; color: #374151; }
.context-content { color: #6b7280; }
.expand-btn { color: #3b82f6; cursor: pointer; font-weight: 500; }
.expand-btn:hover { text-decoration: underline; }
mark{ background: linear-gradient(135deg, #fef08a 0%, #fde047 100%); padding: 3px 6px; border-radius: 6px; font-weight: 600; }
.result-actions { display: flex; gap: 16px; align-items: center; }
.result-actions a {
color: #6b7280; text-decoration: none; font-weight: 500;
transition: color 0.2s; display: flex; align-items: center; gap: 4px;
}
.result-actions a:hover { color: #3b82f6; }
.result-footer {
border-top: 1px solid #f3f4f6; padding-top: 12px; margin-top: 16px;
font-size: 13px; color: #9ca3af; display: flex; gap: 16px;
}
.stats {
background: #f1f5f9; padding: 20px; border-radius: 12px;
margin-bottom: 24px; text-align: center; color: #475569; font-weight: 500;
}
.reindex-section {
background: #fefefe; border: 2px dashed #d1d5db;
padding: 24px; border-radius: 12px; margin-bottom: 32px;
}
.reindex-form { display: flex; gap: 12px; align-items: center; flex-wrap: wrap; }
.reindex-input {
flex: 1; min-width: 300px; padding: 12px 16px;
border: 1px solid #d1d5db; border-radius: 8px; font-size: 14px;
}
.reindex-btn {
padding: 12px 24px; background: #10b981; color: white;
border: none; border-radius: 8px; font-weight: 600; cursor: pointer;
transition: background 0.2s;
}
.reindex-btn:hover { background: #059669; }
.flash-messages{ margin: 24px 0; }
.flash{
padding: 16px 20px; border-radius: 12px; margin: 12px 0;
font-weight: 500; display: flex; align-items: center; gap: 12px;
}
.flash.success{ background: #d1fae5; color: #065f46; border-left: 4px solid #10b981; }
.flash.error{ background: #fee2e2; color: #991b1b; border-left: 4px solid #ef4444; }
.flash.warning{ background: #fef3c7; color: #92400e; border-left: 4px solid #f59e0b; }
/* Date range picker styles */
.date-range-container { margin: 8px 0; }
.date-range-container input[type="date"] {
min-width: 130px;
}
.date-range-container input[type="date"]:focus {
border-color: #3b82f6;
box-shadow: 0 0 0 2px rgba(59,130,246,0.1);
}
.filter-section {
background: white; border-radius: 12px; padding: 20px;
box-shadow: 0 1px 3px rgba(0,0,0,0.1); margin-bottom: 20px;
}
.realtime-note {
font-size: 12px; color: #10b981; margin-top: 8px;
display: flex; align-items: center; gap: 4px;
}
/* Conversation shelf styles */
.conversation-shelf {
position: fixed; top: 0; right: -50%; width: 50%; height: 100vh;
background: white; box-shadow: -4px 0 20px rgba(0,0,0,0.15);
transition: right 0.3s ease-in-out; z-index: 1000;
display: flex; flex-direction: column;
}
.conversation-shelf.open { right: 0; }
.shelf-header {
background: linear-gradient(135deg, #1e3a8a 0%, #3730a3 100%);
color: white; padding: 20px; display: flex; justify-content: space-between; align-items: center;
box-shadow: 0 2px 10px rgba(0,0,0,0.1);
}
.shelf-content { flex: 1; overflow-y: auto; padding: 20px; }
.shelf-close {
background: rgba(255,255,255,0.2); border: none; color: white;
border-radius: 6px; padding: 8px 12px; cursor: pointer; font-size: 16px;
}
.shelf-close:hover { background: rgba(255,255,255,0.3); }
.shelf-overlay {
position: fixed; top: 0; left: 0; width: 100%; height: 100%;
background: rgba(0,0,0,0.5); opacity: 0; visibility: hidden;
transition: all 0.3s ease-in-out; z-index: 999;
}
.shelf-overlay.open { opacity: 1; visibility: visible; }
.message-item {
border: 1px solid #e5e7eb; border-radius: 12px; padding: 16px; margin: 12px 0;
background: #fafafa;
}
.message-role {
font-weight: 600; margin-bottom: 8px; display: flex; align-items: center; gap: 8px;
}
.message-content { white-space: pre-wrap; line-height: 1.5; }
@media (max-width: 768px) {
.content { padding: 20px; }
.search-row { flex-direction: column; }
.search-input { min-width: 100%; }
.controls { flex-direction: column; align-items: flex-start; gap: 12px; }
.result-header { flex-direction: column; gap: 12px; }
.date-range-container { flex-direction: column; align-items: stretch; gap: 4px; }
.date-range-container input[type="date"] { min-width: unset; }
.conversation-shelf { width: 100%; right: -100%; }
.conversation-shelf.open { right: 0; }
}
</style>
<meta name="referrer" content="no-referrer"/>
<div class="container">
<div class="header">
<div style="display: flex; justify-content: space-between; align-items: center;">
<div>
<h1>🔍 Inchive</h1>
<div class="subtitle">Lightning-fast search for your AI conversations</div>
</div>
<a href="{{ url_for('admin') }}" style="color: rgba(255,255,255,0.9); text-decoration: none; padding: 8px 16px; background: rgba(255,255,255,0.1); border-radius: 8px; transition: background 0.2s;">
⚙️ Admin
</a>
</div>
</div>
<div class="content">
<div class="flash-messages">
{% with messages = get_flashed_messages() %}
{% if messages %}
{% for message in messages %}
<div class="flash {% if '✅' in message %}success{% elif '❌' in message %}error{% else %}warning{% endif %}">{{ message }}</div>
{% endfor %}
{% endif %}
{% endwith %}
</div>
<div class="search-section">
<form method="GET">
<div class="search-row">
<input type="text" name="q" value="{{q|e}}" placeholder="🔍 Search your conversations..." autofocus class="search-input"/>
<button type="submit" class="search-btn">Search</button>
</div>
<div class="filter-section">
<div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 16px;">
<h3 style="margin: 0; color: #374151;">🔍 Filters</h3>
<div class="realtime-note">
⚡ Real-time filtering
</div>
</div>
<div class="controls">
<div class="control-group">
<label class="checkbox-label">
<input type="checkbox" name="wild" value="1" {% if wild %}checked{% endif %} onchange="applyFilters()">
<span>Smart expand</span>
<span style="font-size: 11px; color: #6b7280; margin-left: 4px;" title="Automatically adds wildcards to search terms for partial matching (enabled by default)">(?)</span>
</label>
</div>
<div class="control-group">
<label>🤖 Provider</label>
<select name="provider" onchange="applyFilters()">
<option value="" {% if not provider %}selected{% endif %}>All Providers</option>
<option value="claude" {% if provider == 'claude' %}selected{% endif %}>🔵 Claude</option>
<option value="chatgpt" {% if provider == 'chatgpt' %}selected{% endif %}>🟢 ChatGPT</option>
</select>
</div>
<div class="control-group">
<label>👤 Role</label>
<select name="role" onchange="applyFilters()">
<option value="" {% if not role %}selected{% endif %}>All Roles</option>
<option value="user" {% if role == 'user' %}selected{% endif %}>👤 Human</option>
<option value="assistant" {% if role == 'assistant' %}selected{% endif %}>🤖 Assistant</option>
</select>
</div>
<div class="control-group">
<label>📊 Sort</label>
<select name="sort" onchange="applyFilters()">
<option value="rank" {% if sort == 'rank' %}selected{% endif %}>Relevance</option>
<option value="newest" {% if sort == 'newest' %}selected{% endif %}>Newest</option>
<option value="oldest" {% if sort == 'oldest' %}selected{% endif %}>Oldest</option>
</select>
</div>
</div>
<div style="display: flex; gap: 24px; margin-top: 16px; flex-wrap: wrap;">
<div class="control-group">
<label>📅 Date Range</label>
<div class="date-range-container" style="display: flex; align-items: center; gap: 8px;">
<input type="date" name="date_from" value="{{date_from}}"
onchange="applyFilters()"
title="Start date (leave empty for no limit)"
style="padding: 6px 8px; border: 1px solid #d1d5db; border-radius: 6px; font-size: 13px;">
<span style="color: #6b7280;">to</span>
<input type="date" name="date_to" value="{{date_to}}"
onchange="applyFilters()"
title="End date (leave empty for no limit)"
style="padding: 6px 8px; border: 1px solid #d1d5db; border-radius: 6px; font-size: 13px;">
{% if date_from or date_to %}
<button type="button" onclick="clearDateRange()"
style="padding: 4px 8px; background: #f3f4f6; border: 1px solid #d1d5db; border-radius: 4px; font-size: 12px; cursor: pointer;"
title="Clear date filters">✕</button>
{% endif %}
</div>
</div>
</div>
</div>
</form>
</div>
{% if rows is not none %}
<div class="stats">
<strong>{{total_count}}</strong> result(s) found
{% if total_pages > 1 %}
• Page {{page}} of {{total_pages}}
• Showing {{per_page}} per page
{% endif %}
</div>
{% for r in rows %}
<div class="result">
<div class="result-header">
<h3 class="result-title">
<a href="{{ url_for('conversation', conv_id=r['conv_id']) }}">{{r['title']}}</a>
</h3>
</div>
<div class="result-meta">
<div class="pill {% if 'anthropic' in r['source'] %}anthropic{% elif 'chatgpt' in r['source'] %}chatgpt{% else %}default{% endif %}"
onclick="filterByProvider('{% if 'anthropic' in r['source'] %}claude{% elif 'chatgpt' in r['source'] %}chatgpt{% endif %}')"
title="Click to filter by this provider">
{% if 'anthropic' in r['source'] %}🔵 Claude{% elif 'chatgpt' in r['source'] %}🟢 ChatGPT{% else %}{{r['source']}}{% endif %}
</div>
<div class="pill default" onclick="filterByRole('{% if r['role'] == 'user' %}user{% else %}assistant{% endif %}')" title="Click to filter by {% if r['role'] == 'user' %}human{% else %}assistant{% endif %} messages">
{% if r['role'] == 'user' %}👤 Human{% else %}🤖 Assistant{% endif %}
</div>
{% if r['date'] %}<div class="pill default" onclick="filterByDate('{{r['date']}}')" title="Click to filter by this date">{{r['date']}}</div>{% endif %}
</div>
<div class="result-content">
{{r['snip']|safe}}
<div class="expand-btn" onclick="toggleContext('{{r['id']}}', '{{r['conv_id']}}')" id="expand-btn-{{r['id']}}">🔍 Show context</div>
<div class="expand-context" id="context-{{r['id']}}" style="display: none;"></div>
</div>
<div class="result-actions">
<a href="#" onclick="openConversation('{{r['conv_id']}}'); return false;">
📖 View Full Conversation
</a>
{% if r['external_url'] %}
<a href="{{ r['external_url'] }}" target="_blank" rel="noopener noreferrer">
{% if 'chatgpt' in r['source'] %}🔗 Open in ChatGPT{% else %}🔗 Open in Claude{% endif %}
</a>
{% endif %}
</div>
<div class="result-footer">
<span>ID: {{r['id']}}</span>
<span>Conv: {{r['conv_id']}}</span>
</div>
</div>
{% endfor %}
{% if total_pages > 1 %}
<div style="display: flex; justify-content: center; align-items: center; gap: 16px; margin: 32px 0; padding: 24px;">
{% if has_prev %}
<a href="?q={{q|e}}&wild={{wild|int}}&provider={{provider}}&role={{role}}&date_from={{date_from}}&date_to={{date_to}}&sort={{sort}}&page={{page-1}}&per_page={{per_page}}"
style="padding: 12px 20px; background: #3b82f6; color: white; text-decoration: none; border-radius: 8px; font-weight: 500;">
← Previous
</a>
{% endif %}
<div style="display: flex; gap: 8px; align-items: center;">
{% for p in range(1, total_pages + 1) %}
{% if p == page %}
<span style="padding: 8px 12px; background: #1e40af; color: white; border-radius: 6px; font-weight: 600;">{{p}}</span>
{% elif p <= 3 or p >= total_pages - 2 or (p >= page - 1 and p <= page + 1) %}
<a href="?q={{q|e}}&wild={{wild|int}}&provider={{provider}}&role={{role}}&date_from={{date_from}}&date_to={{date_to}}&sort={{sort}}&page={{p}}&per_page={{per_page}}"
style="padding: 8px 12px; color: #374151; text-decoration: none; border-radius: 6px; transition: background 0.2s;">{{p}}</a>
{% elif p == 4 or p == total_pages - 3 %}
<span style="color: #9ca3af;">…</span>
{% endif %}
{% endfor %}
</div>
{% if has_next %}
<a href="?q={{q|e}}&wild={{wild|int}}&provider={{provider}}&role={{role}}&date_from={{date_from}}&date_to={{date_to}}&sort={{sort}}&page={{page+1}}&per_page={{per_page}}"
style="padding: 12px 20px; background: #3b82f6; color: white; text-decoration: none; border-radius: 8px; font-weight: 500;">
Next →
</a>
{% endif %}
</div>
<div style="text-align: center; margin: 16px 0;">
<select onchange="window.location.href='?q={{q|e}}&wild={{wild|int}}&provider={{provider}}&role={{role}}&date_from={{date_from}}&date_to={{date_to}}&sort={{sort}}&page=1&per_page=' + this.value"
style="padding: 8px 12px; border: 1px solid #d1d5db; border-radius: 6px;">
<option value="50" {% if per_page == 50 %}selected{% endif %}>50 per page</option>
<option value="100" {% if per_page == 100 %}selected{% endif %}>100 per page</option>
<option value="200" {% if per_page == 200 %}selected{% endif %}>200 per page</option>
<option value="500" {% if per_page == 500 %}selected{% endif %}>500 per page</option>
</select>
</div>
{% endif %}
{% endif %}
</div>
<div style="text-align: center; padding: 32px; border-top: 1px solid #f3f4f6; color: #9ca3af; font-size: 14px;">
Made with ❤️ in a time of war • Made in America • <a href="https://tom.ms" style="color: #6b7280; text-decoration: none;">tom.ms</a>
</div>
</div>
<script>
function filterByProvider(provider) {
// Update the form control
const providerSelect = document.querySelector('select[name="provider"]');
if (providerSelect) {
providerSelect.value = provider;
}
applyFilters();
}
function filterByRole(role) {
// Update the form control
const roleSelect = document.querySelector('select[name="role"]');
if (roleSelect) {
roleSelect.value = role;
}
applyFilters();
}
function filterByDate(date) {
// Update the form controls
const dateFromInput = document.querySelector('input[name="date_from"]');
const dateToInput = document.querySelector('input[name="date_to"]');
if (dateFromInput && dateToInput) {
dateFromInput.value = date;
dateToInput.value = date;
}
applyFilters();
}
function clearDateRange() {
const dateFromInput = document.querySelector('input[name="date_from"]');
const dateToInput = document.querySelector('input[name="date_to"]');
if (dateFromInput && dateToInput) {
dateFromInput.value = '';
dateToInput.value = '';
}
applyFilters();
}
async function toggleContext(messageId, convId) {
const contextDiv = document.getElementById(`context-${messageId}`);
const expandBtn = document.getElementById(`expand-btn-${messageId}`);
if (contextDiv.style.display === 'none') {
// Show context
expandBtn.textContent = '⏳ Loading context...';
try {
const response = await fetch(`/api/conversation/${convId}`);
const data = await response.json();
if (data.error) {
const suggestion = data.suggestion ? `<br><small style="color: #6b7280;">💡 ${data.suggestion}</small>` : '';
contextDiv.innerHTML = `<div style="color: #dc2626;">Error: ${data.error}${suggestion}</div>`;
} else {
let contextHtml = `<div style="font-weight: 600; margin-bottom: 12px;">📖 Full Conversation: ${data.title}</div>`;
data.messages.forEach((msg, index) => {
const isCurrentMessage = msg.content.includes(document.querySelector(`#context-${messageId}`).closest('.result').querySelector('.result-content mark')?.textContent || '');
const messageClass = isCurrentMessage ? 'context-message current' : `context-message ${msg.role}`;
contextHtml += `
<div class="${messageClass}">
<div class="context-header">
${msg.role === 'user' ? '👤' : '🤖'} ${msg.role.charAt(0).toUpperCase() + msg.role.slice(1)}
${msg.date ? `• ${msg.date}` : ''}
${isCurrentMessage ? ' • 📍 Current Result' : ''}
</div>
<div class="context-content">${msg.content.substring(0, 500)}${msg.content.length > 500 ? '...' : ''}</div>
</div>
`;
});
contextDiv.innerHTML = contextHtml;
}
} catch (error) {
contextDiv.innerHTML = `<div style="color: #dc2626;">Error loading context: ${error.message}<br><small style="color: #6b7280;">💡 Try reindexing your conversations if you see this error frequently.</small></div>`;
}
contextDiv.style.display = 'block';
expandBtn.textContent = '🔼 Hide context';
} else {
// Hide context
contextDiv.style.display = 'none';
expandBtn.textContent = '🔍 Show context';
}
}
function openConversation(convId) {
const newWindow = window.open(`/conv/${convId}`, '_blank');
// If popup blocker prevents opening, show an alert
if (!newWindow) {
alert('Please allow popups for this site to view full conversations. You can also use the "Show context" feature to see more of the conversation inline.');
}
}
function applyFilters() {
// Reset to first page when filters change
const form = document.querySelector('form');
if (form) {
// Add or update page parameter to reset to page 1
let pageInput = form.querySelector('input[name="page"]');
if (!pageInput) {
pageInput = document.createElement('input');
pageInput.type = 'hidden';
pageInput.name = 'page';
form.appendChild(pageInput);
}
pageInput.value = '1';
form.submit();
}
}
</script>
"""
ADMIN_TEMPLATE = """
<!doctype html>
<title>Admin - Inchive</title>
<style>
* { box-sizing: border-box; }
body {
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
margin: 0; padding: 0;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
min-height: 100vh;
line-height: 1.6;
}
.container {
max-width: 900px; margin: 0 auto; background: white;
min-height: 100vh; box-shadow: 0 0 50px rgba(0,0,0,0.1);
}
.header {
background: linear-gradient(135deg, #1e3a8a 0%, #3730a3 100%);
color: white; padding: 24px 32px;
box-shadow: 0 4px 20px rgba(0,0,0,0.1);
}
.header h1 { margin: 0; font-size: 28px; font-weight: 700; }
.header .subtitle { opacity: 0.9; font-size: 16px; margin-top: 4px; }
.content { padding: 32px; }
.admin-section {
background: #f8fafc; padding: 32px; border-radius: 16px;
margin-bottom: 32px; box-shadow: 0 2px 8px rgba(0,0,0,0.04);
}
.admin-section h2 { margin: 0 0 20px 0; color: #1f2937; font-size: 24px; }
.admin-section p { color: #6b7280; margin-bottom: 24px; }
.reindex-form { display: flex; gap: 12px; align-items: flex-start; flex-wrap: wrap; }
.reindex-input {
flex: 1; min-width: 400px; padding: 16px 20px;
border: 2px solid #e2e8f0; border-radius: 12px; font-size: 16px;
transition: all 0.2s;
}
.reindex-input:focus {
outline: none; border-color: #3b82f6;
box-shadow: 0 0 0 4px rgba(59,130,246,0.1);
}
.reindex-btn {
padding: 16px 32px; background: #10b981; color: white;
border: none; border-radius: 12px; font-weight: 600; cursor: pointer;
transition: all 0.2s; font-size: 16px;
}
.reindex-btn:hover { background: #059669; transform: translateY(-1px); }
.back-link {
display: inline-flex; align-items: center; gap: 8px; color: #6b7280;
text-decoration: none; font-weight: 500; margin-bottom: 32px;
transition: color 0.2s;
}
.back-link:hover { color: #3b82f6; }
.flash-messages{ margin: 24px 0; }
.flash{
padding: 16px 20px; border-radius: 12px; margin: 12px 0;
font-weight: 500; display: flex; align-items: center; gap: 12px;
}
.flash.success{ background: #d1fae5; color: #065f46; border-left: 4px solid #10b981; }
.flash.error{ background: #fee2e2; color: #991b1b; border-left: 4px solid #ef4444; }
.flash.warning{ background: #fef3c7; color: #92400e; border-left: 4px solid #f59e0b; }
.help-text {
background: #eff6ff; border: 1px solid #bfdbfe; padding: 16px;
border-radius: 8px; margin-top: 16px; font-size: 14px; color: #1e40af;
}
</style>
<meta name="referrer" content="no-referrer"/>
<div class="container">
<div class="header">
<div style="display: flex; justify-content: space-between; align-items: center;">
<div>
<h1>⚙️ Admin Panel</h1>
<div class="subtitle">Manage your search index</div>
</div>
</div>
</div>
<div class="content">
<a href="{{ url_for('home') }}" class="back-link">
← Back to Search
</a>
<div class="flash-messages">
{% with messages = get_flashed_messages() %}
{% if messages %}
{% for message in messages %}
<div class="flash {% if '✅' in message %}success{% elif '❌' in message %}error{% else %}warning{% endif %}">{{ message }}</div>
{% endfor %}
{% endif %}
{% endwith %}
</div>
<div class="admin-section">
<h2>🔄 Reindex Data</h2>
<p>Update your search index with new or modified conversation exports. You can index single or multiple accounts by providing comma-separated paths.</p>
<form method="POST" action="{{ url_for('reindex') }}" class="reindex-form">
<input type="text" name="export" value="{{export_default|e}}"
placeholder="Path to export folder (or comma-separated paths for multiple accounts)"
class="reindex-input" required/>
<button type="submit" class="reindex-btn">Reindex</button>
</form>
<div class="help-text">
<strong>💡 Tips:</strong><br>
• Single account: <code>/path/to/anthropic-data</code><br>
• Multiple accounts: <code>/path/account1,/path/account2,/path/account3</code><br>
• Each folder should contain: conversations.json, projects.json, users.json
</div>
</div>
<div class="admin-section">
<h2>📊 Conversation Analytics</h2>
<div id="analyticsContent">
<div style="text-align: center; padding: 20px; color: #6b7280;">
<button onclick="loadAnalytics()" style="padding: 12px 24px; background: #3b82f6; color: white; border: none; border-radius: 8px; cursor: pointer; font-weight: 600;">
📈 Load Analytics Dashboard
</button>
</div>
</div>
</div>
<div class="admin-section">
<h2>📊 Database Info</h2>
<p>Current database location: <code>{{db_path}}</code></p>
<p>To completely rebuild the index, delete the database file and reindex your data.</p>
</div>
<div class="admin-section">
<h2>📞 Support & Contact</h2>
<p>Need help or found a bug? Visit the project repository for documentation, issues, and updates.</p>
<p>
<a href="https://github.com/inchive/inchive" target="_blank"
style="display: inline-flex; align-items: center; gap: 8px; padding: 12px 20px; background: #1f2937; color: white; text-decoration: none; border-radius: 8px; font-weight: 500; transition: background 0.2s;">
<span>📦</span> View on GitHub
</a>
</p>
</div>
</div>
<div style="text-align: center; padding: 32px; border-top: 1px solid #f3f4f6; color: #9ca3af; font-size: 14px;">
Made with ❤️ in a time of war • Made in America • <a href="https://tom.ms" style="color: #6b7280; text-decoration: none;">tom.ms</a>
</div>
</div>
"""
SQL = """
SELECT d.id, d.conv_id, d.title, d.role, d.date, d.source,
snippet(docs_fts, 0, '<mark>', '</mark>', ' … ', 12) as snip
FROM docs_fts
JOIN docs d ON d.rowid = docs_fts.rowid
WHERE docs_fts MATCH ?
ORDER BY rank
<!-- Conversation Shelf -->
<div class="shelf-overlay" onclick="closeConversation()"></div>
<div class="conversation-shelf" id="conversationShelf">
<div class="shelf-header">
<h2 id="shelfTitle">Conversation</h2>
<button class="shelf-close" onclick="closeConversation()">✕</button>
</div>
<div class="shelf-content" id="shelfContent">
<div style="text-align: center; color: #6b7280; padding: 40px;">
Select a conversation to view it here
</div>
</div>
</div>
"""
def make_app(db_path: str):
app = Flask(__name__)
app.secret_key = os.environ.get("FLASK_SECRET", "dev")
db_holder = {"conn": sqlite3.connect(db_path, check_same_thread=False), "db_path": db_path}
db_holder["conn"].row_factory = sqlite3.Row
claude_url_template = os.environ.get("CLAUDE_URL_TEMPLATE", "https://claude.ai/chat/{conv_id}")
@app.route("/", methods=["GET"])
def home():
q = request.args.get("q", "").strip()
wild = request.args.get("wild", "1") == "1"
date_from = request.args.get("date_from") or None
date_to = request.args.get("date_to") or None
sort = request.args.get("sort") or "rank"
provider_filter = request.args.get("provider", "")
role_filter = request.args.get("role", "")
page = int(request.args.get("page", "1"))
per_page = int(request.args.get("per_page", "100"))
# Limit per_page to reasonable values
per_page = min(max(per_page, 10), 500)
offset = (page - 1) * per_page
rows = None
total_count = 0
def expand_tokens(txt):
parts = [p for p in txt.replace('\u2013', ' ').replace('\u2014', ' ').split() if p]
expanded = []
for p in parts:
if any(op in p for op in ['"', "'", "AND", "OR", "NOT", "NEAR", ":"]):
expanded.append(p)
elif len(p) > 2:
# Quote tokens with special chars to prevent FTS errors
if '-' in p or '+' in p:
expanded.append('"' + p + '"*')
else:
expanded.append(p + '*')
else:
expanded.append(p)
return " ".join(expanded)
# Easter egg for precision tom
if q.lower().strip() == "precision tom":
enriched = [{
"id": "easter-egg-1",
"conv_id": "precision-tom-2025",
"title": "🎯 Precision Tom Easter Egg",
"role": "system",
"date": "2025-01-24",
"source": "easter.egg",
"snip": "You found the <mark>precision tom</mark> easter egg! 🎉 This search tool was built with precision, care, and attention to detail. Thanks for exploring!",
"external_url": None
}]
return render_template_string(
TEMPLATE,
q=q,
rows=enriched,
wild=wild,
date_from=date_from or "",
date_to=date_to or "",
sort=sort,
page=1,
per_page=100,
total_count=1,
total_pages=1,
has_prev=False,
has_next=False,
export_default=export_default,
)
if q:
base_sql = (
"SELECT d.id, d.conv_id, d.title, d.role, d.date, d.source, "
"snippet(docs_fts, 0, '<mark>', '</mark>', ' … ', 12) as snip "
"FROM docs_fts JOIN docs d ON d.rowid = docs_fts.rowid "
"WHERE docs_fts MATCH ?"
)
params = []
q_try = expand_tokens(q) if wild else q
params.append(q_try)
if date_from:
base_sql += " AND (d.date IS NOT NULL AND d.date >= ?)"
params.append(date_from)
if date_to:
base_sql += " AND (d.date IS NOT NULL AND d.date <= ?)"
params.append(date_to)
if provider_filter:
if provider_filter == "claude":
base_sql += " AND d.source LIKE '%anthropic%'"
elif provider_filter == "chatgpt":
base_sql += " AND d.source LIKE '%chatgpt%'"
if role_filter:
if role_filter == "assistant":
base_sql += " AND (d.role = 'assistant' OR d.role = 'system')"
else:
base_sql += " AND d.role = ?"
params.append(role_filter)
# Get total count first
count_sql = base_sql.replace(
"SELECT d.id, d.conv_id, d.title, d.role, d.date, d.source, snippet(docs_fts, 0, '<mark>', '</mark>', ' … ', 12) as snip",
"SELECT COUNT(*)"
)
total_count = db_holder["conn"].execute(count_sql, tuple(params)).fetchone()[0]
# Add sorting and pagination
if sort == "newest":
base_sql += " ORDER BY (d.date IS NULL), d.date DESC"
elif sort == "oldest":
base_sql += " ORDER BY (d.date IS NULL), d.date ASC"
else:
base_sql += " ORDER BY rank"
base_sql += f" LIMIT {per_page} OFFSET {offset}"
rows = db_holder["conn"].execute(base_sql, tuple(params)).fetchall()
# Fallback with expanded tokens if no results
if not rows and not wild and offset == 0:
q_try = expand_tokens(q)
params[0] = q_try
# Recalculate count with expanded query
total_count = db_holder["conn"].execute(count_sql, tuple(params)).fetchone()[0]
rows = db_holder["conn"].execute(base_sql, tuple(params)).fetchall()
export_default = os.path.abspath(os.path.join(os.path.dirname(__file__), 'files'))
def looks_like_uuid(u: str) -> bool:
try:
return bool(re.match(r"^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$", u or ""))
except Exception:
return False
def safe_url_format(template: str, conv_id: str, source: str = "") -> str:
try:
# Handle ChatGPT links
if "chatgpt" in source.lower():
return f"https://chatgpt.com/c/{conv_id}"
# Handle Claude links with template
if "{conv_id}" in template:
return template.replace("{conv_id}", conv_id)
elif "%7Bconv_id%7D" in template:
return template.replace("%7Bconv_id%7D", conv_id)
else:
# If no placeholder, just append the conv_id
return f"{template.rstrip('/')}/{conv_id}"
except Exception:
return None
enriched = None if rows is None else [
{
"id": r["id"],
"conv_id": r["conv_id"],
"title": r["title"],
"role": r["role"],
"date": r["date"],
"source": r["source"],
"snip": r["snip"],
"external_url": (
safe_url_format(claude_url_template, r["conv_id"], r["source"])
if (r["source"] and (
("anthropic" in r["source"] and looks_like_uuid(r["conv_id"])) or
("chatgpt" in r["source"] and r["conv_id"])
)) else None
),
} for r in rows
]
# Calculate pagination info
total_pages = (total_count + per_page - 1) // per_page if total_count > 0 else 0
has_prev = page > 1
has_next = page < total_pages
return render_template_string(
TEMPLATE,
q=q,
rows=enriched,
wild=wild,
date_from=date_from or "",
date_to=date_to or "",
sort=sort,
provider=provider_filter,
role=role_filter,
page=page,
per_page=per_page,
total_count=total_count,
total_pages=total_pages,
has_prev=has_prev,
has_next=has_next,
export_default=export_default,
)
@app.route("/reindex", methods=["POST"])
def reindex():
export = request.form.get("export", "").strip()
if not export:
flash("❌ Please provide a path to your export directory.")
return redirect(url_for('home'))
if not os.path.exists(export):
flash(f"❌ Directory not found: {export}")
return redirect(url_for('home'))
if not os.path.isdir(export):
flash(f"❌ Path is not a directory: {export}")
return redirect(url_for('home'))
# Check for required files
required_files = ["conversations.json", "projects.json", "users.json"]
missing_files = [f for f in required_files if not os.path.exists(os.path.join(export, f))]
if missing_files:
flash(f"⚠️ Missing files in export directory: {', '.join(missing_files)}")
# Continue anyway - some files might be optional
out_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', 'index'))
try:
from pathlib import Path
from indexer import build_index_multi
exports = [e.strip() for e in export.split(',') if e.strip()]
srcs = []
for e in exports:
p = Path(e)
if p.is_dir():
srcs.append((p.name or "default", p))
if not srcs:
raise RuntimeError("No valid export directories.")
db_path = build_index_multi(srcs, Path(out_dir))
except Exception as e:
flash(f"❌ Reindex failed: {str(e)[:100]}...")
return redirect(url_for('home'))
try:
db_holder["conn"].close()
db_holder["conn"] = sqlite3.connect(str(db_path), check_same_thread=False)
db_holder["conn"].row_factory = sqlite3.Row
db_holder["db_path"] = str(db_path)
flash("✅ Reindex complete! Database updated successfully.")
except Exception as e:
flash(f"⚠️ Reindex complete, but failed to reload database: {str(e)[:50]}..." )
return redirect(url_for('admin'))
@app.route("/admin", methods=["GET"])
def admin():
export_default = os.path.abspath(os.path.join(os.path.dirname(__file__), 'files'))
return render_template_string(
ADMIN_TEMPLATE,
export_default=export_default,
db_path=db_holder["db_path"]
)
@app.route("/api/analytics")
def api_analytics():
"""Analytics API endpoint"""
try:
from analytics import ConversationAnalytics
analytics = ConversationAnalytics(db_holder["db_path"])
overview = analytics.get_overview_stats()
temporal = analytics.get_temporal_patterns()
return jsonify({
'overview': overview,
'temporal': temporal,
'status': 'success'
})
except Exception as e:
return jsonify({
'error': str(e),
'status': 'error'
}), 500
@app.route('/favicon.ico')
def favicon():
return ("", 204)
DETAIL_TEMPLATE = """
<!doctype html>
<title>Conversation {{conv_id}}</title>
<style>
body { font-family: system-ui, -apple-system, Segoe UI, Roboto, sans-serif; margin: 24px; }
.topbar{ display:flex; align-items:center; gap:12px; justify-content:space-between; }
.pill{ background:#eef2ff; color:#374151; border:1px solid #d1d5db; padding:2px 8px; border-radius:999px; font-size:0.8em; }
.muted{ color:#777; }
.msg{ border:1px solid #e5e7eb; border-radius:10px; padding:12px; margin:12px 0; background:#fff; }
.role{ font-weight:600; margin-bottom:6px; display:flex; gap:8px; align-items:center; }
.content{ white-space:pre-wrap; line-height:1.4; }
.actions a{ color:#374151; }
</style>
<div class="topbar">
<div>
<h2 style="margin:0;">{{title}}</h2>
<div class="muted">Conversation <code>{{conv_id}}</code></div>
</div>
<div class="actions">
{% if external_url %}<a href="{{external_url}}" target="_blank" rel="noopener noreferrer">Open in Claude ↗</a>{% endif %}
|
<a href="{{ url_for('home', q='conv_id:"' ~ conv_id ~ '"') }}">Back to search</a>
</div>
</div>
{% if first_date %}
<div class="pill">First message {{first_date}}</div>
{% endif %}
{% for m in messages %}
<div class="msg">
<div class="role">{{m['role']}} {% if m['date'] %}<span class="pill">{{m['date']}}</span>{% endif %}</div>