2022-12-22 16:43:06 +00:00
|
|
|
import os
|
|
|
|
import argparse
|
|
|
|
|
|
|
|
import fitz
|
2022-12-22 21:31:21 +00:00
|
|
|
import Levenshtein
|
2022-12-22 16:43:06 +00:00
|
|
|
|
2022-12-22 17:57:41 +00:00
|
|
|
from pubs.plugins import PapersPlugin
|
2022-12-22 19:28:27 +00:00
|
|
|
from pubs.events import DocAddEvent, NoteEvent
|
2022-12-24 13:34:18 +00:00
|
|
|
from pubs import repo, pretty
|
2022-12-22 17:57:41 +00:00
|
|
|
from pubs.utils import resolve_citekey_list
|
2022-12-22 19:52:10 +00:00
|
|
|
from pubs.content import check_file, read_text_file, write_file
|
2022-12-24 13:23:07 +00:00
|
|
|
from pubs.query import get_paper_filter
|
2022-12-25 11:17:05 +00:00
|
|
|
from .annotation import (
|
|
|
|
PaperAnnotated,
|
|
|
|
Annotation,
|
|
|
|
COLOR_SIMILARITY_MINIMUM,
|
|
|
|
TEXT_SIMILARITY_MINIMUM,
|
|
|
|
)
|
2022-12-24 13:23:07 +00:00
|
|
|
|
2022-12-24 17:01:55 +00:00
|
|
|
CONFIRMATION_PAPER_THRESHOLD = 5
|
2022-12-24 23:18:11 +00:00
|
|
|
|
2022-12-24 17:37:36 +00:00
|
|
|
|
2022-12-22 16:43:06 +00:00
|
|
|
class ExtractPlugin(PapersPlugin):
|
2022-12-22 20:02:01 +00:00
|
|
|
"""Extract annotations from any pdf document.
|
|
|
|
|
|
|
|
The extract plugin allows manual or automatic extraction of all annotations
|
|
|
|
contained in the pdf documents belonging to entries of the pubs library.
|
2022-12-22 16:43:06 +00:00
|
|
|
|
2022-12-22 20:02:01 +00:00
|
|
|
It can write those changes to stdout or directly create and update notes
|
|
|
|
for the pubs entries.
|
2022-12-22 16:43:06 +00:00
|
|
|
|
2022-12-22 20:02:01 +00:00
|
|
|
It adds a `pubs extract` subcommand through which it is invoked, but can
|
|
|
|
optionally run whenever a new document is imported for a pubs entry.
|
2022-12-22 16:43:06 +00:00
|
|
|
"""
|
|
|
|
|
|
|
|
name = "extract"
|
|
|
|
description = "Extract annotations from pubs documents"
|
|
|
|
|
|
|
|
def __init__(self, conf, ui):
|
|
|
|
self.ui = ui
|
2022-12-22 20:10:42 +00:00
|
|
|
self.note_extension = conf["main"]["note_extension"]
|
2022-12-25 11:17:05 +00:00
|
|
|
self.max_authors = conf["main"]["max_authors"]
|
2022-12-22 16:43:06 +00:00
|
|
|
self.repository = repo.Repository(conf)
|
2022-12-22 17:32:11 +00:00
|
|
|
self.pubsdir = os.path.expanduser(conf["main"]["pubsdir"])
|
|
|
|
self.broker = self.repository.databroker
|
2022-12-22 17:34:33 +00:00
|
|
|
|
2022-12-24 16:01:06 +00:00
|
|
|
settings = conf["plugins"].get("extract", {})
|
|
|
|
self.on_import = settings.get("on_import", False)
|
2022-12-24 23:18:11 +00:00
|
|
|
self.minimum_similarity = float(
|
2022-12-24 23:31:35 +00:00
|
|
|
settings.get("minimum_text_similarity", TEXT_SIMILARITY_MINIMUM)
|
2022-12-24 23:18:11 +00:00
|
|
|
)
|
|
|
|
self.minimum_color_similarity = float(
|
|
|
|
settings.get("minimum_color_similarity", COLOR_SIMILARITY_MINIMUM)
|
|
|
|
)
|
2022-12-24 16:01:06 +00:00
|
|
|
self.formatting = settings.get(
|
|
|
|
"formatting",
|
2022-12-24 22:32:34 +00:00
|
|
|
"{%quote_container> {quote} %}[{page}]{%note_container{newline}Note: {note} %}{%tag_container #{tag}%}",
|
2022-12-22 22:21:13 +00:00
|
|
|
)
|
2022-12-24 23:33:08 +00:00
|
|
|
self.color_mapping = settings.get("tags", {})
|
2022-12-24 23:51:47 +00:00
|
|
|
self.short_header = settings.get("short_header", False)
|
2022-12-22 16:43:06 +00:00
|
|
|
|
2022-12-24 16:01:06 +00:00
|
|
|
def update_parser(self, subparsers, _):
|
2022-12-22 20:02:01 +00:00
|
|
|
"""Allow the usage of the pubs extract subcommand"""
|
2022-12-22 16:43:06 +00:00
|
|
|
# TODO option for ignoring missing documents or erroring.
|
|
|
|
extract_parser = subparsers.add_parser(self.name, help=self.description)
|
2022-12-22 17:33:33 +00:00
|
|
|
extract_parser.add_argument(
|
|
|
|
"-w",
|
|
|
|
"--write",
|
2022-12-22 19:52:10 +00:00
|
|
|
help="Write to individual notes instead of standard out. Appends to existing notes.",
|
2022-12-22 19:32:06 +00:00
|
|
|
action="store_true",
|
2022-12-22 17:33:33 +00:00
|
|
|
default=None,
|
|
|
|
)
|
2022-12-22 17:34:23 +00:00
|
|
|
extract_parser.add_argument(
|
|
|
|
"-e",
|
|
|
|
"--edit",
|
2022-12-22 19:52:10 +00:00
|
|
|
help="Open each note in editor for manual editing after extracting annotations to it.",
|
2022-12-22 19:32:06 +00:00
|
|
|
action="store_true",
|
2022-12-22 17:34:23 +00:00
|
|
|
default=False,
|
|
|
|
)
|
2022-12-24 13:23:07 +00:00
|
|
|
extract_parser.add_argument(
|
|
|
|
"-q",
|
|
|
|
"--query",
|
|
|
|
help="Query library instead of providing individual citekeys. For query help see pubs list command.",
|
|
|
|
action="store_true",
|
|
|
|
default=None,
|
|
|
|
dest="is_query",
|
|
|
|
)
|
|
|
|
extract_parser.add_argument(
|
|
|
|
"-i",
|
|
|
|
"--ignore-case",
|
|
|
|
action="store_false",
|
|
|
|
default=None,
|
|
|
|
dest="case_sensitive",
|
|
|
|
help="When using query mode, perform case insensitive search.",
|
|
|
|
)
|
|
|
|
extract_parser.add_argument(
|
|
|
|
"-I",
|
|
|
|
"--force-case",
|
|
|
|
action="store_true",
|
|
|
|
dest="case_sensitive",
|
|
|
|
help="When using query mode, perform case sensitive search.",
|
|
|
|
)
|
|
|
|
extract_parser.add_argument(
|
|
|
|
"--strict",
|
|
|
|
action="store_true",
|
|
|
|
default=False,
|
|
|
|
help="Force strict unicode comparison of query.",
|
|
|
|
)
|
|
|
|
extract_parser.add_argument(
|
|
|
|
"query",
|
|
|
|
nargs=argparse.REMAINDER,
|
|
|
|
help="Citekey(s)/query for the documents to extract from.",
|
|
|
|
)
|
2022-12-22 16:43:06 +00:00
|
|
|
extract_parser.set_defaults(func=self.command)
|
|
|
|
|
|
|
|
def command(self, conf, args):
|
2022-12-22 20:02:01 +00:00
|
|
|
"""Run the annotation extraction command."""
|
2022-12-24 13:23:07 +00:00
|
|
|
papers = self._gather_papers(conf, args)
|
|
|
|
all_annotations = self.extract(papers)
|
2022-12-22 17:33:33 +00:00
|
|
|
if args.write:
|
2022-12-22 20:10:42 +00:00
|
|
|
self._to_notes(all_annotations, self.note_extension, args.edit)
|
2022-12-22 17:33:33 +00:00
|
|
|
else:
|
2022-12-24 23:51:47 +00:00
|
|
|
self._to_stdout(all_annotations, self.short_header)
|
2022-12-22 17:34:33 +00:00
|
|
|
self.repository.close()
|
2022-12-22 16:43:06 +00:00
|
|
|
|
2022-12-24 13:23:07 +00:00
|
|
|
def extract(self, papers):
|
2022-12-22 20:02:01 +00:00
|
|
|
"""Extracts annotations from citekeys.
|
|
|
|
|
|
|
|
Returns all annotations belonging to the papers that
|
|
|
|
are described by the citekeys passed in.
|
|
|
|
"""
|
2022-12-25 11:17:05 +00:00
|
|
|
papers_annotated = []
|
2022-12-22 16:43:06 +00:00
|
|
|
for paper in papers:
|
2022-12-22 17:57:41 +00:00
|
|
|
file = self._get_file(paper)
|
2022-12-22 16:43:06 +00:00
|
|
|
try:
|
2022-12-25 11:17:05 +00:00
|
|
|
annotations = self._get_annotations(file)
|
|
|
|
papers_annotated.append(PaperAnnotated.from_paper(paper, annotations))
|
2022-12-22 16:43:06 +00:00
|
|
|
except fitz.FileDataError as e:
|
2022-12-22 18:39:36 +00:00
|
|
|
self.ui.error(f"Document {file} is broken: {e}")
|
2022-12-22 16:43:06 +00:00
|
|
|
return papers_annotated
|
|
|
|
|
2022-12-24 17:37:36 +00:00
|
|
|
def tag_from_colorname(self, colorname):
|
2022-12-24 23:18:11 +00:00
|
|
|
return self.color_mapping.get(colorname, "")
|
2022-12-24 17:19:42 +00:00
|
|
|
|
2022-12-24 13:23:07 +00:00
|
|
|
def _gather_papers(self, conf, args):
|
2022-12-22 20:02:01 +00:00
|
|
|
"""Get all papers for citekeys.
|
|
|
|
|
|
|
|
Returns all Paper objects described by the citekeys
|
|
|
|
passed in.
|
|
|
|
"""
|
2022-12-22 16:43:06 +00:00
|
|
|
papers = []
|
2022-12-24 13:23:07 +00:00
|
|
|
if not args.is_query:
|
2022-12-24 13:34:18 +00:00
|
|
|
keys = resolve_citekey_list(
|
2022-12-24 13:23:07 +00:00
|
|
|
self.repository, conf, args.query, ui=self.ui, exit_on_fail=True
|
|
|
|
)
|
2022-12-24 16:01:06 +00:00
|
|
|
if not keys:
|
|
|
|
return []
|
2022-12-24 13:34:18 +00:00
|
|
|
for key in keys:
|
2022-12-24 13:23:07 +00:00
|
|
|
papers.append(self.repository.pull_paper(key))
|
|
|
|
else:
|
2022-12-24 16:01:06 +00:00
|
|
|
papers = list(
|
|
|
|
filter(
|
|
|
|
get_paper_filter(
|
|
|
|
args.query,
|
|
|
|
case_sensitive=args.case_sensitive,
|
|
|
|
strict=args.strict,
|
|
|
|
),
|
|
|
|
self.repository.all_papers(),
|
|
|
|
)
|
|
|
|
)
|
2022-12-24 13:34:18 +00:00
|
|
|
if len(papers) > CONFIRMATION_PAPER_THRESHOLD:
|
2022-12-24 16:01:06 +00:00
|
|
|
self.ui.message(
|
|
|
|
"\n".join(
|
|
|
|
pretty.paper_oneliner(
|
2022-12-25 11:17:05 +00:00
|
|
|
p, citekey_only=False, max_authors=self.max_authors
|
2022-12-24 16:01:06 +00:00
|
|
|
)
|
|
|
|
for p in papers
|
|
|
|
)
|
|
|
|
)
|
|
|
|
self.ui.input_yn(
|
|
|
|
question=f"Extract annotations for these papers?", default="y"
|
|
|
|
)
|
2022-12-22 16:43:06 +00:00
|
|
|
return papers
|
|
|
|
|
2022-12-22 17:57:41 +00:00
|
|
|
def _get_file(self, paper):
|
2022-12-22 20:02:01 +00:00
|
|
|
"""Get path of document belonging to paper.
|
|
|
|
|
|
|
|
Returns the real path to the document which belongs
|
|
|
|
to the paper passed in. Emits a warning if no
|
|
|
|
document belongs to paper.
|
|
|
|
"""
|
2022-12-22 16:43:06 +00:00
|
|
|
path = self.broker.real_docpath(paper.docpath)
|
|
|
|
if not path:
|
2022-12-22 18:39:36 +00:00
|
|
|
self.ui.warning(f"{paper.citekey} has no valid document.")
|
2022-12-22 16:43:06 +00:00
|
|
|
return path
|
|
|
|
|
2022-12-25 11:17:05 +00:00
|
|
|
def _get_annotations(self, filename):
|
2022-12-22 20:02:01 +00:00
|
|
|
"""Extract annotations from a file.
|
|
|
|
|
|
|
|
Returns all readable annotations contained in the file
|
|
|
|
passed in. Only returns Highlight or Text annotations
|
|
|
|
currently.
|
|
|
|
"""
|
2022-12-22 16:43:06 +00:00
|
|
|
annotations = []
|
|
|
|
with fitz.Document(filename) as doc:
|
|
|
|
for page in doc:
|
|
|
|
for annot in page.annots():
|
2022-12-22 22:47:50 +00:00
|
|
|
quote, note = self._retrieve_annotation_content(page, annot)
|
2022-12-24 17:37:36 +00:00
|
|
|
a = Annotation(
|
|
|
|
file=filename,
|
|
|
|
text=quote,
|
|
|
|
content=note,
|
|
|
|
colors=annot.colors,
|
|
|
|
type=annot.type[1],
|
|
|
|
page=(page.number or 0) + 1,
|
2022-12-22 23:27:19 +00:00
|
|
|
)
|
2022-12-24 17:37:36 +00:00
|
|
|
a.tag = self.tag_from_colorname(a.colorname)
|
|
|
|
annotations.append(a)
|
2022-12-22 16:43:06 +00:00
|
|
|
return annotations
|
|
|
|
|
2022-12-22 22:47:50 +00:00
|
|
|
def _retrieve_annotation_content(self, page, annotation):
|
2022-12-22 21:31:21 +00:00
|
|
|
"""Gets the text content of an annotation.
|
|
|
|
|
|
|
|
Returns the actual content of an annotation. Sometimes
|
|
|
|
that is only the written words, sometimes that is only
|
|
|
|
annotation notes, sometimes it is both. Runs a similarity
|
|
|
|
comparison between strings to find out whether they
|
|
|
|
should both be included or are doubling up.
|
|
|
|
"""
|
2022-12-22 21:06:41 +00:00
|
|
|
content = annotation.info["content"].replace("\n", " ")
|
|
|
|
written = page.get_textbox(annotation.rect).replace("\n", " ")
|
2022-12-22 21:31:21 +00:00
|
|
|
|
2022-12-22 21:56:07 +00:00
|
|
|
# highlight with selection in note
|
2022-12-22 22:21:13 +00:00
|
|
|
if Levenshtein.ratio(content, written) > self.minimum_similarity:
|
2022-12-22 22:47:50 +00:00
|
|
|
return (content, "")
|
2022-12-22 21:56:07 +00:00
|
|
|
# an independent note, not a highlight
|
|
|
|
elif content and not written:
|
2022-12-22 22:47:50 +00:00
|
|
|
return ("", content)
|
2022-12-22 21:56:07 +00:00
|
|
|
# both a highlight and a note
|
2022-12-22 21:06:41 +00:00
|
|
|
elif content:
|
2022-12-22 22:47:50 +00:00
|
|
|
return (written, content)
|
2022-12-22 21:56:07 +00:00
|
|
|
# highlight with selection not in note
|
2022-12-22 22:47:50 +00:00
|
|
|
return (written, "")
|
2022-12-22 21:06:41 +00:00
|
|
|
|
2022-12-25 11:17:05 +00:00
|
|
|
def _to_stdout(self, annotated_papers, short_header=False):
|
2022-12-22 20:02:01 +00:00
|
|
|
"""Write annotations to stdout.
|
|
|
|
|
|
|
|
Simply outputs the gathered annotations over stdout
|
|
|
|
ready to be passed on through pipelines etc.
|
|
|
|
"""
|
2022-12-22 18:39:36 +00:00
|
|
|
output = ""
|
2022-12-25 11:17:05 +00:00
|
|
|
for paper in annotated_papers:
|
2022-12-25 09:56:30 +00:00
|
|
|
output += (
|
2022-12-25 11:17:05 +00:00
|
|
|
f"\n------ {paper.headline(self.short_header, self.max_authors)} ------\n\n"
|
2022-12-25 09:56:30 +00:00
|
|
|
)
|
2022-12-25 11:17:05 +00:00
|
|
|
for annotation in paper.annotations:
|
2022-12-24 23:18:11 +00:00
|
|
|
output += f"{annotation.format(self.formatting)}\n"
|
2022-12-22 19:32:06 +00:00
|
|
|
output += "\n"
|
2022-12-24 23:51:47 +00:00
|
|
|
self.ui.message(output.strip())
|
2022-12-22 16:43:06 +00:00
|
|
|
|
2022-12-22 19:24:20 +00:00
|
|
|
def _to_notes(self, annotated_papers, note_extension="txt", edit=False):
|
2022-12-22 20:02:01 +00:00
|
|
|
"""Write annotations into pubs notes.
|
|
|
|
|
|
|
|
Permanently writes the given annotations into notes
|
|
|
|
in the pubs notes directory. Creates new notes for
|
|
|
|
citekeys missing a note or appends to existing.
|
|
|
|
"""
|
2022-12-25 11:17:05 +00:00
|
|
|
for paper in annotated_papers:
|
|
|
|
if paper.annotations:
|
|
|
|
notepath = self.broker.real_notepath(paper.citekey, note_extension)
|
2022-12-22 19:52:10 +00:00
|
|
|
if check_file(notepath, fail=False):
|
2022-12-25 11:17:05 +00:00
|
|
|
self._append_to_note(notepath, paper)
|
2022-12-22 19:52:10 +00:00
|
|
|
else:
|
2022-12-25 11:17:05 +00:00
|
|
|
self._write_new_note(notepath, paper, paper.headline(short=True, max_authors=self.max_authors))
|
|
|
|
self.ui.info(f"Wrote annotations to {paper.citekey} note {notepath}.")
|
2022-12-22 19:52:10 +00:00
|
|
|
|
2022-12-22 17:34:23 +00:00
|
|
|
if edit is True:
|
|
|
|
self.ui.edit_file(notepath, temporary=False)
|
2022-12-25 11:17:05 +00:00
|
|
|
NoteEvent(paper.citekey).send()
|
2022-12-22 16:43:06 +00:00
|
|
|
|
2022-12-25 11:17:05 +00:00
|
|
|
def _write_new_note(self, notepath, paper, headline):
|
2022-12-22 20:02:01 +00:00
|
|
|
"""Create a new note containing the annotations.
|
|
|
|
|
|
|
|
Will create a new note in the notes folder of pubs
|
|
|
|
and fill it with the annotations extracted from pdf.
|
|
|
|
"""
|
2022-12-25 11:17:05 +00:00
|
|
|
output = f"# {headline}\n\n"
|
|
|
|
for annotation in paper.annotations:
|
2022-12-24 23:18:11 +00:00
|
|
|
output += f"{annotation.format(self.formatting)}\n\n"
|
2022-12-22 19:52:10 +00:00
|
|
|
write_file(notepath, output, "w")
|
|
|
|
|
2022-12-25 11:17:05 +00:00
|
|
|
def _append_to_note(self, notepath, paper):
|
2022-12-22 19:52:10 +00:00
|
|
|
"""Append new annotations to the end of a note.
|
|
|
|
|
|
|
|
Looks through note to determine any new annotations which should be
|
|
|
|
added and adds them to the end of the note file.
|
|
|
|
"""
|
|
|
|
existing = read_text_file(notepath)
|
|
|
|
# removed annotations already found in the note
|
2022-12-24 22:32:34 +00:00
|
|
|
existing_dropped = [
|
2022-12-25 11:17:05 +00:00
|
|
|
x for x in paper.annotations if x.format(self.formatting) not in existing
|
2022-12-24 22:32:34 +00:00
|
|
|
]
|
2022-12-22 19:52:10 +00:00
|
|
|
if not existing_dropped:
|
|
|
|
return
|
|
|
|
|
|
|
|
output = ""
|
|
|
|
for annotation in existing_dropped:
|
2022-12-24 23:18:11 +00:00
|
|
|
output += f"{annotation.format(self.formatting)}\n\n"
|
2022-12-22 19:52:10 +00:00
|
|
|
write_file(notepath, output, "a")
|
|
|
|
|
2022-12-22 16:43:06 +00:00
|
|
|
|
2022-12-22 19:24:20 +00:00
|
|
|
@DocAddEvent.listen()
|
|
|
|
def modify_event(event):
|
|
|
|
if ExtractPlugin.is_loaded():
|
|
|
|
plg = ExtractPlugin.get_instance()
|
2022-12-22 21:48:47 +00:00
|
|
|
if plg.on_import:
|
2022-12-22 19:24:20 +00:00
|
|
|
all_annotations = plg.extract([event.citekey])
|
|
|
|
if all_annotations[0][1]:
|
2022-12-22 20:10:42 +00:00
|
|
|
plg._to_notes(all_annotations, plg.note_extension)
|