File size: 31,019 Bytes
e17c9f2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import os
import json
import re
from sentence_transformers import SentenceTransformer
from tqdm import tqdm
from utils.paper_crawling import PaperCrawling
from utils.paper_client import PaperClient
from utils.hash import generate_hash_id
from collections import defaultdict
from utils.header import get_dir, ConfigReader
from utils.llms_api import APIHelper
from utils.paper_retriever import Retriever
from utils import scipdf
import click
from collections import Counter
from loguru import logger
import warnings

warnings.filterwarnings("ignore")

unicode_pattern = r"\u00c0-\u00ff\u0100-\u017f\u0180-\u024f\u4e00-\u9fff\u3040-\u309f\u30a0-\u30ff\u31f0-\u31ff"


def find_methodology(article_dict):
    def find_section_index(keywords):
        for i, section in enumerate(article_dict["sections"], 1):
            heading = section["heading"].lower()
            text = section["text"].lower()
            if any(keyword in heading for keyword in keywords):
                return i - 1
            i = -1
        if i == -1:
            for i, section in enumerate(article_dict["sections"], 1):
                heading = section["heading"].lower()
                text = section["text"].lower()
                if any(
                    keyword in re.split(r"(?<=[.!?])\s+", text)[-1]
                    for keyword in keywords
                ):
                    return i
        return -1

    index = find_section_index(["experiment", "evaluation"])
    if index == -1:
        experiments_index = next(
            (
                i
                for i, section in enumerate(article_dict["sections"])
                if "experiment" in section["heading"].lower()
                or "evaluation" in section["heading"].lower()
            ),
            5,
        )
        experiments_index = min(experiments_index, len(article_dict["sections"]))
        texts = [
            section["text"] for section in article_dict["sections"][1:experiments_index]
        ]
        methodology = " ".join(texts)
        return methodology
    texts = [
        section["text"]
        for section in article_dict["sections"][1:index]
        if not any(
            keyword in section["heading"].lower()
            for keyword in ["relate", "previous", "background"]
        )
    ]
    methodology = " ".join(texts)
    return methodology


def count_sb_pairs(text):
    return len(re.findall(r"\[.*?\]", text))


def count_rb_pairs(text):
    return len(re.findall(r"\(.*?\)", text))


def find_cite_paper(introduction, methodology, references):
    """
    Count the number of times []/() appear in the introduction,
    and determine which one is the reference ()/[]
    """
    text = introduction + methodology
    rb_count = count_rb_pairs(introduction)
    sb_count = count_sb_pairs(introduction)
    pattern = (
        r"\b[A-Z"
        + unicode_pattern
        + r"][a-zA-Z"
        + unicode_pattern
        + r"]+(?: and [A-Z"
        + unicode_pattern
        + r"][a-zA-Z"
        + unicode_pattern
        + r"]+)?(?: et al\.)?, \d{4}[a-z]?\b"
    )
    pattern = (
        r"\b[A-Z"
        + unicode_pattern
        + r"][a-zA-Z"
        + unicode_pattern
        + r"]+(?: and [A-Z"
        + unicode_pattern
        + r"][a-zA-Z"
        + unicode_pattern
        + r"]+)?(?: et al\.)?, \d{4}[a-z]?\b"
    )
    temp_list = re.findall(pattern, text)
    ref_list = []
    ref_title = []
    if len(temp_list) > 0:
        pattern = (
            r"\b([A-Z"
            + unicode_pattern
            + r"][a-zA-Z"
            + unicode_pattern
            + r"]+)(?: and [A-Z"
            + unicode_pattern
            + r"][a-zA-Z"
            + unicode_pattern
            + r"]+)?(?: et al\.)?, (\d{4})[a-z]?\b"
        )
        for temp in temp_list:
            match = re.search(pattern, temp)
            ref_list.append({"authors": match.group(1), "year": match.group(2)})
        for i, ref in enumerate(ref_list):
            for j, r in enumerate(references):
                if r["year"] == ref["year"] and ref["authors"] in r["authors"]:
                    ref_title.append(r["title"])
    if len(ref_title) <= 1:
        ref_list = []
        ref_title = []
        if rb_count < sb_count:
            pattern = r"\[\d+(?:,\s*\d+)*\]"
        else:
            pattern = r"\(\d+(?:,\s*\d+)*\)"
        ref_list = re.findall(pattern, text)
        # ref: ['[15, 16]', '[5]', '[2, 3, 8]']
        combined_ref_list = []
        for ref in ref_list:
            numbers = re.findall(r"\d+", ref)
            combined_ref_list.extend(map(int, numbers))
        # Sort
        ref_counts = Counter(combined_ref_list)
        ref_counts = dict(sorted(ref_counts.items()))
        ref_list = list(ref_counts.keys())
        for idx in ref_list:
            if idx < len(references):
                ref_title.append(references[idx]["title"])
    return ref_title


