File size: 30,641 Bytes
928f123
 
ca3e112
 
928f123
 
 
4572f9c
928f123
 
 
 
 
 
ac6931b
928f123
 
 
 
 
 
 
ac6931b
16272b2
928f123
 
ca3e112
4572f9c
 
 
 
 
 
 
 
 
928f123
 
9ddd488
 
928f123
ca3e112
928f123
 
 
 
 
 
ca3e112
125abbd
ca3e112
4572f9c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
64cc57f
4572f9c
ca3e112
928f123
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4572f9c
 
 
125abbd
4572f9c
 
 
 
 
 
6f20169
4572f9c
 
 
 
 
ca3e112
4572f9c
 
 
 
6f20169
4572f9c
 
 
ca3e112
 
4572f9c
 
6f20169
4572f9c
 
 
ca3e112
4572f9c
ca3e112
 
 
 
 
e45dc88
deb91ab
b080e86
 
 
 
deb91ab
e45dc88
ca3e112
928f123
ca3e112
 
928f123
ca3e112
 
928f123
ca3e112
 
 
928f123
ca3e112
 
928f123
ca3e112
 
928f123
ca3e112
 
 
928f123
ca3e112
 
928f123
ca3e112
 
928f123
ca3e112
 
 
 
ffff3d1
 
 
 
 
 
 
 
 
 
 
 
 
125abbd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9381962
 
 
0c9dfe9
 
 
 
 
 
 
125abbd
4572f9c
 
6f20169
125abbd
 
 
 
 
928f123
ba0d9a2
1c5a53b
35b696c
de51e8b
4572f9c
9ddd488
 
 
4572f9c
1c5a53b
64cc57f
1c5a53b
 
 
c53af21
1c5a53b
 
 
928f123
1c5a53b
 
 
928f123
 
 
 
 
 
 
 
 
 
 
 
deee37e
b080e86
 
 
 
 
 
 
9ddd488
66f4eb1
928f123
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4572f9c
928f123
ca3e112
 
ba0d9a2
 
 
 
 
4572f9c
1c5a53b
4572f9c
1c5a53b
 
 
4572f9c
1c5a53b
4572f9c
1c5a53b
 
 
4572f9c
1c5a53b
4572f9c
1c5a53b
 
 
4572f9c
928f123
4572f9c
928f123
 
 
4572f9c
928f123
4572f9c
928f123
 
 
4572f9c
928f123
4572f9c
928f123
 
 
4572f9c
928f123
4572f9c
928f123
 
 
4572f9c
928f123
4572f9c
928f123
 
 
4572f9c
928f123
4572f9c
928f123
 
 
4572f9c
928f123
4572f9c
928f123
 
 
4572f9c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
16ca275
4572f9c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a95339f
4572f9c
a95339f
16ca275
a95339f
 
 
 
 
 
 
 
 
 
 
 
 
 
125abbd
ca3e112
4572f9c
ca3e112
16ca275
ca3e112
 
 
 
 
 
 
 
 
 
 
 
 
 
125abbd
 
928f123
 
 
 
16272b2
125abbd
 
 
ffff3d1
 
 
 
 
 
 
 
 
 
928f123
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import os
import re
import copy
import datasets
import pandas as pd
import gradio as gr

from collections import defaultdict
from datetime import datetime, timedelta
from datasets import Dataset
from huggingface_hub import HfApi
from huggingface_hub import create_repo
from huggingface_hub.utils import HfHubHTTPError

import utils
from paper.download import (
    download_pdf_from_arxiv,
    get_papers_from_hf_daily_papers,
    get_papers_from_arxiv_ids
)
from paper.parser import extract_text_and_figures
from gen.gemini import get_basic_qa, get_deep_qa
from constants.styles import STYLE
from constants.js import UPDATE_SEARCH_RESULTS, UPDATE_IF_TYPE

from apscheduler.schedulers.background import BackgroundScheduler

def count_nans(row):
    count = 0

    for _, (k, v) in enumerate(data.items()):
        if v is None:
            count = count + 1

    return count
    
gemini_api_key = os.getenv("GEMINI_API_KEY")
hf_token = os.getenv("HF_TOKEN")
dataset_repo_id = os.getenv("SOURCE_DATA_REPO_ID") # "chansung/auto-paper-qa2"
request_arxiv_repo_id = os.getenv("REQUEST_DATA_REPO_ID") # "chansung/requested-arxiv-ids-3"

ds = datasets.load_dataset(dataset_repo_id)
request_ds = datasets.load_dataset(request_arxiv_repo_id)
requested_arxiv_ids = []
for request_d in request_ds['train']:
    arxiv_ids = request_d['Requested arXiv IDs']
    requested_arxiv_ids = requested_arxiv_ids + arxiv_ids
