Created
March 10, 2021 13:09
-
-
Save Rmano/69a65024a454c4c4383061d0c9d99c7f to your computer and use it in GitHub Desktop.
Small'n'dirty script to remove the path of the background file in .xopp (xournalpp)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#! /usr/bin/env python3 | |
# -*- coding: utf8 -*- | |
# | |
import sys | |
import os | |
import re | |
import argparse | |
import gzip | |
def warn(*what): | |
if args.verbose: | |
print("WARNING: ", *what, file=sys.stderr) | |
def error(*what): | |
print("ERROR: ", *what, file=sys.stderr) | |
sys.exit(1) | |
# regular expressions | |
bg_element = r'<background.*>' | |
bg_pdf = r'type="pdf"' | |
has_pdf_file = r'filename="(.+?)"' # non-greedy! | |
def replace_with_relative(m): | |
a = m.group(1) | |
r = os.path.split(m.group(1))[1] | |
warn("absolute file name", a) | |
warn("relative file name", r) | |
return "filename=\"{}\" ".format(r) | |
# description | |
parser = argparse.ArgumentParser(description="Remove \ | |
the absolute path from a background of a .xopp file") | |
# two positional (mandatory) argument | |
parser.add_argument('filein', metavar='filein', | |
help='Input file') | |
parser.add_argument('fileout', metavar='fileout', | |
help='Output file') | |
# one flag argument | |
parser.add_argument("-v", "--verbose", dest='verbose', action="store_true", | |
help="increase output verbosity") | |
parser.add_argument("-o", "--overwrite", dest='overwrite', action="store_true", | |
help="overwrite output file (stop otherwise)") | |
args=parser.parse_args() | |
fin=gzip.open(args.filein, mode="rt", encoding="utf-8") | |
if (os.path.exists(args.fileout)): | |
if not args.overwrite: | |
error("File {} exists, aborted (use -o to override)".format(args.fileout)) | |
else: | |
warn("Overwriting output file") | |
fout=gzip.open(args.fileout, mode="wt", encoding="utf-8") | |
for rline in fin: | |
line=rline.strip() | |
if re.match(bg_element, line) and re.search(bg_pdf, line): | |
warn("BG found :", line) | |
m = re.search(has_pdf_file, line) | |
if m: | |
newline = re.sub(has_pdf_file, replace_with_relative, line) | |
warn("Substituting with: ", newline) | |
else: | |
newline = line | |
fout.write(newline) | |
fout.write("\n") | |
else: | |
fout.write(rline) | |
fin.close() | |
fout.close() | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Another way is to use standard unix programs:
zcat absolute.xopp |sed -e 's/filename=\"[^\"]*\//filename=\"/g' |gzip > relative.xopp
To fix all files in a directory (typically exams), I use the following:
ls *.xopp |xargs -I {} sh -c 'zcat {} |sed -e "s/filename=\"[^\"]*\//filename=\"/g" |gzip > {}-~ && mv {}-~ {}'