class PaperManager:
    def __init__(self, config, venue_name="acl", year="2013") -> None:
        log_dir = config.DEFAULT.log_dir
        if not os.path.exists(log_dir):
            os.makedirs(log_dir)
            print(f"Created log directory: {log_dir}")
        log_file = os.path.join(log_dir, "paper_manager.log")
        logger.add(log_file, level=config.DEFAULT.log_level)
        self.venue_name = venue_name
        self.year = year
        self.data_type = "train"
        self.paper_client = PaperClient(config)
        self.paper_crawling = PaperCrawling(config, data_type=self.data_type)
        self.embedding_model = SentenceTransformer(
            model_name_or_path=get_dir(config.DEFAULT.embedding), device=self.config.DEFAULT.device
        )
        self.api_helper = APIHelper(config)
        self.retriever = Retriever(config)
        self.paper_id_map = defaultdict()
        self.citemap = defaultdict(set)
        self.year_list = [
            "2013",
            "2014",
            "2015",
            "2016",
            "2017",
            "2018",
            "2019",
            "2020",
            "2021",
            "2022",
            "2023",
            "2024",
        ]
        self.config = config
        with open(config.DEFAULT.ignore_paper_id_list, "r", encoding="utf-8") as f:
            try:
                self.ignore_paper_pdf_url = [dic["pdf_url"] for dic in json.load(f)]
            except:
                self.ignore_paper_pdf_url = []

    def create_vector_index(self):
        index_exists = self.paper_client.check_index_exists()
        if not index_exists:
            print("Create vector index paper-embeddings")
            self.paper_client.create_vector_index()

    def clean_entity(self, entity):
        if entity is None:
            return None
        cleaned_entity = re.sub(r"\([^)]*\)", "", entity)
        cleaned_entity = re.sub(r"[^\w\s]", "", cleaned_entity)
        cleaned_entity = re.sub(r"_", " ", cleaned_entity)
        cleaned_entity = re.sub(r"\s+", " ", cleaned_entity).strip()
        return cleaned_entity

    def clean_text(self, text):
        return text.replace(", , ", ", ")

    def check_parse(self, paper):
        # Required keys
        required_keys = [
            "abstract",
            "introduction",
            "reference",
            "methodology",
            "reference_filter",
        ]
        # Check for missing keys or None values
        for key in required_keys:
            if key not in paper or paper[key] is None:
                logger.error(
                    f"hash_id: {paper.get('hash_id')} pdf_url: {paper.get('pdf_url')} : "
                    f"Missing or None '{key}' in paper."
                )
                return False
        return True

    def update_paper(
        self,
        paper,
        need_download=False,
        need_parse=False,
        need_summary=False,
        need_get_entities=False,
        need_ground_truth=False,
    ):
        if paper["pdf_url"] in self.ignore_paper_pdf_url:
            logger.warning(
                "hash_id: {}, pdf_url: {} ignore".format(
                    paper["hash_id"], paper["pdf_url"]
                )
            )
            return
        self.paper_client.update_paper_from_client(paper)
        if need_download:
            if not self.paper_crawling.download_paper(paper):
                print(f"download paper {paper['pdf_url']} failed!")
                return
        if need_parse:
            if not self.check_parse(paper):
                logger.debug(f"begin to parse {paper['hash_id']}")
                if not self.paper_crawling.download_paper(paper):
                    logger.error(f"download paper {paper['pdf_url']} failed!")
                    return
                try:
                    article_dict = scipdf.parse_pdf_to_dict(paper["pdf_path"])
                    if "title" not in paper.keys() or paper["title"] is None:
                        paper["title"] = article_dict["title"]
                    paper["abstract"] = article_dict["abstract"]
                    paper["introduction"] = article_dict["sections"][0]["text"]
                    paper["methodology"] = find_methodology(article_dict)
                    reference = []
                    for ref in article_dict["references"]:
                        reference.append(ref["title"])
                    paper["reference"] = reference
                    paper["reference_filter"] = find_cite_paper(
                        paper["introduction"],
                        paper["methodology"],
                        article_dict["references"],
                    )
                    logger.info(f"{paper['hash_id']} parse success")
                except Exception:
                    logger.error(
                        f"{paper['hash_id']}: {paper['pdf_url']}  parse error!"
                    )

        if need_summary:
            if not self.check_parse(paper):
                logger.error(f"paper {paper['hash_id']} need parse first...")
            elif "summary" not in paper.keys():
                result = self.api_helper(
                    paper["title"], paper["abstract"], paper["introduction"]
                )
                if result is not None:
                    paper["summary"] = result["summary"]
                    paper["motivation"] = result["motivation"]
                    paper["contribution"] = result["contribution"]
                    logger.info(f"paper {paper['hash_id']} summary success...")
                else:
                    logger.warning(
                        "hash_id: {}, pdf_url: {} summary failed...".format(
                            paper["hash_id"], paper["pdf_url"]
                        )
                    )
            if need_ground_truth:
                if "ground_truth" not in paper.keys():
                    if (
                        "abstract" in paper.keys()
                        and "contribution" in paper.keys()
                        and "methodology" in paper.keys()
                    ):
                        paper["ground_truth"] = self.api_helper.generate_ground_truth(
                            abstract=paper["abstract"],
                            contribution=paper["contribution"],
                            text=paper["methodology"],
                        )
                        logger.info(f"paper {paper['hash_id']} ground truth success...")
                    else:
                        logger.error("Can't get ground truth...please check")

        # insert paper in database
        if self.check_parse(paper):
            self.paper_client.add_paper_node(paper)
        else:
            return

        if need_get_entities and self.paper_client.check_entity_node_count(
            paper["hash_id"]
        ):
            if (
                paper["abstract"] is None
                or paper["introduction"] is None
                or paper["reference"] is None
            ):
                logger.error(f"paper need parse first")
            entities = self.api_helper.generate_entity_list(paper["abstract"])
            logger.info("hash_id {}, Entities: {}".format(paper["hash_id"], entities))
            if entities is not None:
                self.paper_client.add_entity_node(paper["hash_id"], entities)
            else:
                logger.warning(
                    "hash_id: {}, pdf_url: {} entities None...".format(
                        paper["hash_id"], paper["pdf_url"]
                    )
                )

    def update_paper_local(
        self,
        paper,
        need_download=False,
        need_parse=False,
        need_summary=False,
        need_get_entities=False,
        need_ground_truth=False,
    ):
        if paper["pdf_url"] in self.ignore_paper_pdf_url:
            logger.warning(
                "hash_id: {}, pdf_url: {} ignore".format(
                    paper["hash_id"], paper["pdf_url"]
                )
            )
            return
        # keep the content of the paper node consistent with the database
        self.paper_client.update_paper_from_client(paper)
        if need_download:
            if not self.paper_crawling.download_paper(paper):
                print(f"download paper {paper['pdf_url']} failed!")
                return
        if need_parse:
            if not self.check_parse(paper):  # haven't parse
                logger.debug(f"begin to parse {paper['hash_id']}")
                if not self.paper_crawling.download_paper(paper):
                    logger.error(f"download paper {paper['pdf_url']} failed!")
                    return
                try:
                    article_dict = scipdf.parse_pdf_to_dict(paper["pdf_path"])
                    if "title" not in paper.keys() or paper["title"] is None:
                        paper["title"] = article_dict["title"]
                    paper["abstract"] = article_dict["abstract"]
                    paper["introduction"] = article_dict["sections"][0]["text"]
                    paper["methodology"] = find_methodology(article_dict)
                    reference = []
                    for ref in article_dict["references"]:
                        reference.append(ref["title"])
                    paper["reference"] = reference
                    paper["reference_filter"] = find_cite_paper(
                        paper["introduction"],
                        paper["methodology"],
                        article_dict["references"],
                    )
                    logger.info(f"{paper['hash_id']} parse success")
                except Exception:
                    logger.error(
                        f"{paper['hash_id']}: {paper['pdf_url']}  parse error!"
                    )

        if need_summary:
            print(paper.keys())
            if not self.check_parse(paper):
                logger.error(f"paper {paper['hash_id']} need parse first...")

            result = self.api_helper(
                paper["title"], paper["abstract"], paper["introduction"]
            )
            if result is not None:
                paper["summary"] = result["summary"]
                paper["motivation"] = result["motivation"]
                paper["contribution"] = result["contribution"]
                logger.info(f"paper {paper['hash_id']} summary success...")
            else:
                logger.warning(
                    "hash_id: {}, pdf_url: {} summary failed...".format(
                        paper["hash_id"], paper["pdf_url"]
                    )
                )

            if need_ground_truth:
                if (
                    "abstract" in paper.keys()
                    and "contribution" in paper.keys()
                    and "methodology" in paper.keys()
                ):
                    paper["ground_truth"] = self.api_helper.generate_ground_truth(
                        abstract=paper["abstract"],
                        contribution=paper["contribution"],
                        text=paper["methodology"],
                    )
                    logger.info(f"paper {paper['hash_id']} ground truth success...")
                else:
                    logger.error("Can't get ground truth...please check")

        if need_get_entities and self.paper_client.check_entity_node_count(
            paper["hash_id"]
        ):
            if (
                paper["abstract"] is None
                or paper["introduction"] is None
                or paper["reference"] is None
            ):
                logger.error(f"paper need parse first")
            entities = self.api_helper.generate_entity_list(paper["abstract"])
            logger.info("hash_id {}, Entities: {}".format(paper["hash_id"], entities))
            if entities is not None:
                self.paper_client.add_entity_node(paper["hash_id"], entities)
            else:
                logger.warning(
                    "hash_id: {}, pdf_url: {} entities None...".format(
                        paper["hash_id"], paper["pdf_url"]
                    )
                )

        with open(
            self.config.output_path.replace(
                ".json", "_{}.json".format(paper["hash_id"])
            ),
            "w",
            encoding="utf8",
        ) as f:
            json.dump(paper, f)
        return paper

    def update_paper_from_json(
        self,
        need_download=True,
        need_parse=False,
        need_summary=False,
        need_get_entities=False,
        need_ground_truth=False,
    ):
        if self.year != "all":
            logger.info(
                "=== year {}, venue name {} ===".format(self.year, self.venue_name)
            )
            with open(
                f"./assets/paper/{self.venue_name}/{self.venue_name}_{self.year}_paper_list.json",
                "r",
                encoding="utf8",
            ) as f:
                paper_list = json.load(f)
            for paper in tqdm(paper_list):
                self.update_paper(
                    paper,
                    need_download=need_download,
                    need_parse=need_parse,
                    need_summary=need_summary,
                    need_get_entities=need_get_entities,
                    need_ground_truth=need_ground_truth,
                )
        else:
            if self.venue_name == "iccv":
                self.year_list = ["2013", "2015", "2017", "2019", "2021", "2023"]
            elif self.venue_name == "eccv":
                self.year_list = ["2018", "2020", "2022", "2024"]
            for year in self.year_list:
                with open(
                    f"./assets/paper/{self.venue_name}/{self.venue_name}_{year}_paper_list.json",
                    "r",
                    encoding="utf8",
                ) as f:
                    paper_list = json.load(f)
                logger.info(
                    "=== year {}, venue name {} ===".format(year, self.venue_name)
                )
                for paper in tqdm(paper_list):
                    self.update_paper(
                        paper,
                        need_download=need_download,
                        need_parse=need_parse,
                        need_summary=need_summary,
                        need_get_entities=need_get_entities,
                        need_ground_truth=need_ground_truth,
                    )

    def update_paper_from_json_to_json(
        self,
        need_download=True,
        need_parse=False,
        need_summary=False,
        need_get_entities=False,
        need_ground_truth=False,
    ):
        result = []
        if self.year != "all":
            logger.info(
                "=== year {}, venue name {} ===".format(self.year, self.venue_name)
            )
            with open(
                f"./assets/paper/{self.venue_name}/{self.venue_name}_{self.year}_paper_list.json",
                "r",
                encoding="utf8",
            ) as f:
                paper_list = json.load(f)
            result = [
                self.update_paper_local(
                    paper,
                    need_download=need_download,
                    need_parse=need_parse,
                    need_summary=need_summary,
                    need_get_entities=need_get_entities,
                    need_ground_truth=need_ground_truth,
                )
                for paper in tqdm(paper_list)
            ]

        else:
            if self.venue_name == "iccv":
                self.year_list = ["2013", "2015", "2017", "2019", "2021", "2023"]
            elif self.venue_name == "eccv":
                self.year_list = ["2018", "2020", "2022", "2024"]
            for year in self.year_list:
                with open(
                    f"./assets/paper/{self.venue_name}/{self.venue_name}_{year}_paper_list.json",
                    "r",
                    encoding="utf8",
                ) as f:
                    paper_list = json.load(f)
                logger.info(
                    "=== year {}, venue name {} ===".format(year, self.venue_name)
                )
                subresult = [
                    self.update_paper_local(
                        paper,
                        need_download=need_download,
                        need_parse=need_parse,
                        need_summary=need_summary,
                        need_get_entities=need_get_entities,
                        need_ground_truth=need_ground_truth,
                    )
                    for paper in tqdm(paper_list)
                ]
                result += subresult

        with open(self.config.output_path, "w", encoding="utf8") as f:
            json.dump(result, f)

    def insert_citation(self):
        if self.year != "all":
            year_list = [self.year]
        else:
            year_list = self.year_list
        for year in year_list:
            paper_list = self.paper_client.select_paper(self.venue_name, year)
            for paper in tqdm(paper_list):
                if (
                    self.check_parse(paper)
                    and len(paper["reference"]) > 0
                    and "motivation" in paper.keys()
                    and paper["motivation"] is not None
                ):
                    paper["cite_id_list"] = [
                        generate_hash_id(ref_title)
                        for ref_title in paper["reference_filter"]
                    ]
                    paper["cite_id_list"] = self.paper_client.filter_paper_id_list(
                        paper["cite_id_list"], year=year
                    )
                    paper["all_cite_id_list"] = [
                        generate_hash_id(ref_title) for ref_title in paper["reference"]
                    ]
                    paper["all_cite_id_list"] = self.paper_client.filter_paper_id_list(
                        paper["all_cite_id_list"], year=year
                    )
                    if "entities" not in paper.keys() or len(paper["entities"]) < 3:
                        paper["entities"] = self.api_helper.generate_entity_list(
                            paper["abstract"]
                        )
                        logger.debug(
                            "get entity from context: {}".format(paper["entities"])
                        )
                    logger.debug(
                        "paper hash_id {}, cite_id_list {}, all_cite_id_list {}".format(
                            paper["hash_id"],
                            paper["cite_id_list"],
                            paper["all_cite_id_list"],
                        )
                    )
                else:
                    paper["cite_id_list"] = []
                    paper["all_cite_id_list"] = []
                if (
                    "entities" in paper.keys()
                    and "cite_id_list" in paper.keys()
                    and "all_cite_id_list" in paper.keys()
                ):
                    self.paper_client.add_paper_citation(paper)

    def insert_entity_combinations(self):
        if self.year != "all":
            year_list = [self.year]
        else:
            year_list = self.year_list
        for year in year_list:
            self.paper_client.get_entity_combinations(self.venue_name, year)

    def insert_embedding(self, hash_id=None):
        self.paper_client.add_paper_abstract_embedding(self.embedding_model, hash_id)
        # self.client.add_paper_bg_embedding(self.embedding_model, hash_id)
        # self.client.add_paper_contribution_embedding(self.embedding_model, hash_id)
        # self.client.add_paper_summary_embedding(self.embedding_model, hash_id)

    def cosine_similarity_search(self, data_type, context, k=1):
        """
        return related paper: list
        """
        embedding = self.embedding_model.encode(context)
        result = self.paper_client.cosine_similarity_search(data_type, embedding, k)
        return result

    def generate_paper_list(self):
        folder_path = f"./assets/paper/{self.venue_name}"
        if not os.path.exists(folder_path):
            os.makedirs(folder_path)
        if self.year != "all":
            logger.info(
                "=== year {}, venue name {} ===".format(self.year, self.venue_name)
            )
            paper_list = self.paper_crawling.crawling(self.year, self.venue_name)
            with open(
                f"{folder_path}/{self.venue_name}_{self.year}_paper_list.json",
                "w",
            ) as f:
                json.dump(paper_list, f, indent=4, ensure_ascii=False)
        else:
            for year in self.year_list:
                logger.info(
                    "=== year {}, venue name {} ===".format(year, self.venue_name)
                )
                paper_list = self.paper_crawling.crawling(year, self.venue_name)
                with open(
                    f"{folder_path}/{self.venue_name}_{year}_paper_list.json",
                    "w",
                ) as f:
                    json.dump(paper_list, f, indent=4, ensure_ascii=False)