requested_arxiv_ids_df = pd.DataFrame({'Requested arXiv IDs': requested_arxiv_ids})

title2qna = {}
date2qna = {}
date_dict = defaultdict(lambda: defaultdict(lambda: defaultdict(list)))

for data in ds["train"]:
    date = data["target_date"].strftime("%Y-%m-%d")

    if date in date2qna:
        papers = copy.deepcopy(date2qna[date])
        for paper in papers:
            if paper["title"] == data["title"]:
                if count_nans(paper) > count_nans(data):
                    date2qna[date].remove(paper)
        
        date2qna[date].append(data)
        del papers
    else:
        date2qna[date] = [data]

for date in date2qna:
    year, month, day = date.split("-")
    papers = date2qna[date]
    for paper in papers:
        title2qna[paper["title"]] = paper
        date_dict[year][month][day].append(paper)

titles = title2qna.keys()

sorted_dates = sorted(date2qna.keys())

sorted_year = sorted(date_dict.keys())
last_year = sorted_year[-1]
sorted_month = sorted(date_dict[last_year].keys())
last_month = sorted_month[-1]
sorted_day = sorted(date_dict[last_year][last_month].keys())
last_day = sorted_day[-1]
last_papers = date_dict[last_year][last_month][last_day]
selected_paper = last_papers[0]

def filter_function(example, ids):
    ids_e = example['Requested arXiv IDs']
    for iid in ids:
        if iid in ids_e:
            ids_e.remove(iid)
            example['Requested arXiv IDs'] = ids_e

    print(example)
    return example

def process_arxiv_ids(gemini_api, hf_repo_id, req_hf_repo_id, hf_token, how_many=10):
    arxiv_ids = []

    ds1 = datasets.load_dataset(req_hf_repo_id)
    for d in ds1['train']:
        req_arxiv_ids = d['Requested arXiv IDs']
        if len(req_arxiv_ids) > 0 and req_arxiv_ids[0] != "top":
            arxiv_ids = arxiv_ids + req_arxiv_ids

    arxiv_ids = arxiv_ids[:how_many]

    if arxiv_ids is not None and len(arxiv_ids) > 0:
        print(f"1. Get metadata for the papers [{arxiv_ids}]")
        papers = get_papers_from_arxiv_ids(arxiv_ids)
        print("...DONE")
        
        print("2. Generating QAs for the paper")
        for paper in papers:
            try:
                title = paper['title']
                target_date = paper['target_date']
                abstract = paper['paper']['summary']
                arxiv_id = paper['paper']['id']
                authors = paper['paper']['authors']

                print(f"...PROCESSING ON[{arxiv_id}, {title}]")
                print(f"......Downloading the paper PDF")
                filename = download_pdf_from_arxiv(arxiv_id)
                print(f"......DONE")

                print(f"......Extracting text and figures")
                texts, figures = extract_text_and_figures(filename)
                text =' '.join(texts)
                print(f"......DONE")

                print(f"......Generating the seed(basic) QAs")
                qnas = get_basic_qa(text, gemini_api_key=gemini_api, trucate=30000)
                qnas['title'] = title
                qnas['abstract'] = abstract
                qnas['authors'] = ','.join(authors)
                qnas['arxiv_id'] = arxiv_id
                qnas['target_date'] = target_date
                qnas['full_text'] = text
                print(f"......DONE")

                print(f"......Generating the follow-up QAs")
                qnas = get_deep_qa(text, qnas, gemini_api_key=gemini_api, trucate=30000)
                del qnas["qna"]
                print(f"......DONE")

                print(f"......Exporting to HF Dataset repo at [{hf_repo_id}]")
                utils.push_to_hf_hub(qnas, hf_repo_id, hf_token)
                print(f"......DONE")

                print(f"......Updating request arXiv HF Dataset repo at [{req_hf_repo_id}]")
                ds1 = ds1['train'].map(
                    lambda example: filter_function(example, [arxiv_id])
                ).filter(
                    lambda example: len(example['Requested arXiv IDs']) > 0
                )
                ds1.push_to_hub(req_hf_repo_id, token=hf_token)
                            
                print(f"......DONE")
            except Exception as e:
                print(f".......failed due to exception {e}")
                continue

        HfApi(token=hf_token).restart_space(
            repo_id="chansung/paper_qa", token=hf_token
        )

def push_to_hf_hub(
    df, repo_id, token, append=True
):
    exist = False
    ds = Dataset.from_pandas(df)

    try:
        create_repo(request_arxiv_repo_id, repo_type="dataset", token=hf_token)
    except HfHubHTTPError as e:
        exist = True
        
    if exist and append:
        existing_ds = datasets.load_dataset(repo_id)
        ds = datasets.concatenate_datasets([existing_ds['train'], ds])

    ds.push_to_hub(repo_id, token=token)

