-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
1694 lines (1390 loc) · 68.8 KB
/
Copy pathmain.py
File metadata and controls
1694 lines (1390 loc) · 68.8 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
#!/usr/bin/env python3
"""
🚀 Research Paper Extractor v2.0.0 — Modern Research Toolkit
Available Commands:
search Search arXiv and Semantic Scholar
shell NEW: Interactive persistent session
recommend NEW: Activity-based suggestions
compare NEW: Side-by-side paper analysis
grep-pdf NEW: Search text inside downloaded PDFs
library Manage local library (add/list/tag/rate/note/export)
digest Generate daily research digest (MD/HTML)
analyze Run analytics with visualizations
summarize Show RAKE key-point summary
watch Manage the keyword/author watchlist
check-alerts Fetch new papers for all subscriptions
citations Look up Semantic Scholar citation counts
related Find related papers for a given arXiv ID
categories FULL LIST of arXiv categories
config Manage CLI settings (Themes, URLs)
open Open paper in browser
"""
import click
import sys
import os
from pathlib import Path
from typing import List, Optional
import logging
from research_paper_extractor.arxiv_api import ArxivAPI, ArxivPaper
from research_paper_extractor.downloader import PaperDownloader
from research_paper_extractor.config import DEFAULT_MAX_RESULTS, ARXIV_CATEGORIES
# ── Feature imports ────────────────────────────────────────────────────────────
from research_paper_extractor.citation_exporter import (
export_citations, EXPORT_FORMATS, FORMAT_EXTENSIONS
)
from research_paper_extractor.analytics import analyze_papers, format_analytics_report
from research_paper_extractor.summarizer import summarize_paper
from research_paper_extractor.watchlist import (
add_keyword, remove_keyword, add_author, remove_author,
list_watchlist, clear_watchlist, check_for_new_papers, format_watchlist_results
)
from research_paper_extractor.library import PaperLibrary
from research_paper_extractor.batch_downloader import (
resolve_batch, create_sample_batch_file
)
from research_paper_extractor.digest import generate_digest, save_digest
from research_paper_extractor.citations import (
get_citation_count, enrich_papers_with_citations, format_citation_table
)
from research_paper_extractor.related_papers import find_related_papers, format_related_papers
from research_paper_extractor.pdf_manager import PDFManager
from research_paper_extractor.history import SearchHistory
from research_paper_extractor.semantic_scholar import SemanticScholarAPI
from research_paper_extractor.webhooks import WebhookManager
from research_paper_extractor.comparison import PaperComparator
from research_paper_extractor.recommender import Recommender
from research_paper_extractor.shell import InteractiveShell
from research_paper_extractor.utils import themed_header, themed_print
from research_paper_extractor import config_manager
from research_paper_extractor.bibtex_parser import parse_bibtex_file, bib_entry_to_paper_obj
# Set up logging
logging.basicConfig(
level=logging.WARNING, # Quieter default — only show warnings+
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger(__name__)
# ══════════════════════════════════════════════════════════════════════════════
# CLI Root
# ══════════════════════════════════════════════════════════════════════════════
@click.group()
@click.version_option(version='2.0.0')
def cli():
"""ArXiv Paper Downloader v2.0 — Search, download, and manage research papers."""
pass
# ══════════════════════════════════════════════════════════════════════════════
# EXISTING COMMANDS (unchanged API, minor improvements)
# ══════════════════════════════════════════════════════════════════════════════
@cli.command()
@click.argument('query', required=True)
@click.option('--max-results', '-n', default=None, type=int,
help=f'Maximum papers to find (default: from config)')
@click.option('--download-dir', '-d', default=None,
help='Directory to download papers (default: from config)')
@click.option('--categories', '-c', multiple=True,
help='arXiv categories to search in (e.g., cs.AI, cs.LG)')
@click.option('--sort-by', default='relevance',
type=click.Choice(['relevance', 'lastUpdatedDate', 'submittedDate']),
help='Sort results by (default: relevance)')
@click.option('--preview-only', '-p', is_flag=True,
help='Only preview results without downloading')
@click.option('--auto-download', '-a', is_flag=True,
help='Automatically download all found papers without confirmation')
@click.option('--recent-days', type=int, default=None,
help='Only show papers from the last N days')
@click.option('--add-to-library', '-l', is_flag=True,
help='Add search results to your local library')
@click.option('--manifest', '-m', is_flag=True,
help='Save a JSON manifest file after downloading')
@click.option('--source', '-s', default='arxiv', type=click.Choice(['arxiv', 'semantic_scholar', 'both']),
help='Search source (default: arxiv)')
def search(query: str, max_results: Optional[int], download_dir: Optional[str],
categories: tuple, sort_by: str, preview_only: bool,
auto_download: bool, recent_days: Optional[int], add_to_library: bool,
manifest: bool, source: str):
"""Search and download papers from arXiv based on a query."""
try:
api = ArxivAPI()
_max = max_results or config_manager.get_max_results_from_config()
_dir = download_dir or config_manager.get_download_dir_from_config()
downloader = PaperDownloader(_dir, topic=query)
click.echo(f"Searching arXiv for: '{query}'")
if categories:
click.echo(f"Categories: {', '.join(categories)}")
# Validate categories
valid_categories = list(ARXIV_CATEGORIES.keys())
invalid_cats = [cat for cat in categories if cat not in valid_categories]
if invalid_cats:
click.echo(f"Warning: Invalid categories: {', '.join(invalid_cats)}")
categories = tuple(cat for cat in categories if cat in valid_categories)
# Search
papers = []
themed_header(f"Searching for: {query}")
if source in ['arxiv', 'both']:
click.echo(f"Searching arXiv for: '{query}'")
if recent_days:
papers.extend(api.search_recent(query, days=recent_days, max_results=_max))
else:
papers.extend(api.search(
query=query, max_results=_max,
categories=list(categories) if categories else None,
sort_by=sort_by
))
if source in ['semantic_scholar', 'both']:
ss_api = SemanticScholarAPI()
ss_papers = ss_api.search(query, max_results=_max)
click.echo(f"Found {len(ss_papers)} papers on Semantic Scholar")
papers.extend(ss_papers)
# Log to history
hist = SearchHistory()
hist.add_entry(query, filters={"categories": categories, "sort_by": sort_by}, results_count=len(papers))
if not papers:
click.echo("No papers found matching your query.")
return
click.echo(downloader.get_paper_info_summary(papers))
# Optionally add to library
if add_to_library:
lib = PaperLibrary()
added = sum(1 for p in papers if lib.add_paper(p))
click.echo(f"Added {added} new paper(s) to your library.")
if preview_only:
click.echo("Preview mode — no papers downloaded.")
return
if auto_download or click.confirm(f"\nDownload {len(papers)} papers?"):
click.echo("\nStarting downloads...")
downloaded_files = downloader.download_papers(papers)
click.echo(downloader.create_download_summary(downloaded_files))
if downloaded_files:
click.echo("Download completed successfully!")
if manifest:
mpath = downloader.save_download_manifest(papers, downloaded_files)
click.echo(f"Manifest saved: {mpath}")
if add_to_library:
lib = PaperLibrary()
for p, fp in zip(papers, downloaded_files):
lib.set_file_path(p.id, fp)
else:
click.echo("No papers were downloaded.")
else:
click.echo("Download cancelled.")
except Exception as e:
logger.error(f"Error during search: {e}")
click.echo(f"Error: {e}", err=True)
sys.exit(1)
@cli.command()
@click.argument('arxiv_id', required=True)
@click.option('--download-dir', '-d', default=None,
help='Directory to download paper (default: ./downloads)')
@click.option('--filename', '-f', default=None,
help='Custom filename for the download (without extension)')
@click.option('--add-to-library', '-l', is_flag=True,
help='Add paper to your local library after download')
def download_by_id(arxiv_id: str, download_dir: Optional[str],
filename: Optional[str], add_to_library: bool):
"""Download a specific paper by its arXiv ID."""
try:
api = ArxivAPI()
_dir = download_dir or config_manager.get_download_dir_from_config()
downloader = PaperDownloader(_dir, topic=f"paper_{arxiv_id}")
click.echo(f"Looking up arXiv paper: {arxiv_id}")
paper = api.get_paper_by_id(arxiv_id)
if not paper:
click.echo(f"Paper with ID '{arxiv_id}' not found.")
return
click.echo(f"\nFound paper:")
click.echo(f" Title: {paper.title}")
click.echo(f" Authors: {', '.join(paper.authors)}")
click.echo(f" Published: {paper.published.strftime('%Y-%m-%d')}")
click.echo(f" Categories: {', '.join(paper.categories)}")
if add_to_library:
lib = PaperLibrary()
lib.add_paper(paper)
click.echo(" Added to library.")
if click.confirm(f"\nDownload this paper?"):
click.echo("\nStarting download...")
filepath = downloader.download_paper(paper, filename)
if filepath:
click.echo(f"Downloaded successfully: {filepath}")
if add_to_library:
PaperLibrary().set_file_path(paper.id, filepath)
else:
click.echo("Download failed.")
else:
click.echo("Download cancelled.")
except Exception as e:
logger.error(f"Error downloading paper: {e}")
click.echo(f"Error: {e}", err=True)
sys.exit(1)
@cli.command()
@click.argument('author_name', required=True)
@click.option('--max-results', '-n', default=None, type=int,
help='Maximum number of papers to find (default: from config)')
@click.option('--download-dir', '-d', default=None,
help='Directory to download papers (default: ./downloads)')
@click.option('--preview-only', '-p', is_flag=True,
help='Only preview results without downloading')
def search_by_author(author_name: str, max_results: Optional[int],
download_dir: Optional[str], preview_only: bool):
"""Search for papers by a specific author."""
try:
api = ArxivAPI()
_max = max_results or config_manager.get_max_results_from_config()
_dir = download_dir or config_manager.get_download_dir_from_config()
downloader = PaperDownloader(_dir, topic=f"author_{author_name}")
click.echo(f"Searching papers by author: {author_name}")
papers = api.search_by_author(author_name, _max)
if not papers:
click.echo(f"No papers found for author '{author_name}'.")
return
click.echo(downloader.get_paper_info_summary(papers))
if preview_only:
click.echo("Preview mode — no papers downloaded.")
return
if click.confirm(f"\nDownload {len(papers)} papers?"):
click.echo("\nStarting downloads...")
downloaded_files = downloader.download_papers(papers)
click.echo(downloader.create_download_summary(downloaded_files))
if downloaded_files:
click.echo("Download completed successfully!")
else:
click.echo("No papers were downloaded.")
else:
click.echo("Download cancelled.")
except Exception as e:
logger.error(f"Error searching by author: {e}")
click.echo(f"Error: {e}", err=True)
sys.exit(1)
@cli.command()
def categories():
"""List available arXiv categories."""
click.echo("Available arXiv categories:\n")
for category, description in ARXIV_CATEGORIES.items():
click.echo(f" {category:<15} - {description}")
click.echo(f"\nUse with --categories/-c option")
click.echo(f" Example: python main.py search 'machine learning' -c cs.LG -c cs.AI")
@cli.command()
@click.option('--query', '-q', prompt=True, help='Search query')
@click.option('--max-results', '-n', default=None, type=int,
help='Maximum number of papers')
@click.option('--download-dir', '-d', default=None, help='Download directory')
def interactive(query: str, max_results: Optional[int], download_dir: Optional[str]):
"""Interactive mode for searching and downloading papers."""
try:
api = ArxivAPI()
_max = max_results or config_manager.get_max_results_from_config()
_dir = download_dir or config_manager.get_download_dir_from_config()
downloader = PaperDownloader(_dir, topic=f"interactive_{query}")
while True:
click.echo(f"\nSearching for: '{query}'")
papers = api.search(query, max_results=_max)
if not papers:
click.echo("No papers found.")
if click.confirm("Try a different search?"):
query = click.prompt("Enter new search query")
downloader = PaperDownloader(_dir, topic=f"interactive_{query}")
continue
break
click.echo(f"\nFound {len(papers)} papers:")
for i, paper in enumerate(papers, 1):
click.echo(f"\n{i}. {paper.title}")
click.echo(f" Authors: {', '.join(paper.authors[:2])}")
if len(paper.authors) > 2:
click.echo(f" and {len(paper.authors) - 2} others")
click.echo(f" ID: {paper.id} | Published: {paper.published.strftime('%Y-%m-%d')}")
click.echo(f"\nOptions:")
click.echo(f" 'all' - Download all papers")
click.echo(f" '1,3,5' - Download specific papers by number")
click.echo(f" 'none' - Don't download anything")
click.echo(f" 'new' - New search")
choice = click.prompt("What would you like to do?", default="none").strip().lower()
if choice == "none":
click.echo("No downloads.")
elif choice == "all":
downloaded_files = downloader.download_papers(papers)
click.echo(downloader.create_download_summary(downloaded_files))
elif choice == "new":
query = click.prompt("Enter new search query")
downloader = PaperDownloader(_dir, topic=f"interactive_{query}")
continue
else:
try:
indices = [int(x.strip()) - 1 for x in choice.split(',')]
selected = [papers[i] for i in indices if 0 <= i < len(papers)]
if selected:
downloaded_files = downloader.download_papers(selected)
click.echo(downloader.create_download_summary(downloaded_files))
else:
click.echo("Invalid paper numbers.")
except ValueError:
click.echo("Invalid format. Use numbers separated by commas (e.g., '1,3,5')")
if not click.confirm("\nContinue searching?"):
break
click.echo("\nGoodbye!")
except KeyboardInterrupt:
click.echo("\n\nGoodbye!")
except Exception as e:
logger.error(f"Error in interactive mode: {e}")
click.echo(f"Error: {e}", err=True)
sys.exit(1)
# ══════════════════════════════════════════════════════════════════════════════
# FEATURE 1 — Citation Export
# ══════════════════════════════════════════════════════════════════════════════
@cli.command()
@click.argument('query', required=True)
@click.option('--format', '-f', 'fmt',
type=click.Choice(list(EXPORT_FORMATS.keys())),
default='bibtex', show_default=True,
help='Citation export format')
@click.option('--max-results', '-n', default=None, type=int,
help='Max papers to include')
@click.option('--output', '-o', default=None,
help='Output file path (default: print to stdout)')
@click.option('--categories', '-c', multiple=True,
help='arXiv categories to filter')
def export(query: str, fmt: str, max_results: Optional[int],
output: Optional[str], categories: tuple):
"""Export paper citations in BibTeX, RIS, APA, or plain text format.
\b
Examples:
python main.py export "transformers NLP" -f bibtex -o refs.bib
python main.py export "graph neural networks" -f apa
"""
try:
api = ArxivAPI()
_max = max_results or config_manager.get_max_results_from_config()
click.echo(f"Searching: '{query}'...")
papers = api.search(
query=query, max_results=_max,
categories=list(categories) if categories else None,
)
if not papers:
click.echo("No papers found.")
return
click.echo(f"Exporting {len(papers)} papers as {fmt.upper()}...")
citation_text = export_citations(papers, fmt=fmt)
if output:
out_path = Path(output)
ext = FORMAT_EXTENSIONS[fmt]
if not output.endswith(ext):
out_path = Path(output + ext)
out_path.write_text(citation_text, encoding='utf-8')
click.echo(f"Citations saved to: {out_path}")
else:
click.echo('\n' + citation_text)
except Exception as e:
click.echo(f"Error: {e}", err=True)
sys.exit(1)
# ══════════════════════════════════════════════════════════════════════════════
# FEATURE 2 — Analytics
# ══════════════════════════════════════════════════════════════════════════════
@cli.command()
@click.argument('query', required=True)
@click.option('--max-results', '-n', default=50, show_default=True,
help='Number of papers to analyze')
@click.option('--categories', '-c', multiple=True, help='arXiv categories to filter')
@click.option('--output', '-o', default=None,
help='Save report to this file path')
def analyze(query: str, max_results: int, categories: tuple, output: Optional[str]):
"""Run analytics on arXiv search results.
Shows statistics on authors, categories, publication years, and keywords.
\b
Example:
python main.py analyze "deep learning" -n 100
"""
try:
api = ArxivAPI()
click.echo(f"Fetching {max_results} papers for analysis: '{query}'...")
papers = api.search(
query=query, max_results=max_results,
categories=list(categories) if categories else None,
)
if not papers:
click.echo("No papers found.")
return
stats = analyze_papers(papers)
report = format_analytics_report(stats)
click.echo(report)
if output:
Path(output).write_text(report, encoding='utf-8')
click.echo(f"\nReport saved to: {output}")
except Exception as e:
click.echo(f"Error: {e}", err=True)
sys.exit(1)
# ══════════════════════════════════════════════════════════════════════════════
# FEATURE 3 — Summarize
# ══════════════════════════════════════════════════════════════════════════════
@cli.command()
@click.argument('arxiv_id_or_query', required=True)
@click.option('--sentences', '-s', default=3, show_default=True,
help='Number of key sentences to extract')
@click.option('--keywords', '-k', default=8, show_default=True,
help='Number of keywords to show')
@click.option('--is-query', '-q', is_flag=True,
help='Treat argument as a search query instead of an arXiv ID')
@click.option('--max-results', '-n', default=None, type=int,
help='Max results when using --is-query')
def summarize(arxiv_id_or_query: str, sentences: int, keywords: int,
is_query: bool, max_results: Optional[int]):
"""Show a TF-IDF key-point summary of paper abstract(s).
\b
Examples:
python main.py summarize 2301.07041
python main.py summarize "attention mechanism" --is-query -n 3
"""
try:
api = ArxivAPI()
papers: List[ArxivPaper] = []
if is_query:
_max = max_results or 5
click.echo(f"Searching: '{arxiv_id_or_query}'...")
papers = api.search(arxiv_id_or_query, max_results=_max)
else:
paper = api.get_paper_by_id(arxiv_id_or_query)
if paper:
papers = [paper]
if not papers:
click.echo("No papers found.")
return
for paper in papers:
click.echo('\n' + '─' * 65)
click.echo(summarize_paper(paper, max_sentences=sentences, top_keywords=keywords))
click.echo('─' * 65)
except Exception as e:
click.echo(f"Error: {e}", err=True)
sys.exit(1)
# ══════════════════════════════════════════════════════════════════════════════
# FEATURE 4 — Watchlist management
# ══════════════════════════════════════════════════════════════════════════════
@cli.group()
def watch():
"""Manage your keyword/author watchlist for new paper alerts."""
pass
@watch.command('add-keyword')
@click.argument('keyword', required=True)
def watch_add_keyword(keyword: str):
"""Add a keyword to your watchlist."""
if add_keyword(keyword):
click.echo(f"✓ Added keyword: '{keyword}'")
else:
click.echo(f"Keyword '{keyword}' is already in your watchlist.")
@watch.command('remove-keyword')
@click.argument('keyword', required=True)
def watch_remove_keyword(keyword: str):
"""Remove a keyword from your watchlist."""
if remove_keyword(keyword):
click.echo(f"✓ Removed keyword: '{keyword}'")
else:
click.echo(f"Keyword '{keyword}' not found in watchlist.")
@watch.command('add-author')
@click.argument('author', required=True)
def watch_add_author(author: str):
"""Add an author to your watchlist."""
if add_author(author):
click.echo(f"✓ Added author: '{author}'")
else:
click.echo(f"Author '{author}' is already in your watchlist.")
@watch.command('remove-author')
@click.argument('author', required=True)
def watch_remove_author(author: str):
"""Remove an author from your watchlist."""
if remove_author(author):
click.echo(f"✓ Removed author: '{author}'")
else:
click.echo(f"Author '{author}' not found in watchlist.")
@watch.command('list')
def watch_list():
"""Show your current watchlist."""
data = list_watchlist()
click.echo("\n── Watchlist ─────────────────────────────")
if data['keywords']:
click.echo("Keywords:")
for kw in data['keywords']:
click.echo(f" • {kw}")
else:
click.echo("Keywords: (none)")
if data['authors']:
click.echo("Authors:")
for au in data['authors']:
click.echo(f" • {au}")
else:
click.echo("Authors: (none)")
lc = data.get('last_check')
click.echo(f"\nLast checked: {lc[:16] if lc else 'never'}")
click.echo("──────────────────────────────────────────")
@watch.command('clear')
@click.confirmation_option(prompt='Clear all watchlist entries?')
def watch_clear():
"""Clear all entries from your watchlist."""
clear_watchlist()
click.echo("Watchlist cleared.")
@cli.group()
def webhook():
"""Manage notification webhooks (Discord/Slack)."""
pass
@webhook.command('set')
@click.argument('url', required=True)
def webhook_set(url: str):
"""Set the Discord/Slack webhook URL."""
from research_paper_extractor import config_manager
config_manager.set_value('notifications', 'webhook_url', url)
click.echo(f"✓ Webhook URL updated successfully.")
@webhook.command('test')
def webhook_test():
"""Send a test message to your configured webhook."""
from research_paper_extractor import config_manager
from research_paper_extractor.webhooks import WebhookManager
url = config_manager.get('notifications', 'webhook_url')
if not url:
click.echo("Error: No webhook URL configured. Use 'webhook set <URL>' first.")
return
click.echo(f"Sending test message to {url[:40]}...")
wm = WebhookManager(url)
if wm.send_simple_message("🚀 This is a test notification from Research Paper Extractor v2.0.0!"):
click.echo("✓ Test message sent successfully!")
else:
click.echo("Error: Failed to send test message. Check your URL and connection.", err=True)
@webhook.command('clear')
def webhook_clear():
"""Remove the configured webhook URL."""
from research_paper_extractor import config_manager
config_manager.set_value('notifications', 'webhook_url', '')
click.echo("✓ Webhook URL cleared.")
# ══════════════════════════════════════════════════════════════════════════════
# FEATURE 5 — Check alerts
# ══════════════════════════════════════════════════════════════════════════════
@cli.command('check-alerts')
@click.option('--days', '-d', default=7, show_default=True,
help='Check for papers published in the last N days')
@click.option('--max-per-query', '-n', default=10, show_default=True,
help='Max results per keyword/author')
@click.option('--download', is_flag=True,
help='Download found papers automatically')
@click.option('--download-dir', default=None, help='Download directory')
def check_alerts(days: int, max_per_query: int, download: bool,
download_dir: Optional[str]):
"""Check your watchlist for new papers since last check.
\b
Example:
python main.py check-alerts --days 3
"""
try:
wl = list_watchlist()
if not wl['keywords'] and not wl['authors']:
click.echo("Your watchlist is empty. Use 'watch add-keyword' to add entries.")
return
click.echo(f"Checking for new papers (last {days} days)...")
results = check_for_new_papers(days=days, max_per_query=max_per_query)
click.echo(format_watchlist_results(results))
# Webhook Notification
webhook_url = config_manager.get('notifications', 'webhook_url')
if webhook_url and results:
wm = WebhookManager(webhook_url)
all_papers = [p for papers in results.values() for p in papers]
click.echo("Sending webhook notification...")
wm.send_notification("New Research Papers Alert",
f"Found {len(all_papers)} new papers in your watchlist.",
all_papers)
if download and results:
all_papers = [p for papers in results.values() for p in papers]
if click.confirm(f"\nDownload all {len(all_papers)} found papers?"):
_dir = download_dir or config_manager.get_download_dir_from_config()
downloader = PaperDownloader(_dir, topic='watchlist_alerts')
downloaded = downloader.download_papers(all_papers)
click.echo(downloader.create_download_summary(downloaded))
except Exception as e:
click.echo(f"Error: {e}", err=True)
sys.exit(1)
# ══════════════════════════════════════════════════════════════════════════════
# FEATURE 6 — Library management
# ══════════════════════════════════════════════════════════════════════════════
@cli.group()
def library():
"""Manage your local paper library (SQLite-backed)."""
pass
@library.command('add')
@click.argument('arxiv_id', required=True)
def library_add(arxiv_id: str):
"""Add a paper to your library by arXiv ID."""
api = ArxivAPI()
paper = api.get_paper_by_id(arxiv_id)
if not paper:
click.echo(f"Paper '{arxiv_id}' not found on arXiv.")
return
lib = PaperLibrary()
if lib.add_paper(paper):
click.echo(f"✓ Added: {paper.title[:60]}")
else:
click.echo("Paper is already in your library.")
@library.command('list')
@click.option('--unread', 'filter_read', flag_value=False, default=None,
help='Show only unread papers')
@click.option('--read', 'filter_read', flag_value=True,
help='Show only read papers')
@click.option('--tag', default=None, help='Filter by tag')
@click.option('--rating', default=None, type=int,
help='Filter by minimum star rating (1-5)')
@click.option('--limit', '-n', default=50, show_default=True)
def library_list(filter_read, tag, rating, limit):
"""List papers in your library."""
lib = PaperLibrary()
papers = lib.list_papers(read=filter_read, tag=tag, rating=rating, limit=limit)
click.echo(lib.format_library_list(papers))
stats = lib.get_stats()
click.echo(f"\nLibrary: {stats['total']} total | "
f"{stats['read']} read | {stats['unread']} unread")
@library.command('mark-read')
@click.argument('arxiv_id', required=True)
@click.option('--unread', is_flag=True, help='Mark as unread instead')
def library_mark_read(arxiv_id: str, unread: bool):
"""Mark a paper as read or unread."""
lib = PaperLibrary()
if lib.mark_read(arxiv_id, read=not unread):
status = 'unread' if unread else 'read'
click.echo(f"✓ Marked {arxiv_id} as {status}.")
else:
click.echo(f"Paper '{arxiv_id}' not found in library.")
@library.command('rate')
@click.argument('arxiv_id', required=True)
@click.argument('rating', type=click.IntRange(1, 5))
def library_rate(arxiv_id: str, rating: int):
"""Rate a paper 1-5 stars."""
lib = PaperLibrary()
if lib.set_rating(arxiv_id, rating):
click.echo(f"✓ Rated {arxiv_id}: {'★' * rating}{'☆' * (5 - rating)}")
else:
click.echo(f"Paper '{arxiv_id}' not found in library.")
@library.command('note')
@click.argument('arxiv_id', required=True)
@click.argument('note', required=True)
def library_note(arxiv_id: str, note: str):
"""Add or update a personal note for a paper."""
lib = PaperLibrary()
if lib.add_note(arxiv_id, note):
click.echo(f"✓ Note saved for {arxiv_id}.")
else:
click.echo(f"Paper '{arxiv_id}' not found in library.")
@library.command('tag')
@click.argument('arxiv_id', required=True)
@click.argument('tag', required=True)
def library_tag(arxiv_id: str, tag: str):
"""Add a tag to a library paper."""
lib = PaperLibrary()
if lib.add_tag(arxiv_id, tag):
click.echo(f"✓ Added tag '{tag}' to {arxiv_id}.")
else:
click.echo(f"Paper '{arxiv_id}' not found in library.")
@library.command('bulk-tag')
@click.argument('tag', required=True)
@click.argument('arxiv_ids', nargs=-1, required=True)
def library_bulk_tag(tag, arxiv_ids):
"""Add a tag to multiple library papers at once."""
lib = PaperLibrary()
count = lib.add_tags_bulk(list(arxiv_ids), tag)
click.echo(f"✓ Added tag '{tag}' to {count} paper(s).")
@library.command('untag')
@click.argument('arxiv_id', required=True)
@click.argument('tag', required=True)
def library_untag(arxiv_id: str, tag: str):
"""Remove a tag on a library paper (alias for tag --remove)."""
lib = PaperLibrary()
if lib.remove_tag(arxiv_id, tag):
click.echo(f"✓ Removed tag '{tag}' from {arxiv_id}.")
else:
click.echo(f"Paper '{arxiv_id}' or tag '{tag}' not found.")
@library.command('tags')
def library_tags():
"""List all unique tags in your library."""
lib = PaperLibrary()
tags = lib.get_all_tags()
if not tags:
click.echo("No tags found in your library.")
return
click.echo("\n── Library Tags ──────────────────────────")
for t in tags:
# Count papers with this tag
papers = lib.list_papers(tag=t, limit=1000)
click.echo(f" • {t:<20} ({len(papers)} papers)")
click.echo("──────────────────────────────────────────")
@library.command('remove')
@click.argument('arxiv_id', required=True)
@click.confirmation_option(prompt='Remove this paper from your library?')
def library_remove(arxiv_id: str):
"""Remove a paper from your library."""
lib = PaperLibrary()
if lib.remove_paper(arxiv_id):
click.echo(f"✓ Removed {arxiv_id} from library.")
else:
click.echo(f"Paper '{arxiv_id}' not found in library.")
@library.command('stats')
def library_stats():
"""Show library statistics."""
lib = PaperLibrary()
stats = lib.get_stats()
click.echo("\n── Library Statistics ────────────────────")
click.echo(f" Total papers : {stats['total']}")
click.echo(f" Read : {stats['read']}")
click.echo(f" Unread : {stats['unread']}")
click.echo(f" Rated papers : {stats['rated']}")
if stats['avg_rating']:
click.echo(f" Avg rating : {stats['avg_rating']:.1f} / 5.0")
click.echo("─────────────────────────────────────────")
@library.command('export')
@click.argument('filename', required=True)
@click.option('--format', '-f', type=click.Choice(['csv', 'json', 'bibtex']), default='csv', show_default=True)
def library_export(filename, format):
"""Export the entire paper library to CSV, JSON, or BibTeX."""
lib = PaperLibrary()
# Ensure extension
ext = format if format != 'bibtex' else 'bib'
if not filename.endswith(f".{ext}"):
filename += f".{ext}"
click.echo(f"Exporting library to {filename} ({format.upper()})...")
success = False
if format == 'csv':
success = lib.export_to_csv(filename)
elif format == 'json':
success = lib.export_to_json(filename)
else:
success = lib.export_to_bibtex(filename)
if success:
click.echo(f"✓ Library exported successfully to: {filename}")
else:
click.echo("Error: Could not export library (is it empty?)", err=True)
@library.command('export-md')
@click.argument('output_dir', type=click.Path())
@click.option('--tag', '-t', default=None, help='Filter papers by tag')
def library_export_md(output_dir: str, tag: Optional[str]):
"""Export papers to Markdown files (Obsidian/Notion compatible)."""
from research_paper_extractor.markdown_exporter import export_library_to_markdown
lib = PaperLibrary()
papers = lib.list_papers(tag=tag, limit=10000)
if not papers:
click.echo("No papers found matching the filter.")
return
click.echo(f"Exporting {len(papers)} papers to {output_dir}...")
count = export_library_to_markdown(papers, output_dir)
click.echo(f"✓ successfully exported {count} papers as Markdown.")
@library.command('import-bib')
@click.argument('bib_file', type=click.Path(exists=True))
@click.option('--fetch-metadata', '-f', is_flag=True, help='Fetch full metadata from arXiv for each ID')
def library_import_bib(bib_file: str, fetch_metadata: bool):
"""Import papers from a .bib file into your library."""
from research_paper_extractor.bibtex_parser import parse_bibtex_file, bib_entry_to_paper_obj
entries = parse_bibtex_file(bib_file)
if not entries:
click.echo(f"No valid arXiv entries found in {bib_file}.")
return
click.echo(f"Found {len(entries)} candidate papers in BibTeX file.")
lib = PaperLibrary()
api = ArxivAPI()
added_count = 0
with click.progressbar(entries, label='Importing papers') as bar:
for entry in bar:
arxiv_id = entry.get('arxiv_id')
if not arxiv_id:
continue
paper = None
if fetch_metadata:
try:
paper = api.get_paper_by_id(arxiv_id)
except Exception:
pass
if not paper:
# Use metadata from BibTeX
mock_entry = bib_entry_to_paper_obj(entry)
if mock_entry:
paper = ArxivPaper(mock_entry)
if paper:
if lib.add_paper(paper):
added_count += 1
click.echo(f"✓ Successfully imported {added_count} new papers to library.")
@library.command('sync-metadata')
@click.option('--arxiv-id', '-i', default=None, help='Sync metadata for a specific arXiv ID')
@click.option('--all', 'sync_all', is_flag=True, help='Sync metadata for all papers in library')
def library_sync_metadata(arxiv_id: Optional[str], sync_all: bool):
"""Sync citation counts and metadata for papers from Semantic Scholar."""
from research_paper_extractor.citations import get_citation_count
from datetime import datetime, timezone
lib = PaperLibrary()
if arxiv_id:
papers_to_sync = [lib.get_paper(arxiv_id)] if lib.get_paper(arxiv_id) else []
elif sync_all:
papers_to_sync = lib.list_papers(limit=1000)
else:
click.echo("Please specify --arxiv-id or --all.")
return
if not papers_to_sync:
click.echo("No papers found to sync.")
return
click.echo(f"Syncing {len(papers_to_sync)} papers...")
synced_count = 0
with click.progressbar(papers_to_sync, label='Syncing metadata') as bar:
for p in bar:
aid = p.get('arxiv_id')
if not aid:
continue
citations = get_citation_count(aid)
if citations:
metadata = {
'citation_count': citations['citation_count'],
'last_synced': datetime.now(timezone.utc).isoformat()
}
if lib.update_paper_metadata(aid, metadata):
synced_count += 1
click.echo(f"✓ Finished syncing metadata for {synced_count} paper(s).")