@click.group()
@click.pass_context
def main(ctx):
    """
    Training and evaluation
    """
    print("Mode:", ctx.invoked_subcommand)


@main.command()
@click.option(
    "-c",
    "--config-path",
    default=get_dir("./configs/datasets.yaml"),
    type=click.File(),
    required=True,
    help="Dataset configuration file in YAML",
)
@click.option(
    "--year",
    default="2013",
    type=str,
    required=True,
    help="Venue year",
)
@click.option(
    "--venue-name",
    default="acl",
    type=str,
    required=True,
    help="Venue name",
)
@click.option(
    "--llms-api",
    default=None,
    type=str,
    required=False,
    help="The LLMS API alias used. If you do not have separate APIs for summarization and generation, you can use this unified setting. This option is ignored when setting the API to be used by summarization and generation separately",
)
@click.option(
    "--sum-api",
    default=None,
    type=str,
    required=False,
    help="The LLMS API aliases used for summarization. When used, it will invalidate --llms-api",
)
@click.option(
    "--gen-api",
    default=None,
    type=str,
    required=False,
    help="The LLMS API aliases used for generation. When used, it will invalidate --llms-api",
)
def crawling(config_path, year, venue_name, **kwargs):
    # Configuration
    config = ConfigReader.load(config_path, **kwargs)
    pm = PaperManager(config, venue_name, year)
    pm.generate_paper_list()