def _filter_duplicate_arxiv_ids(arxiv_ids_to_be_added):
    ds1 = datasets.load_dataset("chansung/requested-arxiv-ids-3")
    ds2 = datasets.load_dataset("chansung/auto-paper-qa2")

    unique_arxiv_ids = set()

    for d in ds1['train']:
        arxiv_ids = d['Requested arXiv IDs']
        unique_arxiv_ids = set(list(unique_arxiv_ids) + arxiv_ids)

    for d in ds2['train']:
        arxiv_id = d['arxiv_id']
        unique_arxiv_ids.add(arxiv_id)

    return list(set(arxiv_ids_to_be_added) - unique_arxiv_ids)

def _is_arxiv_id_valid(arxiv_id):
  pattern = r"^\d{4}\.\d{5}$" 
  return bool(re.match(pattern, arxiv_id))

def _get_valid_arxiv_ids(arxiv_ids_str):
    valid_arxiv_ids = []
    invalid_arxiv_ids = []
    
    for arxiv_id in arxiv_ids_str.split(","):
        arxiv_id = arxiv_id.strip()
        if _is_arxiv_id_valid(arxiv_id):
           valid_arxiv_ids.append(arxiv_id)
        else:
            invalid_arxiv_ids.append(arxiv_id)

    return valid_arxiv_ids, invalid_arxiv_ids

def add_arxiv_ids_to_queue(queue, arxiv_ids_str):
    print(0)
    valid_arxiv_ids, invalid_arxiv_ids = _get_valid_arxiv_ids(arxiv_ids_str)
    print("01")
    
    if len(invalid_arxiv_ids) > 0: 
        gr.Warning(f"found invalid arXiv ids as in {invalid_arxiv_ids}")

    if len(valid_arxiv_ids) > 0:
        valid_arxiv_ids = _filter_duplicate_arxiv_ids(valid_arxiv_ids)

        if len(valid_arxiv_ids) > 0:
            valid_arxiv_ids = [[arxiv_id] for arxiv_id in valid_arxiv_ids]
            gr.Warning(f"Processing on [{valid_arxiv_ids}]. Other requested arXiv IDs not found on this list should be already processed or being processed...")
            valid_arxiv_ids = pd.DataFrame({'Requested arXiv IDs': valid_arxiv_ids})
            queue = pd.concat([queue, valid_arxiv_ids])
            queue.reset_index(drop=True)

            push_to_hf_hub(valid_arxiv_ids, request_arxiv_repo_id, hf_token)
        else:
            gr.Warning(f"All requested arXiv IDs are already processed or being processed...")
    else:
        gr.Warning(f"No valid arXiv IDs found...")

    return (
        queue, gr.Textbox("")
    )

def get_paper_by_year(y):
    m = sorted(date_dict[y].keys())
    last_m = m[-1]
    d = sorted(date_dict[y][last_m].keys())
    last_d = d[-1]
    papers = [paper["title"] for paper in date_dict[y][last_m][last_d]]
    papers = list(set(papers))
    return (
        gr.Dropdown(choices=m, value=last_m),
        gr.Dropdown(choices=d, value=last_d),
        gr.Dropdown(choices=papers, value=papers[0])
    )

def get_paper_by_month(y, m):
    d = sorted(date_dict[y][m].keys())
    last_d = d[-1]
    papers = [paper["title"] for paper in date_dict[y][m][last_d]]
    papers = list(set(papers))
    return (
        gr.Dropdown(choices=d, value=last_d),
        gr.Dropdown(choices=papers, value=papers[0])
    )

def get_paper_by_day(y, m, d):
    papers = [paper["title"] for paper in date_dict[y][m][d]]
    papers = list(set(papers))
    return gr.Dropdown(choices=papers, value=papers[0])

