gamster 0.6.4__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- gamster/__init__.py +11 -0
- gamster/cli.py +160 -0
- gamster/create_bag.py +191 -0
- gamster/loggers.py +50 -0
- gamster/unpack.py +142 -0
- gamster-0.6.4.dist-info/METADATA +120 -0
- gamster-0.6.4.dist-info/RECORD +10 -0
- gamster-0.6.4.dist-info/WHEEL +4 -0
- gamster-0.6.4.dist-info/entry_points.txt +3 -0
- gamster-0.6.4.dist-info/licenses/LICENSE +21 -0
gamster/__init__.py
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
"Package for packaging GAMS models and data into a single file."
|
|
2
|
+
|
|
3
|
+
from importlib.metadata import metadata
|
|
4
|
+
|
|
5
|
+
meta = metadata(__name__)
|
|
6
|
+
NAME = meta["name"]
|
|
7
|
+
VERSION = meta["version"]
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class BagExistsError(Exception):
|
|
11
|
+
"""Exception raised when a bag already exists."""
|
gamster/cli.py
ADDED
|
@@ -0,0 +1,160 @@
|
|
|
1
|
+
"The command line interface to gamspacking."
|
|
2
|
+
|
|
3
|
+
import logging
|
|
4
|
+
import sys
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
|
|
7
|
+
import click
|
|
8
|
+
import gamslib
|
|
9
|
+
|
|
10
|
+
from gamster import create_bag, loggers, unpack
|
|
11
|
+
|
|
12
|
+
from . import NAME, VERSION
|
|
13
|
+
|
|
14
|
+
logger = logging.getLogger()
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
@click.group()
|
|
18
|
+
@click.option(
|
|
19
|
+
"-v",
|
|
20
|
+
"--verbose",
|
|
21
|
+
is_flag=True,
|
|
22
|
+
default=False,
|
|
23
|
+
help="Enable verbose logging. Cannot be used together with '--quiet'.",
|
|
24
|
+
)
|
|
25
|
+
@click.option(
|
|
26
|
+
"-q",
|
|
27
|
+
"--quiet",
|
|
28
|
+
is_flag=True,
|
|
29
|
+
default=False,
|
|
30
|
+
help="Disable logging. Only Errors are shown. Cannot be used together '--verbose'.",
|
|
31
|
+
)
|
|
32
|
+
@click.option(
|
|
33
|
+
"--logfile", help="Path to the log file. If not set, no logfile will be created."
|
|
34
|
+
)
|
|
35
|
+
@click.option(
|
|
36
|
+
"--filelog-level",
|
|
37
|
+
type=click.Choice(
|
|
38
|
+
["DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL"], case_sensitive=False
|
|
39
|
+
),
|
|
40
|
+
default="INFO",
|
|
41
|
+
help="Log level for the log file. Default is INFO.",
|
|
42
|
+
)
|
|
43
|
+
@click.version_option(version=VERSION, prog_name=NAME)
|
|
44
|
+
def cli(quiet: bool, verbose: bool, filelog_level: str, logfile=f"{NAME}.log"):
|
|
45
|
+
"""packager is the GAMS tool to package file based object data into BagIt bags.
|
|
46
|
+
|
|
47
|
+
Run packager --help to see the available commands.
|
|
48
|
+
"""
|
|
49
|
+
if quiet and verbose:
|
|
50
|
+
raise click.UsageError("You cannot use --quiet and --verbose together.")
|
|
51
|
+
if quiet:
|
|
52
|
+
loglevel = logging.ERROR
|
|
53
|
+
elif verbose:
|
|
54
|
+
loglevel = logging.DEBUG
|
|
55
|
+
else:
|
|
56
|
+
loglevel = logging.INFO
|
|
57
|
+
real_filelog_level = getattr(logging, filelog_level.upper())
|
|
58
|
+
loggers.configure_logging(loglevel, logfile, real_filelog_level)
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
@click.group(name="bag")
|
|
62
|
+
def bag_group():
|
|
63
|
+
"Commands for creating bags."
|
|
64
|
+
# Identionally empty
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
@click.command(name="create")
|
|
68
|
+
@click.option(
|
|
69
|
+
"-o",
|
|
70
|
+
"--outputdir",
|
|
71
|
+
default="bags",
|
|
72
|
+
help="Path to the directory where the bags will be created.",
|
|
73
|
+
)
|
|
74
|
+
@click.option(
|
|
75
|
+
"--overwrite-bag",
|
|
76
|
+
default=False,
|
|
77
|
+
is_flag=True,
|
|
78
|
+
help="Set this flag to overwrite existing bags.",
|
|
79
|
+
)
|
|
80
|
+
@click.option(
|
|
81
|
+
"--zip",
|
|
82
|
+
is_flag=True,
|
|
83
|
+
default=False,
|
|
84
|
+
help="Create the bag as zip archive. If not set, the bag will be created as a folder.",
|
|
85
|
+
)
|
|
86
|
+
@click.argument("objects_root", required=True, type=click.Path(exists=True))
|
|
87
|
+
def createbags(
|
|
88
|
+
objects_root: str, outputdir: str, overwrite_bag: bool = False, zip: bool = False
|
|
89
|
+
):
|
|
90
|
+
"""Generate bags for all objects in or below 'objects_root' folder.
|
|
91
|
+
|
|
92
|
+
objects_root is the path to the folder containing the objects to be bagged.
|
|
93
|
+
|
|
94
|
+
Use 'packager bag create --help' to see the available options.
|
|
95
|
+
"""
|
|
96
|
+
|
|
97
|
+
created_bags = []
|
|
98
|
+
output_path = Path(outputdir)
|
|
99
|
+
for path in gamslib.objectdir.find_object_folders(Path(objects_root)):
|
|
100
|
+
try:
|
|
101
|
+
bag_path = create_bag.make_bag(path, output_path, overwrite_bag, zip)
|
|
102
|
+
created_bags.append(bag_path)
|
|
103
|
+
except gamslib.sip.BagValidationError as err:
|
|
104
|
+
click.echo(f"Bag from {path} is not valid.", color=True, err=True)
|
|
105
|
+
click.echo(f"{err}", color=True, err=True)
|
|
106
|
+
sys.exit(1)
|
|
107
|
+
except create_bag.BagExistsError:
|
|
108
|
+
click.echo(
|
|
109
|
+
"Bag for {path} already exists in {output_path}.", color=True, err=True
|
|
110
|
+
)
|
|
111
|
+
click.echo(
|
|
112
|
+
"Use --overwrite-bag to overwrite or delete the existing bag directory."
|
|
113
|
+
)
|
|
114
|
+
sys.exit(1)
|
|
115
|
+
logger.info("Created %d bags in %s", len(created_bags), outputdir)
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
@click.command(name="unpack")
|
|
119
|
+
@click.argument("bagfolder", required=True, type=click.Path(exists=True))
|
|
120
|
+
@click.option(
|
|
121
|
+
"-o",
|
|
122
|
+
"--outputdir",
|
|
123
|
+
default="unpacked_objects",
|
|
124
|
+
help="Path to the folder where the unpacked objects will be created.",
|
|
125
|
+
)
|
|
126
|
+
@click.option(
|
|
127
|
+
"--overwrite",
|
|
128
|
+
is_flag=True,
|
|
129
|
+
default=False,
|
|
130
|
+
help="Overwrite existing object directories.",
|
|
131
|
+
)
|
|
132
|
+
def unpack_bags(outputdir: str, bagfolder: str, overwrite: bool = False):
|
|
133
|
+
"""Unpack one or more bags.
|
|
134
|
+
|
|
135
|
+
Use this to convert a bagged SIP directory back into the original object directory structure.
|
|
136
|
+
BAGFOLDER is the path to the folder containing one or more bags to unpack.
|
|
137
|
+
Use 'packager bag unpack --help' to see the available options.
|
|
138
|
+
"""
|
|
139
|
+
outputdir = Path(outputdir)
|
|
140
|
+
outputdir.mkdir(parents=True, exist_ok=True)
|
|
141
|
+
counter = 0
|
|
142
|
+
for bag_path in unpack.find_bag_folders(Path(bagfolder)):
|
|
143
|
+
try:
|
|
144
|
+
unpack.unpack_bag(bag_path, outputdir, overwrite=overwrite)
|
|
145
|
+
counter += 1
|
|
146
|
+
except FileExistsError:
|
|
147
|
+
click.echo(
|
|
148
|
+
(
|
|
149
|
+
f"Object directory for bag {bag_path} already exists. "
|
|
150
|
+
"Use --overwrite to overwrite existing directories."
|
|
151
|
+
),
|
|
152
|
+
err=True,
|
|
153
|
+
color=True,
|
|
154
|
+
)
|
|
155
|
+
sys.exit(1)
|
|
156
|
+
click.echo(f"Unpacked {counter} bags into {outputdir}.")
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
cli.add_command(createbags)
|
|
160
|
+
cli.add_command(unpack_bags)
|
gamster/create_bag.py
ADDED
|
@@ -0,0 +1,191 @@
|
|
|
1
|
+
"""Create a Bagit directory from object folders."""
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
import logging
|
|
5
|
+
import shutil
|
|
6
|
+
import tempfile
|
|
7
|
+
import warnings
|
|
8
|
+
from datetime import datetime, timezone
|
|
9
|
+
from pathlib import Path
|
|
10
|
+
|
|
11
|
+
import gamslib.sip
|
|
12
|
+
from gamslib.objectcsv.objectcsvmanager import ObjectCSVManager
|
|
13
|
+
from gamslib.objectdir import validate_object_dir
|
|
14
|
+
from gamslib.sip.sipjson import SipJson
|
|
15
|
+
|
|
16
|
+
from gamster import BagExistsError
|
|
17
|
+
|
|
18
|
+
from . import NAME, VERSION
|
|
19
|
+
|
|
20
|
+
logger = logging.getLogger(__name__)
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def write_sip_json(bag_dir: Path, json_data: dict):
|
|
24
|
+
"""Write sip.json to the bagit object folder."""
|
|
25
|
+
sip_json_file = bag_dir / "data" / "meta" / "sip.json"
|
|
26
|
+
sip_json_file.parent.mkdir(parents=True, exist_ok=True)
|
|
27
|
+
with sip_json_file.open("w", encoding="utf-8", newline="") as f:
|
|
28
|
+
f.write(json.dumps(json_data, indent=2, ensure_ascii=False))
|
|
29
|
+
logger.debug("Created %s", sip_json_file)
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def write_bagit_txt(bag_dir: Path):
|
|
33
|
+
"Create the bagit.txt file in the object bagit folder."
|
|
34
|
+
bagit_txt = bag_dir / "bagit.txt"
|
|
35
|
+
bagit_txt.write_text(
|
|
36
|
+
"BagIt-Version: 1.0\nTag-File-Character-Encoding: UTF-8\n", encoding="utf-8"
|
|
37
|
+
)
|
|
38
|
+
logger.debug("Created %s", bag_dir / "bagit.txt")
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def write_manifest_md5(bag_dir: Path, manifest_data: dict):
|
|
42
|
+
"Write the manifest-md5.txt file to the bagit object folder."
|
|
43
|
+
with open(bag_dir / "manifest-md5.txt", "w", encoding="utf-8", newline="") as f:
|
|
44
|
+
for key in sorted(manifest_data.keys()):
|
|
45
|
+
if key == "sip.json":
|
|
46
|
+
f.write(f"{manifest_data[key]['md5']} data/meta/{key}\n")
|
|
47
|
+
else:
|
|
48
|
+
f.write(f"{manifest_data[key]['md5']} data/content/{key}\n")
|
|
49
|
+
logger.debug("Created %s", bag_dir / "manifest-md5.txt")
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def write_manifest_sha512(bag_dir: Path, manifest_data: dict):
|
|
53
|
+
"Write the manifest-sha512.txt file to the bagit object folder."
|
|
54
|
+
with open(bag_dir / "manifest-sha512.txt", "w", encoding="utf-8", newline="") as f:
|
|
55
|
+
for key in sorted(manifest_data.keys()):
|
|
56
|
+
if key == "sip.json":
|
|
57
|
+
f.write(f"{manifest_data[key]['sha512']} data/meta/{key}\n")
|
|
58
|
+
else:
|
|
59
|
+
f.write(f"{manifest_data[key]['sha512']} data/content/{key}\n")
|
|
60
|
+
logger.debug("Created %s", bag_dir / "manifest-sha512.txt")
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def write_bag_info_txt(bag_dir: Path, sip_json: SipJson):
|
|
64
|
+
"Write the bag-info.txt file to the bagit object folder."
|
|
65
|
+
with open(bag_dir / "bag-info.txt", "w", encoding="utf-8", newline="") as f:
|
|
66
|
+
utc_now = datetime.now(timezone.utc)
|
|
67
|
+
f.write(f"Bagging-Date: {utc_now.strftime('%Y-%m-%d')}\n")
|
|
68
|
+
# Payload-Oxum: <octets = Size in Bytes>.<number of files>
|
|
69
|
+
oxum_bytes = gamslib.sip.utils.count_bytes(Path(bag_dir) / "data")
|
|
70
|
+
f.write(
|
|
71
|
+
f"Payload-Oxum: {oxum_bytes}.{gamslib.sip.utils.count_files(Path(bag_dir) / 'data')}\n"
|
|
72
|
+
)
|
|
73
|
+
f.write("Contact-Email: dh@uni-graz.at\n") # aus .toml?
|
|
74
|
+
f.write(f"External-Description: {sip_json.title}\n")
|
|
75
|
+
logger.debug("Created %s", bag_dir / "bag-info.txt")
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def cleanup_bag_dir(bag_path: Path, overwrite_bag=False) -> None:
|
|
79
|
+
"""Check if the bag (either a folder or a zip archive) already exists and
|
|
80
|
+
remove it if overwrite_bag is True.
|
|
81
|
+
|
|
82
|
+
Raises BagExistsError if the bag directory or bag zip archive already exists
|
|
83
|
+
and overwrite_bag is False.
|
|
84
|
+
|
|
85
|
+
If overwrite_bag is True, a warning is issued and the existing bag directory and/or zip archive
|
|
86
|
+
is removed before creating a new bag directory.
|
|
87
|
+
"""
|
|
88
|
+
if bag_path.exists():
|
|
89
|
+
if overwrite_bag:
|
|
90
|
+
warnings.warn(
|
|
91
|
+
f"Bag '{bag_path.name}' already exists in '{bag_path.parent}'. Overwriting it.",
|
|
92
|
+
UserWarning,
|
|
93
|
+
)
|
|
94
|
+
shutil.rmtree(bag_path)
|
|
95
|
+
else:
|
|
96
|
+
raise BagExistsError(
|
|
97
|
+
f"Bag '{bag_path.name}' already exists in '{bag_path.parent}'"
|
|
98
|
+
)
|
|
99
|
+
# we additionally check for existing zip archive
|
|
100
|
+
zip_path = bag_path.with_suffix(bag_path.suffix + ".zip")
|
|
101
|
+
if zip_path.exists():
|
|
102
|
+
if overwrite_bag:
|
|
103
|
+
warnings.warn(
|
|
104
|
+
f"Bag archive '{zip_path.name}' already exists in '{zip_path.parent}'. Overwriting it.",
|
|
105
|
+
UserWarning,
|
|
106
|
+
)
|
|
107
|
+
zip_path.unlink()
|
|
108
|
+
else:
|
|
109
|
+
raise BagExistsError(
|
|
110
|
+
f"Bag archive '{zip_path.name}' already exists in '{zip_path.parent}'"
|
|
111
|
+
)
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def create_temporary_bag_dir(pid: str, object_dir: Path, sip_json: SipJson) -> Path:
|
|
115
|
+
"""Create a temporary Bagit directory for the object folder.
|
|
116
|
+
|
|
117
|
+
The temporary directory will be created in the system's temp directory.
|
|
118
|
+
Purpose is to prepare the bagit structure and files and to validate the bag
|
|
119
|
+
before moving it to the final location.
|
|
120
|
+
|
|
121
|
+
Returns the path to the temporary directory.
|
|
122
|
+
"""
|
|
123
|
+
manifest_data = {}
|
|
124
|
+
# with tempfile.TemporaryDirectory() as tmpdir:
|
|
125
|
+
tmpdir = tempfile.mkdtemp(prefix=f"gamster-{pid}-")
|
|
126
|
+
tmp_bag_dir = Path(tmpdir) / pid # tempory object folder
|
|
127
|
+
tmp_bag_dir.mkdir()
|
|
128
|
+
# copy the datastreams to the temporary object folder
|
|
129
|
+
# and add each size and bagpath to the SIPJSON
|
|
130
|
+
for content_file in sip_json.contentFiles:
|
|
131
|
+
# dsmeta = object_csv.get_datastreamdata(ds_file.dsid)
|
|
132
|
+
src_file = object_dir / content_file.dsid
|
|
133
|
+
manifest_data[content_file.dsid] = {}
|
|
134
|
+
manifest_data[content_file.dsid]["md5"] = gamslib.sip.utils.md5hash(src_file)
|
|
135
|
+
manifest_data[content_file.dsid]["sha512"] = gamslib.sip.utils.sha512hash(src_file)
|
|
136
|
+
|
|
137
|
+
target_file = tmp_bag_dir / "data" / "content" / src_file.name
|
|
138
|
+
target_file.parent.mkdir(parents=True, exist_ok=True)
|
|
139
|
+
shutil.copy(src_file, target_file)
|
|
140
|
+
|
|
141
|
+
content_file.size = target_file.stat().st_size
|
|
142
|
+
content_file.bagpath = target_file.relative_to(tmp_bag_dir).as_posix()
|
|
143
|
+
|
|
144
|
+
write_sip_json(tmp_bag_dir, sip_json.get_json())
|
|
145
|
+
manifest_data["sip.json"] = {}
|
|
146
|
+
manifest_data["sip.json"]["md5"] = gamslib.sip.utils.md5hash(
|
|
147
|
+
tmp_bag_dir / "data" / "meta" / "sip.json"
|
|
148
|
+
)
|
|
149
|
+
manifest_data["sip.json"]["sha512"] = gamslib.sip.utils.sha512hash(
|
|
150
|
+
tmp_bag_dir / "data" / "meta" / "sip.json"
|
|
151
|
+
)
|
|
152
|
+
|
|
153
|
+
write_bagit_txt(tmp_bag_dir)
|
|
154
|
+
write_manifest_md5(tmp_bag_dir, manifest_data)
|
|
155
|
+
write_manifest_sha512(tmp_bag_dir, manifest_data)
|
|
156
|
+
write_bag_info_txt(tmp_bag_dir, sip_json)
|
|
157
|
+
return tmp_bag_dir
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
def make_bag(
|
|
161
|
+
object_dir: Path, output_root: Path, overwrite_bag=False, as_zip=False
|
|
162
|
+
) -> Path:
|
|
163
|
+
"""Create a Bagit directory for files in object_dir.
|
|
164
|
+
|
|
165
|
+
The resulting directory will be created under the output_root directory.
|
|
166
|
+
Returns the path of the created bag directory.
|
|
167
|
+
Raises BagExistsError if the bag directory already exists and overwrite_bag is False.
|
|
168
|
+
Raises gamslib.sip.BagValidationError if the bag validation fails.
|
|
169
|
+
"""
|
|
170
|
+
validate_object_dir(object_dir)
|
|
171
|
+
pid = object_dir.name
|
|
172
|
+
gamslib.sip.validation.validate_pid(pid)
|
|
173
|
+
bag_path = output_root / pid
|
|
174
|
+
|
|
175
|
+
# handle existing bag directory
|
|
176
|
+
cleanup_bag_dir(bag_path, overwrite_bag)
|
|
177
|
+
|
|
178
|
+
# object_csv = ObjectCSV(object_dir)
|
|
179
|
+
csv_mgr = ObjectCSVManager(object_dir)
|
|
180
|
+
packager_name = f"{NAME.capitalize()} {VERSION}"
|
|
181
|
+
sip_json = SipJson.from_objectcsvmanager(packager_name, csv_mgr)
|
|
182
|
+
|
|
183
|
+
tmp_bag_dir = create_temporary_bag_dir(pid, object_dir, sip_json)
|
|
184
|
+
gamslib.sip.validation.validate_bag(tmp_bag_dir)
|
|
185
|
+
if as_zip:
|
|
186
|
+
zip_path = shutil.make_archive(bag_path, "zip", tmp_bag_dir)
|
|
187
|
+
shutil.rmtree(tmp_bag_dir)
|
|
188
|
+
return Path(zip_path)
|
|
189
|
+
# bag directory
|
|
190
|
+
shutil.move(tmp_bag_dir, bag_path)
|
|
191
|
+
return bag_path
|
gamster/loggers.py
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
"""Logging related code"""
|
|
2
|
+
|
|
3
|
+
import logging
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
def make_console_handler(loglevel: int = logging.INFO) -> logging.StreamHandler:
|
|
7
|
+
"""Create a console handler with a specific log level."""
|
|
8
|
+
ch = logging.StreamHandler()
|
|
9
|
+
ch.name = "console"
|
|
10
|
+
ch.setLevel(loglevel)
|
|
11
|
+
ch_formatter = logging.Formatter("%(message)s")
|
|
12
|
+
ch.setFormatter(ch_formatter)
|
|
13
|
+
return ch
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def make_file_handler(logfile: str, loglevel: int) -> logging.FileHandler:
|
|
17
|
+
"""Create a file handler with a specific log level."""
|
|
18
|
+
fh = logging.FileHandler(logfile)
|
|
19
|
+
fh.name = "file"
|
|
20
|
+
fh.setLevel(loglevel)
|
|
21
|
+
file_formatter = logging.Formatter(
|
|
22
|
+
"%(asctime)s - %(name)s - %(levelname)s - %(message)s"
|
|
23
|
+
)
|
|
24
|
+
fh.setFormatter(file_formatter)
|
|
25
|
+
return fh
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def configure_logging(
|
|
29
|
+
level: int | None = None,
|
|
30
|
+
logfile: str | None = None,
|
|
31
|
+
logfile_level: int | None = None,
|
|
32
|
+
) -> logging.Logger:
|
|
33
|
+
"""Setup up the root logger with a console handler and an optional file handler."""
|
|
34
|
+
root_logger = logging.getLogger()
|
|
35
|
+
loglevel = logging.INFO if level is None else level
|
|
36
|
+
file_log_level = loglevel if logfile_level is None else logfile_level
|
|
37
|
+
|
|
38
|
+
root_logger.handlers.clear() # Clear existing handlers to start fresh
|
|
39
|
+
|
|
40
|
+
# We have to use the minimum of the log levels because the root logger will not
|
|
41
|
+
# pass messages to handlers that have a higher level than the root logger.
|
|
42
|
+
root_logger.setLevel(min([loglevel, file_log_level]))
|
|
43
|
+
|
|
44
|
+
root_logger.addHandler(make_console_handler(loglevel))
|
|
45
|
+
|
|
46
|
+
if logfile is None or logfile == "":
|
|
47
|
+
root_logger.warning("No logfile specified. Only console logging will be used.")
|
|
48
|
+
else:
|
|
49
|
+
root_logger.addHandler(make_file_handler(logfile, file_log_level))
|
|
50
|
+
return root_logger
|
gamster/unpack.py
ADDED
|
@@ -0,0 +1,142 @@
|
|
|
1
|
+
"""Functions to unpack bags into object directories.
|
|
2
|
+
|
|
3
|
+
Unpacking a bag will recreate the original object directory structure
|
|
4
|
+
from the bag contents and generate the object.csv and datastreams.csv files
|
|
5
|
+
based on the sip.json metadata in the bag.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
import json
|
|
9
|
+
|
|
10
|
+
import re
|
|
11
|
+
import shutil
|
|
12
|
+
from pathlib import Path
|
|
13
|
+
from tempfile import TemporaryDirectory
|
|
14
|
+
import warnings
|
|
15
|
+
|
|
16
|
+
from gamslib.objectcsv.dsdata import DSData
|
|
17
|
+
from gamslib.objectcsv.objectcsvmanager import ObjectCSVManager
|
|
18
|
+
from gamslib.objectcsv.objectdata import ObjectData
|
|
19
|
+
from gamslib.sip.utils import is_bag
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def _extract_objectdata_from_bag(sip_data: dict) -> ObjectData:
|
|
23
|
+
"""Extracts ObjectData from the sip.json file in the bag."""
|
|
24
|
+
obj_data = {}
|
|
25
|
+
for fieldname in ObjectData.fieldnames():
|
|
26
|
+
if fieldname in ("lang", "tags"):
|
|
27
|
+
obj_data[fieldname] = ";".join(sip_data.get(fieldname, []))
|
|
28
|
+
else:
|
|
29
|
+
obj_data[fieldname] = sip_data.get(fieldname)
|
|
30
|
+
return ObjectData(**obj_data)
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def _extract_dsdata_from_bag(sip_data: dict) -> list[DSData]:
|
|
34
|
+
"""Extracts the DSData from the sip.json file in the bag.
|
|
35
|
+
|
|
36
|
+
Returns a list of DSData objects.
|
|
37
|
+
"""
|
|
38
|
+
datastreams = []
|
|
39
|
+
for content_file in sip_data.get("contentFiles", []):
|
|
40
|
+
ds_data = {}
|
|
41
|
+
for fieldname in DSData.fieldnames():
|
|
42
|
+
if fieldname == "dspath":
|
|
43
|
+
ds_data["dspath"] = f"{content_file['dsid']}"
|
|
44
|
+
elif fieldname in ("lang", "tags"):
|
|
45
|
+
ds_data[fieldname] = ",".join(content_file.get(fieldname, []))
|
|
46
|
+
else:
|
|
47
|
+
ds_data[fieldname] = content_file[fieldname]
|
|
48
|
+
# dspath is not in sip.json, but we can construct it
|
|
49
|
+
datastreams.append(DSData(**ds_data))
|
|
50
|
+
return datastreams
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def _create_temporary_bag_dir(
|
|
54
|
+
object_id: str, tmpdir: Path, original_bag_path: Path
|
|
55
|
+
) -> Path:
|
|
56
|
+
"""Creates a temporary copy of the original bag.
|
|
57
|
+
|
|
58
|
+
We use this temporary copy so we can handle both zipped and unzipped bags in the same way.
|
|
59
|
+
original_bag_path can be either a zipped bag file or a bag directory.
|
|
60
|
+
The temporary bag directory will be created under tmpdir/bag/object_id.
|
|
61
|
+
|
|
62
|
+
Returns the path to the temporary bag directory.
|
|
63
|
+
"""
|
|
64
|
+
extracted_bag_dir = Path(tmpdir) / "bag" / object_id
|
|
65
|
+
extracted_bag_dir.mkdir(parents=True)
|
|
66
|
+
shutil.rmtree(extracted_bag_dir) # just in case it exists
|
|
67
|
+
if original_bag_path.is_file(): # extract zipped bag to bag_dir
|
|
68
|
+
shutil.unpack_archive(original_bag_path, extracted_bag_dir)
|
|
69
|
+
else: # bag is a folder: copy to bag_dir
|
|
70
|
+
shutil.copytree(original_bag_path, extracted_bag_dir)
|
|
71
|
+
return extracted_bag_dir
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def _check_existing_object_dir(object_path: Path, overwrite: bool = False):
|
|
75
|
+
"""Check if the object directory already exists.
|
|
76
|
+
|
|
77
|
+
If overwrite is False and the object directory exists, a FileExistsError is raised.
|
|
78
|
+
If overwrite is True and the object directory exists, it is deleted and a warning is issued.
|
|
79
|
+
"""
|
|
80
|
+
if object_path.exists():
|
|
81
|
+
if overwrite:
|
|
82
|
+
shutil.rmtree(object_path)
|
|
83
|
+
warnings.warn(
|
|
84
|
+
f"Object directory {object_path} already exists. Overwriting it.",
|
|
85
|
+
UserWarning,
|
|
86
|
+
)
|
|
87
|
+
else:
|
|
88
|
+
raise FileExistsError(f"Object directory {object_path} already exists.")
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def unpack_bag(bag_path: Path, outputdir: Path, overwrite: bool = False) -> Path:
|
|
92
|
+
"""Unpacks a bag to a object directory in outputdir.
|
|
93
|
+
|
|
94
|
+
The unpacked object directory will be named according to the object ID in the bag,
|
|
95
|
+
with ':' replaced by '%3A'.
|
|
96
|
+
|
|
97
|
+
If overwrite is False and the object directory already exists, a FileExistsError is raised.
|
|
98
|
+
|
|
99
|
+
Returns the path to the unpacked object directory.
|
|
100
|
+
"""
|
|
101
|
+
# With a temporary bag_dir we can handle zipped and unzipped bags in the same way.
|
|
102
|
+
object_id = re.sub(r"\.zip$", "", bag_path.name).replace(":", "%3A")
|
|
103
|
+
final_object_path = outputdir / object_id
|
|
104
|
+
with TemporaryDirectory() as tmpdir:
|
|
105
|
+
# this is where we extracted the bag (if zipped) or copy the bag folder to
|
|
106
|
+
temporary_bag_path = _create_temporary_bag_dir(
|
|
107
|
+
object_id, Path(tmpdir), bag_path
|
|
108
|
+
)
|
|
109
|
+
# create a temporary object dir to be copied later, if everything went smoothly
|
|
110
|
+
temporary_object_path = Path(tmpdir) / "object_tmp"
|
|
111
|
+
|
|
112
|
+
sip_json_data = json.loads(
|
|
113
|
+
(temporary_bag_path / "data" / "meta" / "sip.json").read_text()
|
|
114
|
+
)
|
|
115
|
+
# copy bag data to the temporary object dir
|
|
116
|
+
shutil.copytree(temporary_bag_path / "data" / "content", temporary_object_path)
|
|
117
|
+
# create the csv files based on sip.json
|
|
118
|
+
obj_csv_mgr = ObjectCSVManager(temporary_object_path)
|
|
119
|
+
obj_csv_mgr.set_object(_extract_objectdata_from_bag(sip_json_data))
|
|
120
|
+
for ds in _extract_dsdata_from_bag(sip_json_data):
|
|
121
|
+
obj_csv_mgr.add_datastream(ds)
|
|
122
|
+
obj_csv_mgr.save()
|
|
123
|
+
_check_existing_object_dir(final_object_path, overwrite)
|
|
124
|
+
shutil.move(temporary_object_path, final_object_path)
|
|
125
|
+
return final_object_path
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
def find_bag_folders(rootfolder: Path) -> list[Path]:
|
|
129
|
+
"""Find all bag folders or zipped bag files in or below rootfolder.
|
|
130
|
+
|
|
131
|
+
Bag directories cannot be nested, but rootfolder can be a bag itself.
|
|
132
|
+
|
|
133
|
+
Returns a list of Paths to the bag directories or zip files.
|
|
134
|
+
"""
|
|
135
|
+
bags = []
|
|
136
|
+
for path in rootfolder.rglob("bagit.txt"):
|
|
137
|
+
if is_bag(path.parent):
|
|
138
|
+
bags.append(path.parent)
|
|
139
|
+
for zipfile_path in rootfolder.rglob("*.zip"):
|
|
140
|
+
if is_bag(zipfile_path):
|
|
141
|
+
bags.append(zipfile_path)
|
|
142
|
+
return bags
|
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: gamster
|
|
3
|
+
Version: 0.6.4
|
|
4
|
+
Summary: Convert local GAMS object directories to BagitFiles.
|
|
5
|
+
Author-email: Fabio Tosques <fabio.tosques@uni-graz.at>, Gunter Vasold <gunter.vasold@uni-graz.at>
|
|
6
|
+
License-File: LICENSE
|
|
7
|
+
Requires-Python: >=3.11
|
|
8
|
+
Requires-Dist: click>=8.4.2
|
|
9
|
+
Requires-Dist: gamslib>=0.8.5
|
|
10
|
+
Description-Content-Type: text/markdown
|
|
11
|
+
|
|
12
|
+
# Gamster
|
|
13
|
+
|
|
14
|
+
## Overview
|
|
15
|
+
|
|
16
|
+
`gamster` creates bag directories from *GAMS object directories*, which can then be ingested into GAMS.
|
|
17
|
+
The program can also convert bags back into GAMS object directories.
|
|
18
|
+
|
|
19
|
+
The command for creating Bags is `gamster create <PATH>`.
|
|
20
|
+
|
|
21
|
+
The command for "unpacking" Bags into GAMS object directories is:
|
|
22
|
+
`gamster unpack <PATH>`
|
|
23
|
+
|
|
24
|
+
```mermaid
|
|
25
|
+
graph LR
|
|
26
|
+
subgraph A[Object directory]
|
|
27
|
+
AA[Must contain files
|
|
28
|
+
that belong to the digital object,
|
|
29
|
+
plus 'DC.xml',
|
|
30
|
+
'object.csv', and
|
|
31
|
+
'datastreams.csv']
|
|
32
|
+
end
|
|
33
|
+
subgraph B[BAG]
|
|
34
|
+
BB[Data structure
|
|
35
|
+
in Bag format
|
|
36
|
+
that can be ingested,
|
|
37
|
+
i.e. one
|
|
38
|
+
Bag directory
|
|
39
|
+
per digital object]
|
|
40
|
+
end
|
|
41
|
+
A -->|gamster create| B[Bag file]
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
Using `unpack`, an object directory can be recreated from a bag directory at any time.
|
|
45
|
+
|
|
46
|
+
```mermaid
|
|
47
|
+
graph LR
|
|
48
|
+
subgraph A[Object directory]
|
|
49
|
+
AA[Must contain files
|
|
50
|
+
that belong to the digital object,
|
|
51
|
+
plus 'DC.xml',
|
|
52
|
+
'object.csv', and
|
|
53
|
+
'datastreams.csv']
|
|
54
|
+
end
|
|
55
|
+
subgraph B[BAG]
|
|
56
|
+
BB[Data structure
|
|
57
|
+
in Bag format
|
|
58
|
+
that can be ingested,
|
|
59
|
+
i.e. one
|
|
60
|
+
Bag directory
|
|
61
|
+
per digital object]
|
|
62
|
+
end
|
|
63
|
+
B[BAG] -->|gamster unpack| A[Object directory]
|
|
64
|
+
|
|
65
|
+
```
|
|
66
|
+
At the moment, only a command-line interface (CLI) is available. A GUI is planned.
|
|
67
|
+
|
|
68
|
+
## Installation
|
|
69
|
+
|
|
70
|
+
### Without explicit installation
|
|
71
|
+
|
|
72
|
+
If the user has `uv` installed, `gamster` can be run directly without prior
|
|
73
|
+
installation via `uvx gamster` (or `uv tool install gamster`).
|
|
74
|
+
If needed, a suitable Python installation and virtual environment are created
|
|
75
|
+
in the background.
|
|
76
|
+
|
|
77
|
+
### Traditional installation
|
|
78
|
+
|
|
79
|
+
`pip install gamster`. We strongly recommend using a dedicated virtual
|
|
80
|
+
environment for this.
|
|
81
|
+
`gamster` and `gamspreprocessing` can be installed in the same virtual
|
|
82
|
+
environment.
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
## Usage
|
|
86
|
+
## Create Bags from object directories
|
|
87
|
+
|
|
88
|
+
`gamster create` creates Bags.
|
|
89
|
+
|
|
90
|
+
In the simplest form, this command is sufficient:
|
|
91
|
+
```
|
|
92
|
+
gamster create <PATH>
|
|
93
|
+
```
|
|
94
|
+
|
|
95
|
+
* `PATH` can be a single object directory or a
|
|
96
|
+
directory that contains multiple object directories.
|
|
97
|
+
|
|
98
|
+
By default, the generated Bags are created in the `./bags` directory.
|
|
99
|
+
|
|
100
|
+
`gamster create` supports several options that control its behavior. Details
|
|
101
|
+
are available via `gamster create --help` or in the
|
|
102
|
+
[Online-Dokumentation](https://dhgraz.github.io/gamster/)
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
## Convert Bags into an object directory
|
|
107
|
+
|
|
108
|
+
To create an object directory from a Bag, this command is sufficient:
|
|
109
|
+
`gamster unpack <PATH>`. `PATH` is either the path to the bag to unpack or
|
|
110
|
+
to a directory that contains bags to unpack (these are also searched for in
|
|
111
|
+
subdirectories). `unpack` can handle both bag directories and zipped bags.
|
|
112
|
+
Here is a complete example that converts all bags in the `bags` directory into
|
|
113
|
+
object directories and creates them in the `objects` directory:
|
|
114
|
+
|
|
115
|
+
```
|
|
116
|
+
gamster unpack -o objects bags
|
|
117
|
+
```
|
|
118
|
+
|
|
119
|
+
All available options are shown via `gamster unpack --help` and in the
|
|
120
|
+
[online documentation](https://dhgraz.github.io/gamster/).
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
gamster/__init__.py,sha256=1yJAeDxJEgw9hQmFkz80x9kqNMvCijHBIXyFv9kkW_Y,268
|
|
2
|
+
gamster/cli.py,sha256=1p2ykkHgnNL8MFgL8twjwwODALqHA43Y1Tz-qU5HMR8,4874
|
|
3
|
+
gamster/create_bag.py,sha256=PFyQwsSwyZcH2I7PgqGrRn1MekromFoCgYrKMrSDgbI,7634
|
|
4
|
+
gamster/loggers.py,sha256=ALGaLpO9SWUseMtm_C4EoC1Y5VyPqqmFaeCwc9mRFLo,1749
|
|
5
|
+
gamster/unpack.py,sha256=YbpgK9Q1EuCaH2sD42HPsai0eOGDqWEyPpe9KuLUtcM,5592
|
|
6
|
+
gamster-0.6.4.dist-info/METADATA,sha256=FO-LQIWn1ibPM4m94-TdndcbjomwqYAC6V85nSsScSc,3406
|
|
7
|
+
gamster-0.6.4.dist-info/WHEEL,sha256=lCkmxWfQsSc9CfIClYeavTdQeEX2toPqufh9gI35EQA,87
|
|
8
|
+
gamster-0.6.4.dist-info/entry_points.txt,sha256=zsAhKQJJNykw9utvOqqZcoLaRrJXSUbjTbCTFj9NKkQ,71
|
|
9
|
+
gamster-0.6.4.dist-info/licenses/LICENSE,sha256=iz1i7O_z7YwcEXyf1ymFU6WyPqTt3DgOTp1LZAKFRtM,1070
|
|
10
|
+
gamster-0.6.4.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Vasold Gunter
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|