@main.command()
@click.option(
    "-c",
    "--config-path",
    default=get_dir("./configs/datasets.yaml"),
    type=click.File(),
    required=True,
    help="Dataset configuration file in YAML",
)
@click.option(
    "--year",
    default="2013",
    type=str,
    required=True,
    help="Venue year",
)
@click.option(
    "--venue-name",
    default="acl",
    type=str,
    required=True,
    help="Venue name",
)
@click.option(
    "--llms-api",
    default=None,
    type=str,
    required=False,
    help="The LLMS API alias used. If you do not have separate APIs for summarization and generation, you can use this unified setting. This option is ignored when setting the API to be used by summarization and generation separately",
)
@click.option(
    "--sum-api",
    default=None,
    type=str,
    required=False,
    help="The LLMS API aliases used for summarization. When used, it will invalidate --llms-api",
)
@click.option(
    "--gen-api",
    default=None,
    type=str,
    required=False,
    help="The LLMS API aliases used for generation. When used, it will invalidate --llms-api",
)
def update(config_path, year, venue_name, **kwargs):
    # Configuration
    config = ConfigReader.load(config_path, **kwargs)
    pm = PaperManager(config, venue_name, year)
    pm.update_paper_from_json(need_download=True)


@main.command()
@click.option(
    "-c",
    "--config-path",
    default=get_dir("./configs/datasets.yaml"),
    type=click.File(),
    required=True,
    help="Dataset configuration file in YAML",
)
@click.option(
    "--year",
    default="2013",
    type=str,
    required=True,
    help="Venue year",
)
@click.option(
    "--venue-name",
    default="acl",
    type=str,
    required=True,
    help="Venue name",
)
@click.option(
    "--llms-api",
    default=None,
    type=str,
    required=False,
    help="The LLMS API alias used. If you do not have separate APIs for summarization and generation, you can use this unified setting. This option is ignored when setting the API to be used by summarization and generation separately",
)
@click.option(
    "--sum-api",
    default=None,
    type=str,
    required=False,
    help="The LLMS API aliases used for summarization. When used, it will invalidate --llms-api",
)
@click.option(
    "--gen-api",
    default=None,
    type=str,
    required=False,
    help="The LLMS API aliases used for generation. When used, it will invalidate --llms-api",
)
@click.option(
    "-o",
    "--output",
    default=get_dir("./output/out.json"),
    type=click.File("wb"),
    required=True,
    help="Dataset configuration file in YAML",
)
def local(config_path, year, venue_name, output, **kwargs):
    # Configuration
    output_path = output.name
    if not os.path.exists(os.path.dirname(output_path)):
        os.makedirs(os.path.dirname(output_path))
    config = ConfigReader.load(config_path, output_path=output_path, **kwargs)
    pm = PaperManager(config, venue_name, year)
    pm.update_paper_from_json_to_json(
        need_download=True, need_parse=True, need_summary=True, need_ground_truth=True
    )


@main.command()
@click.option(
    "-c",
    "--config-path",
    default=get_dir("./configs/datasets.yaml"),
    type=click.File(),
    required=True,
    help="Dataset configuration file in YAML",
)
def embedding(config_path):
    # Configuration
    config = ConfigReader.load(config_path)
    PaperManager(config).insert_embedding()


if __name__ == "__main__":
    main()