def set_paper(y, m, d, paper_title):
    selected_paper = None
    for paper in date_dict[y][m][d]:
        if paper["title"] == paper_title:
            selected_paper = paper
            break

    return (
        gr.Markdown(f"# {selected_paper['title']}"), 
        gr.Markdown(
            "[![arXiv](https://img.shields.io/badge/arXiv-%s-b31b1b.svg)](https://arxiv.org/abs/%s)" % (selected_paper['arxiv_id'], selected_paper['arxiv_id'])
        ),
        gr.Markdown(
            "[![Paper page](https://huggingface.co/datasets/huggingface/badges/resolve/main/paper-page-md.svg)](https://huggingface.co/papers/%s)" % selected_paper['arxiv_id']
        ),
        gr.Markdown(selected_paper["summary"]),

        gr.Markdown(f"### πŸ™‹ {selected_paper['0_question']}"), 
        gr.Markdown(f"β†ͺ **(ELI5)** {selected_paper['0_answers:eli5']}"), 
        gr.Markdown(f"β†ͺ **(Technical)** {selected_paper['0_answers:expert']}"),
        gr.Markdown(f"### πŸ™‹πŸ™‹ {selected_paper['0_additional_depth_q:follow up question']}"),
        gr.Markdown(f"β†ͺ **(ELI5)** {selected_paper['0_additional_depth_q:answers:eli5']}"), 
        gr.Markdown(f"β†ͺ **(Technical)** {selected_paper['0_additional_depth_q:answers:expert']}"),
        gr.Markdown(f"### πŸ™‹πŸ™‹ {selected_paper['0_additional_breath_q:follow up question']}"), 
        gr.Markdown(f"β†ͺ **(ELI5)** {selected_paper['0_additional_breath_q:answers:eli5']}"), 
        gr.Markdown(f"β†ͺ **(Technical)** {selected_paper['0_additional_breath_q:answers:expert']}"),

        gr.Markdown(f"### πŸ™‹ {selected_paper['1_question']}"), 
        gr.Markdown(f"β†ͺ **(ELI5)** {selected_paper['1_answers:eli5']}"), 
        gr.Markdown(f"β†ͺ **(Technical)** {selected_paper['1_answers:expert']}"),
        gr.Markdown(f"### πŸ™‹πŸ™‹ {selected_paper['1_additional_depth_q:follow up question']}"), 
        gr.Markdown(f"β†ͺ **(ELI5)** {selected_paper['1_additional_depth_q:answers:eli5']}"), 
        gr.Markdown(f"β†ͺ **(Technical)** {selected_paper['1_additional_depth_q:answers:expert']}"),
        gr.Markdown(f"### πŸ™‹πŸ™‹ {selected_paper['1_additional_breath_q:follow up question']}"), 
        gr.Markdown(f"β†ͺ **(ELI5)** {selected_paper['1_additional_breath_q:answers:eli5']}"), 
        gr.Markdown(f"β†ͺ **(Technical)** {selected_paper['1_additional_breath_q:answers:expert']}"),

        gr.Markdown(f"### πŸ™‹ {selected_paper['2_question']}"), 
        gr.Markdown(f"β†ͺ **(ELI5)** {selected_paper['2_answers:eli5']}"), 
        gr.Markdown(f"β†ͺ **(Technical)** {selected_paper['2_answers:expert']}"),
        gr.Markdown(f"### πŸ™‹πŸ™‹ {selected_paper['2_additional_depth_q:follow up question']}"), 
        gr.Markdown(f"β†ͺ **(ELI5)** {selected_paper['2_additional_depth_q:answers:eli5']}"), 
        gr.Markdown(f"β†ͺ **(Technical)** {selected_paper['2_additional_depth_q:answers:expert']}"),
        gr.Markdown(f"### πŸ™‹πŸ™‹ {selected_paper['2_additional_breath_q:follow up question']}"), 
        gr.Markdown(f"β†ͺ **(ELI5)** {selected_paper['2_additional_breath_q:answers:eli5']}"), 
        gr.Markdown(f"β†ͺ **(Technical)** {selected_paper['2_additional_breath_q:answers:expert']}"),
    )

def change_exp_type(exp_type):
    if exp_type == "ELI5":
        return (
            gr.Markdown(visible=True), gr.Markdown(visible=False), gr.Markdown(visible=True), gr.Markdown(visible=False), gr.Markdown(visible=True), gr.Markdown(visible=False),
            gr.Markdown(visible=True), gr.Markdown(visible=False), gr.Markdown(visible=True), gr.Markdown(visible=False), gr.Markdown(visible=True), gr.Markdown(visible=False),
            gr.Markdown(visible=True), gr.Markdown(visible=False), gr.Markdown(visible=True), gr.Markdown(visible=False), gr.Markdown(visible=True), gr.Markdown(visible=False),
        )
    else:
        return (
            gr.Markdown(visible=False), gr.Markdown(visible=True), gr.Markdown(visible=False), gr.Markdown(visible=True), gr.Markdown(visible=False), gr.Markdown(visible=True),
            gr.Markdown(visible=False), gr.Markdown(visible=True), gr.Markdown(visible=False), gr.Markdown(visible=True), gr.Markdown(visible=False), gr.Markdown(visible=True),
            gr.Markdown(visible=False), gr.Markdown(visible=True), gr.Markdown(visible=False), gr.Markdown(visible=True), gr.Markdown(visible=False), gr.Markdown(visible=True),
        )        

def search(search_in, max_results=3):
    results = []

    for title in titles:
        if len(results) > 3:
            break
        else:
            if search_in in title:
                results.append(title)

    return (
        gr.Textbox(
            visible=True if len(results) > 0 else False,
            value=results[0] if len(results) > 0 else ""
        ),
        gr.Textbox(
            visible=True if len(results) > 1 else False,
            value=results[1] if len(results) > 1 else ""
        ),
        gr.Textbox(
            visible=True if len(results) > 2 else False,
            value=results[2] if len(results) > 2 else ""
        )
    )

def set_date(title):
    for _, (year, months) in enumerate(date_dict.items()):
        for _, (month, days) in enumerate(months.items()):
            for _, (day, papers) in enumerate(days.items()):
                for paper in papers:
                    if paper['title'] == title:
                        return (
                            gr.Dropdown(value=year),
                            gr.Dropdown(choices=sorted(months), value=month),
                            gr.Dropdown(choices=sorted(days), value=day),
                        )

def set_papers(y, m, d, title):
    papers = [paper["title"] for paper in date_dict[y][m][d]]
    papers = list(set(papers))
    return (
        gr.Dropdown(choices=papers, value=title),
        gr.Textbox("")
    )

with gr.Blocks(css=STYLE, theme=gr.themes.Soft()) as demo:
    gr.Markdown("# Let's explore papers with auto generated Q&As")
    
    with gr.Column(elem_id="control-panel", elem_classes=["group"]):
        with gr.Column():
            with gr.Row():
                year_dd = gr.Dropdown(sorted_year, value=last_year, label="Year", interactive=True, filterable=False)    
                month_dd = gr.Dropdown(sorted_month, value=last_month, label="Month", interactive=True, filterable=False)    
                day_dd = gr.Dropdown(sorted_day, value=last_day, label="Day", interactive=True, filterable=False)
                
            papers_dd = gr.Dropdown(
                list(set([paper["title"] for paper in last_papers])),
                value=selected_paper["title"],
                label="Select paper title", 
                interactive=True,
                filterable=False
            )

        with gr.Column(elem_classes=["no-gap"]):
            search_in = gr.Textbox("", placeholder="Enter keywords to search...", elem_classes=["textbox-no-label"])
            search_r1 = gr.Button(visible=False, elem_id="search_r1", elem_classes=["no-radius"])
            search_r2 = gr.Button(visible=False, elem_id="search_r2", elem_classes=["no-radius"])
            search_r3 = gr.Button(visible=False, elem_id="search_r3", elem_classes=["no-radius"])
            search_r4 = gr.Button(visible=False, elem_id="search_r4", elem_classes=["no-radius"])
            search_r5 = gr.Button(visible=False, elem_id="search_r5", elem_classes=["no-radius"])
            search_r6 = gr.Button(visible=False, elem_id="search_r6", elem_classes=["no-radius"])
            search_r7 = gr.Button(visible=False, elem_id="search_r7", elem_classes=["no-radius"])
            search_r8 = gr.Button(visible=False, elem_id="search_r8", elem_classes=["no-radius"])
            search_r9 = gr.Button(visible=False, elem_id="search_r9", elem_classes=["no-radius"])
            search_r10 = gr.Button(visible=False, elem_id="search_r10", elem_classes=["no-radius"])

        conv_type = gr.Radio(choices=["Q&As", "Chat"], value="Q&As", interactive=True, visible=False, elem_classes=["conv-type"])

    with gr.Column(scale=7):
        title = gr.Markdown(f"# {selected_paper['title']}")
        # with gr.Row():
        with gr.Row():
            arxiv_link = gr.Markdown(
                "[![arXiv](https://img.shields.io/badge/arXiv-%s-b31b1b.svg)](https://arxiv.org/abs/%s)" % (selected_paper['arxiv_id'], selected_paper['arxiv_id'])
            )
            hf_paper_link = gr.Markdown(
                "[![Paper page](https://huggingface.co/datasets/huggingface/badges/resolve/main/paper-page-md.svg)](https://huggingface.co/papers/%s)" % selected_paper['arxiv_id']
            )
            gr.Button("Chat about the paper", interactive=False)
            
        summary = gr.Markdown(f"{selected_paper['summary']}", elem_classes=["small-font"])

        with gr.Column(elem_id="chat_block", visible=False):
            gr.Chatbot([("hello", "world"), ("how", "are you?")])

        with gr.Column(elem_id="qna_block", visible=True):
            with gr.Row():
                with gr.Column(scale=7):
                    gr.Markdown("## Auto generated Questions & Answers")

                exp_type = gr.Radio(choices=["ELI5", "Technical"], value="ELI5", elem_classes=["exp-type"], scale=3)

            # 1
            with gr.Column(elem_classes=["group"], visible=True) as q_0:
                basic_q_0 = gr.Markdown(f"### πŸ™‹ {selected_paper['0_question']}")
                basic_q_eli5_0 = gr.Markdown(f"β†ͺ **(ELI5)** {selected_paper['0_answers:eli5']}", elem_classes=["small-font"]) 
                basic_q_expert_0 = gr.Markdown(f"β†ͺ **(Technical)** {selected_paper['0_answers:expert']}", visible=False, elem_classes=["small-font"]) 

                with gr.Accordion("Additional question #1", open=False, elem_classes=["accordion"]) as aq_0_0:
                    depth_q_0 = gr.Markdown(f"### πŸ™‹πŸ™‹ {selected_paper['0_additional_depth_q:follow up question']}")
                    depth_q_eli5_0 = gr.Markdown(f"β†ͺ **(ELI5)** {selected_paper['0_additional_depth_q:answers:eli5']}", elem_classes=["small-font"])
                    depth_q_expert_0 = gr.Markdown(f"β†ͺ **(Technical)** {selected_paper['0_additional_depth_q:answers:expert']}", visible=False, elem_classes=["small-font"])

                with gr.Accordion("Additional question #2", open=False, elem_classes=["accordion"]) as aq_0_1:
                    breath_q_0 = gr.Markdown(f"### πŸ™‹πŸ™‹ {selected_paper['0_additional_breath_q:follow up question']}")
                    breath_q_eli5_0 = gr.Markdown(f"β†ͺ **(ELI5)** {selected_paper['0_additional_breath_q:answers:eli5']}", elem_classes=["small-font"])
                    breath_q_expert_0 = gr.Markdown(f"β†ͺ **(Technical)** {selected_paper['0_additional_breath_q:answers:expert']}", visible=False, elem_classes=["small-font"])

            # 2
            with gr.Column(elem_classes=["group"], visible=True) as q_1:
                basic_q_1 = gr.Markdown(f"### πŸ™‹ {selected_paper['1_question']}")
                basic_q_eli5_1 = gr.Markdown(f"β†ͺ **(ELI5)** {selected_paper['1_answers:eli5']}", elem_classes=["small-font"]) 
                basic_q_expert_1 = gr.Markdown(f"β†ͺ **(Technical)** {selected_paper['1_answers:expert']}", visible=False, elem_classes=["small-font"]) 

                with gr.Accordion("Additional question #1", open=False, elem_classes=["accordion"]) as aq_1_0:
                    depth_q_1 = gr.Markdown(f"### πŸ™‹πŸ™‹ {selected_paper['1_additional_depth_q:follow up question']}")
                    depth_q_eli5_1 = gr.Markdown(f"β†ͺ **(ELI5)** {selected_paper['1_additional_depth_q:answers:eli5']}", elem_classes=["small-font"])
                    depth_q_expert_1 = gr.Markdown(f"β†ͺ **(Technical)** {selected_paper['1_additional_depth_q:answers:expert']}", visible=False, elem_classes=["small-font"])

                with gr.Accordion("Additional question #2", open=False, elem_classes=["accordion"]) as aq_1_1:
                    breath_q_1 = gr.Markdown(f"### πŸ™‹πŸ™‹ {selected_paper['1_additional_breath_q:follow up question']}")
                    breath_q_eli5_1 = gr.Markdown(f"β†ͺ **(ELI5)** {selected_paper['1_additional_breath_q:answers:eli5']}", elem_classes=["small-font"])
                    breath_q_expert_1 = gr.Markdown(f"β†ͺ **(Technical)** {selected_paper['1_additional_breath_q:answers:expert']}", visible=False, elem_classes=["small-font"])

            # 3
            with gr.Column(elem_classes=["group"], visible=True) as q_2:
                basic_q_2 = gr.Markdown(f"### πŸ™‹ {selected_paper['2_question']}")
                basic_q_eli5_2 = gr.Markdown(f"β†ͺ **(ELI5)** {selected_paper['2_answers:eli5']}", elem_classes=["small-font"]) 
                basic_q_expert_2 = gr.Markdown(f"β†ͺ **(Technical)** {selected_paper['2_answers:expert']}", visible=False, elem_classes=["small-font"]) 

                with gr.Accordion("Additional question #1", open=False, elem_classes=["accordion"]) as aq_2_0:
                    depth_q_2 = gr.Markdown(f"### πŸ™‹πŸ™‹ {selected_paper['2_additional_depth_q:follow up question']}")
                    depth_q_eli5_2 = gr.Markdown(f"β†ͺ **(ELI5)** {selected_paper['2_additional_depth_q:answers:eli5']}", elem_classes=["small-font"])
                    depth_q_expert_2 = gr.Markdown(f"β†ͺ **(Technical)** {selected_paper['2_additional_depth_q:answers:expert']}", visible=False, elem_classes=["small-font"])

                with gr.Accordion("Additional question #2", open=False, elem_classes=["accordion"]) as aq_2_1:
                    breath_q_2 = gr.Markdown(f"### πŸ™‹πŸ™‹ {selected_paper['2_additional_breath_q:follow up question']}")
                    breath_q_eli5_2 = gr.Markdown(f"β†ͺ **(ELI5)** {selected_paper['2_additional_breath_q:answers:eli5']}", elem_classes=["small-font"])
                    breath_q_expert_2 = gr.Markdown(f"β†ͺ **(Technical)** {selected_paper['2_additional_breath_q:answers:expert']}", visible=False, elem_classes=["small-font"])

        gr.Markdown("## Request any arXiv ids")
        arxiv_queue = gr.Dataframe(
            headers=["Requested arXiv IDs"], col_count=(1, "fixed"),
            value=requested_arxiv_ids_df,
            datatype=["str"],
            interactive=False
        )

        arxiv_id_enter = gr.Textbox(placeholder="Enter comma separated arXiv IDs...", elem_classes=["textbox-no-label"])
        arxiv_id_enter.submit(
            add_arxiv_ids_to_queue,
            [arxiv_queue, arxiv_id_enter],
            [arxiv_queue, arxiv_id_enter]
        )


    gr.Markdown("The target papers are collected from [Hugging Face πŸ€— Daily Papers](https://huggingface.co/papers) on a daily basis. "
                "The entire data is generated by [Google's Gemini 1.0](https://deepmind.google/technologies/gemini/) Pro. "
                "If you are curious how it is done, visit the [Auto Paper Q&A Generation project repository](https://github.com/deep-diver/auto-paper-analysis) "
                "Also, the generated dataset is hosted on Hugging Face πŸ€— Dataset repository as well([Link](https://huggingface.co/datasets/chansung/auto-paper-qa2)). ")
    
    search_r1.click(set_date, search_r1, [year_dd, month_dd, day_dd]).then(
        set_papers,
        inputs=[year_dd, month_dd, day_dd, search_r1],
        outputs=[papers_dd, search_in]
    )

    search_r2.click(set_date, search_r2, [year_dd, month_dd, day_dd]).then(
        set_papers,
        inputs=[year_dd, month_dd, day_dd, search_r2],
        outputs=[papers_dd, search_in]
    )

    search_r3.click(set_date, search_r3, [year_dd, month_dd, day_dd]).then(
        set_papers,
        inputs=[year_dd, month_dd, day_dd, search_r3],
        outputs=[papers_dd, search_in]
    )

    search_r4.click(set_date, search_r4, [year_dd, month_dd, day_dd]).then(
        set_papers,
        inputs=[year_dd, month_dd, day_dd, search_r4],
        outputs=[papers_dd, search_in]
    )

    search_r5.click(set_date, search_r5, [year_dd, month_dd, day_dd]).then(
        set_papers,
        inputs=[year_dd, month_dd, day_dd, search_r5],
        outputs=[papers_dd, search_in]
    )

    search_r6.click(set_date, search_r6, [year_dd, month_dd, day_dd]).then(
        set_papers,
        inputs=[year_dd, month_dd, day_dd, search_r6],
        outputs=[papers_dd, search_in]
    )

    search_r7.click(set_date, search_r7, [year_dd, month_dd, day_dd]).then(
        set_papers,
        inputs=[year_dd, month_dd, day_dd, search_r7],
        outputs=[papers_dd, search_in]
    )    

    search_r8.click(set_date, search_r8, [year_dd, month_dd, day_dd]).then(
        set_papers,
        inputs=[year_dd, month_dd, day_dd, search_r8],
        outputs=[papers_dd, search_in]
    )

    search_r9.click(set_date, search_r9, [year_dd, month_dd, day_dd]).then(
        set_papers,
        inputs=[year_dd, month_dd, day_dd, search_r9],
        outputs=[papers_dd, search_in]
    )

    search_r10.click(set_date, search_r10, [year_dd, month_dd, day_dd]).then(
        set_papers,
        inputs=[year_dd, month_dd, day_dd, search_r10],
        outputs=[papers_dd, search_in]
    )

    year_dd.input(
        get_paper_by_year, 
        inputs=[year_dd],
        outputs=[month_dd, day_dd, papers_dd]
    ).then(
        set_paper,
        [year_dd, month_dd, day_dd, papers_dd],
        [
            title, summary,
            basic_q_0, basic_q_eli5_0, basic_q_expert_0,
            depth_q_0, depth_q_eli5_0, depth_q_expert_0,
            breath_q_0, breath_q_eli5_0, breath_q_expert_0,

            basic_q_1, basic_q_eli5_1, basic_q_expert_1,
            depth_q_1, depth_q_eli5_1, depth_q_expert_1,
            breath_q_1, breath_q_eli5_1, breath_q_expert_1,

            basic_q_2, basic_q_eli5_2, basic_q_expert_2,
            depth_q_2, depth_q_eli5_2, depth_q_expert_2,
            breath_q_2, breath_q_eli5_2, breath_q_expert_2
        ]        
    )

    month_dd.input(
        get_paper_by_month, 
        inputs=[year_dd, month_dd], 
        outputs=[day_dd, papers_dd]
    ).then(
        set_paper,
        [year_dd, month_dd, day_dd, papers_dd],
        [
            title, arxiv_link, hf_paper_link, summary,
            basic_q_0, basic_q_eli5_0, basic_q_expert_0,
            depth_q_0, depth_q_eli5_0, depth_q_expert_0,
            breath_q_0, breath_q_eli5_0, breath_q_expert_0,

            basic_q_1, basic_q_eli5_1, basic_q_expert_1,
            depth_q_1, depth_q_eli5_1, depth_q_expert_1,
            breath_q_1, breath_q_eli5_1, breath_q_expert_1,

            basic_q_2, basic_q_eli5_2, basic_q_expert_2,
            depth_q_2, depth_q_eli5_2, depth_q_expert_2,
            breath_q_2, breath_q_eli5_2, breath_q_expert_2
        ]        
    )

    day_dd.input(
        get_paper_by_day, 
        inputs=[year_dd, month_dd, day_dd], 
        outputs=[papers_dd]
    ).then(
        set_paper,
        [year_dd, month_dd, day_dd, papers_dd],
        [
            title, arxiv_link, hf_paper_link, summary,
            basic_q_0, basic_q_eli5_0, basic_q_expert_0,
            depth_q_0, depth_q_eli5_0, depth_q_expert_0,
            breath_q_0, breath_q_eli5_0, breath_q_expert_0,

            basic_q_1, basic_q_eli5_1, basic_q_expert_1,
            depth_q_1, depth_q_eli5_1, depth_q_expert_1,
            breath_q_1, breath_q_eli5_1, breath_q_expert_1,

            basic_q_2, basic_q_eli5_2, basic_q_expert_2,
            depth_q_2, depth_q_eli5_2, depth_q_expert_2,
            breath_q_2, breath_q_eli5_2, breath_q_expert_2
        ]        
    )

    papers_dd.change(
        set_paper,
        [year_dd, month_dd, day_dd, papers_dd],
        [
            title, arxiv_link, hf_paper_link, summary,
            basic_q_0, basic_q_eli5_0, basic_q_expert_0,
            depth_q_0, depth_q_eli5_0, depth_q_expert_0,
            breath_q_0, breath_q_eli5_0, breath_q_expert_0,

            basic_q_1, basic_q_eli5_1, basic_q_expert_1,
            depth_q_1, depth_q_eli5_1, depth_q_expert_1,
            breath_q_1, breath_q_eli5_1, breath_q_expert_1,

            basic_q_2, basic_q_eli5_2, basic_q_expert_2,
            depth_q_2, depth_q_eli5_2, depth_q_expert_2,
            breath_q_2, breath_q_eli5_2, breath_q_expert_2
        ]
    )

    search_in.change(
        inputs=[search_in],
        outputs=[
            search_r1, search_r2, search_r3, search_r4, search_r5,
            search_r6, search_r7, search_r8, search_r9, search_r10
        ],
        js=UPDATE_SEARCH_RESULTS % str(list(titles)),
        fn=None
    )

    exp_type.select(
        change_exp_type,
        exp_type,
        [
            basic_q_eli5_0, basic_q_expert_0, depth_q_eli5_0, depth_q_expert_0, breath_q_eli5_0, breath_q_expert_0,
            basic_q_eli5_1, basic_q_expert_1, depth_q_eli5_1, depth_q_expert_1, breath_q_eli5_1, breath_q_expert_1,
            basic_q_eli5_2, basic_q_expert_2, depth_q_eli5_2, depth_q_expert_2, breath_q_eli5_2, breath_q_expert_2
        ]
    )

    conv_type.select(
        inputs=[conv_type],
        js=UPDATE_IF_TYPE,
        outputs=None,
        fn=None
    )

start_date = datetime.now() + timedelta(minutes=1)
scheduler = BackgroundScheduler()
scheduler.add_job(
    process_arxiv_ids,
    trigger='interval',
    seconds=3600,
    args=[
        gemini_api_key, 
        dataset_repo_id,
        request_arxiv_repo_id,
        hf_token
    ],
    start_date=start_date
)
scheduler.start()

demo.launch(share=True, debug=True)