mediaferry 0.2.1__tar.gz

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.
@@ -0,0 +1,112 @@
1
+ Creative Commons Legal Code
2
+
3
+ CC0 1.0 Universal
4
+
5
+ Statement of Purpose
6
+
7
+ The laws of most jurisdictions throughout the world automatically confer
8
+ exclusive Copyright and Related Rights (defined below) upon the creator
9
+ and subsequent owner(s) (each and all, an "owner") of an original work of
10
+ authorship and/or a database (each, a "Work").
11
+
12
+ Certain owners wish to permanently relinquish those rights to a Work for
13
+ the purpose of contributing to a commons of creative, cultural and
14
+ scientific works ("Commons") that the public can reliably and without fear
15
+ of later claims of infringement build upon, modify, incorporate in other
16
+ works, reuse and redistribute as freely as possible in any form whatsoever
17
+ and for any purposes, including without limitation commercial purposes.
18
+ These owners may contribute to the Commons to promote the ideal of a free
19
+ culture and the further production of creative, cultural and scientific
20
+ works, or to gain reputation or greater distribution for their Work in
21
+ part through the use and efforts of others.
22
+
23
+ For these and/or other purposes and motivations, and without any
24
+ expectation of additional consideration or compensation, the person
25
+ associating CC0 with a Work (the "Affirmer"), to the extent that he or she
26
+ is an owner of Copyright and Related Rights in the Work, voluntarily
27
+ elects to apply CC0 to the Work and publicly distribute the Work under its
28
+ terms, with knowledge of his or her Copyright and Related Rights in the
29
+ Work and the meaning and intended legal effect of CC0 on those rights.
30
+
31
+ 1. Copyright and Related Rights. A Work made available under CC0 may be
32
+ protected by copyright and related or neighboring rights ("Copyright and
33
+ Related Rights"). Copyright and Related Rights include, but are not
34
+ limited to, the following:
35
+
36
+ i. the right to reproduce, adapt, distribute, perform, display,
37
+ communicate, and translate a Work;
38
+ ii. moral rights retained by the original author(s) and/or performer(s);
39
+ iii. publicity and privacy rights pertaining to a person's image or
40
+ likeness depicted in a Work;
41
+ iv. rights protecting against unfair competition in regards to a Work,
42
+ subject to the limitations in paragraph 4(a), below;
43
+ v. rights protecting the extraction, dissemination, use and reuse of data
44
+ in a Work;
45
+ vi. database rights (such as those arising under Directive 96/9/EC of the
46
+ European Parliament and of the Council of 11 March 1996 on the legal
47
+ protection of databases, and under any national implementation
48
+ thereof, including any amended or successor version of such
49
+ directive); and
50
+ vii. other similar, equivalent or corresponding rights throughout the
51
+ world based on applicable law or treaty, and any national
52
+ implementations thereof.
53
+
54
+ 2. Waiver. To the greatest extent permitted by, but not in contravention
55
+ of, applicable law, Affirmer hereby overtly, fully, permanently,
56
+ irrevocably and unconditionally waives, abandons, and surrenders all of
57
+ Affirmer's Copyright and Related Rights and associated claims and causes
58
+ of action, whether now known or unknown (including existing as well as
59
+ future claims and causes of action), in the Work (i) in all territories
60
+ worldwide, (ii) for the maximum duration provided by applicable law or
61
+ treaty (including future time extensions), (iii) in any current or future
62
+ medium and for any number of copies, and (iv) for any purpose whatsoever,
63
+ including without limitation commercial, advertising or promotional
64
+ purposes (the "Waiver"). Affirmer makes the Waiver for the benefit of each
65
+ member of the public at large and to the detriment of Affirmer's heirs and
66
+ successors, fully intending that such Waiver shall not be subject to
67
+ revocation, rescission, cancellation, termination, or any other legal or
68
+ equitable action to disrupt the quiet enjoyment of the Work by the public
69
+ as contemplated by Affirmer's express Statement of Purpose.
70
+
71
+ 3. Public License Fallback. Should any part of the Waiver for any reason
72
+ be judged legally invalid or ineffective under applicable law, then the
73
+ Waiver shall be preserved to the maximum extent permitted taking into
74
+ account Affirmer's express Statement of Purpose. In addition, to the
75
+ extent the Waiver is so judged Affirmer hereby grants to each affected
76
+ person a royalty-free, non transferable, non sublicensable, non exclusive,
77
+ irrevocable and unconditional license to exercise Affirmer's Copyright and
78
+ Related Rights in the Work (i) in all territories worldwide, (ii) for the
79
+ maximum duration provided by applicable law or treaty (including future
80
+ time extensions), (iii) in any current or future medium and for any number
81
+ of copies, and (iv) for any purpose whatsoever, including without
82
+ limitation commercial, advertising or promotional purposes (the
83
+ "License"). The License shall be deemed effective as of the date CC0 was
84
+ applied by Affirmer to the Work. Should any part of the License for any
85
+ reason be judged legally invalid or ineffective under applicable law, such
86
+ partial invalidity or ineffectiveness shall not invalidate the remainder
87
+ of the License, and in such case Affirmer hereby affirms that he or she
88
+ will not (i) exercise any of his or her remaining Copyright and Related
89
+ Rights in the Work or (ii) assert any associated claims and causes of
90
+ action with respect to the Work, in either case contrary to Affirmer's
91
+ express Statement of Purpose.
92
+
93
+ 4. Limitations and Disclaimers.
94
+
95
+ a. No trademark or patent rights held by Affirmer are waived, abandoned,
96
+ surrendered, licensed or otherwise affected by this document.
97
+ b. Affirmer offers the Work as-is and makes no representations or
98
+ warranties of any kind concerning the Work, express, implied,
99
+ statutory or otherwise, including without limitation warranties of
100
+ title, merchantability, fitness for a particular purpose, non
101
+ infringement, or the absence of latent or other defects, accuracy, or
102
+ the present or absence of errors, whether or not discoverable, all to
103
+ the greatest extent permissible under applicable law.
104
+ c. Affirmer disclaims responsibility for clearing rights of other persons
105
+ that may apply to the Work or any use thereof, including without
106
+ limitation any person's Copyright and Related Rights in the Work.
107
+ Further, Affirmer disclaims responsibility for obtaining any necessary
108
+ consents, permissions or other rights required for any use of the
109
+ Work.
110
+ d. Affirmer understands and acknowledges that Creative Commons is not a
111
+ party to this document and has no duty or obligation with respect to
112
+ this CC0 or use of the Work.
@@ -0,0 +1,40 @@
1
+ Metadata-Version: 2.4
2
+ Name: mediaferry
3
+ Version: 0.2.1
4
+ Summary: yt-dlp download management tool
5
+ License-File: LICENSE
6
+ Author: DigitalDragon
7
+ Requires-Python: >=3.8
8
+ Classifier: Programming Language :: Python :: 3
9
+ Classifier: Programming Language :: Python :: 3.8
10
+ Classifier: Programming Language :: Python :: 3.9
11
+ Classifier: Programming Language :: Python :: 3.10
12
+ Classifier: Programming Language :: Python :: 3.11
13
+ Classifier: Programming Language :: Python :: 3.12
14
+ Classifier: Programming Language :: Python :: 3.13
15
+ Classifier: Programming Language :: Python :: 3.14
16
+ Requires-Dist: dataclasses-json
17
+ Requires-Dist: humanize
18
+ Requires-Dist: internetarchive (>=5.0.3)
19
+ Requires-Dist: yt-dlp
20
+ Project-URL: Repository, https://github.com/DigitalDwagon/MediaFerry
21
+ Description-Content-Type: text/markdown
22
+
23
+ mediaferry is a simple CLI interface to download videos with yt-dlp in a consistent format that can be later uploaded to the Internet Archive with a tool like `dartboard`
24
+
25
+
26
+ ```
27
+ usage: mediaferry [-h] [--verbose] [--force] [--metadata METADATA] [--cookies COOKIES] url
28
+
29
+ MediaFerry
30
+
31
+ positional arguments:
32
+ url URL of the media to download
33
+
34
+ options:
35
+ -h, --help show this help message and exit
36
+ --verbose Enable verbose output
37
+ --force Force download even if an archive.org item already exists
38
+ --metadata METADATA Add metadata as key:value pairs
39
+ --cookies COOKIES Path to a cookies.txt file to use for downloading
40
+ ```
@@ -0,0 +1,18 @@
1
+ mediaferry is a simple CLI interface to download videos with yt-dlp in a consistent format that can be later uploaded to the Internet Archive with a tool like `dartboard`
2
+
3
+
4
+ ```
5
+ usage: mediaferry [-h] [--verbose] [--force] [--metadata METADATA] [--cookies COOKIES] url
6
+
7
+ MediaFerry
8
+
9
+ positional arguments:
10
+ url URL of the media to download
11
+
12
+ options:
13
+ -h, --help show this help message and exit
14
+ --verbose Enable verbose output
15
+ --force Force download even if an archive.org item already exists
16
+ --metadata METADATA Add metadata as key:value pairs
17
+ --cookies COOKIES Path to a cookies.txt file to use for downloading
18
+ ```
File without changes
@@ -0,0 +1,4 @@
1
+ import importlib.metadata
2
+
3
+ version : str = importlib.metadata.version(__package__ or __name__)
4
+ yt_dlp_version : str = importlib.metadata.version("yt-dlp")
@@ -0,0 +1,9 @@
1
+ from dataclasses import dataclass, field
2
+
3
+
4
+ @dataclass
5
+ class Config:
6
+ force: bool = False
7
+ verbose: bool = False
8
+ metadata: dict = field(default_factory=dict)
9
+ cookies: str = None
@@ -0,0 +1,180 @@
1
+ import json
2
+ import os
3
+ import re
4
+ from datetime import datetime
5
+ from urllib.parse import urlparse
6
+
7
+ import internetarchive
8
+ import humanize
9
+ import yt_dlp
10
+
11
+ from mediaferry.__version__ import version, yt_dlp_version
12
+
13
+ class Media:
14
+ def __init__(self, media_info: dict):
15
+ self.url = media_info["webpage_url"]
16
+ self.id = media_info.get("display_id", media_info.get("id"))
17
+ self.extractor = media_info["extractor"]
18
+ self.media_info = media_info
19
+
20
+
21
+ def get_identifier(self):
22
+ return re.sub(r'[^\w-]', "-", f"{self.extractor}-{self.id}")
23
+
24
+ def internetarchive_item_exists(self):
25
+ item = internetarchive.get_item(self.get_identifier())
26
+ return item.exists
27
+
28
+ def download(self, config):
29
+ print(f"Downloading {self.url} ({self.get_identifier()})...")
30
+ if not config.force and self.internetarchive_item_exists():
31
+ print(f"Item {self.get_identifier()} already exists on archive.org. If you want to download it anyways, use --force.")
32
+ print(f"https://archive.org/details/{self.get_identifier()}")
33
+ return False
34
+
35
+ directory = os.path.abspath(self.get_identifier())
36
+ os.makedirs(directory, exist_ok=True)
37
+
38
+ options = get_ytdlp_options(config, self.get_identifier())
39
+ options["progress_hooks"] = [progress_hook]
40
+ with yt_dlp.YoutubeDL(options) as ydl:
41
+ status_code = ydl.download([self.url])
42
+
43
+ if status_code != 0:
44
+ print(f"Error downloading {self.url} (exit status {status_code}).")
45
+
46
+ print(f"Downloaded {self.url} to {self.get_identifier()}.")
47
+ print("Generating metadata...")
48
+ metadata = self.get_internetarchive_metadata()
49
+ print(json.dumps(metadata, indent=4))
50
+
51
+ # Safety check - if there isn't an MKV, the video wasn't downloaded.
52
+ if not any(fname.endswith(".mkv") for fname in os.listdir(directory)):
53
+ print(f"Error: No MKV file found in {directory}. Did the download or remux fail?")
54
+ with open(os.path.join(directory, "__ia_meta.json.failed_download"), "a") as f:
55
+ f.write(json.dumps(metadata, indent=4))
56
+ return False
57
+
58
+ with open(os.path.join(directory, "__ia_meta.json"), "a") as f:
59
+ f.write(json.dumps(metadata, indent=4))
60
+
61
+ # delete empty description files, consistent with tubeup
62
+ for filename in os.listdir(directory):
63
+ if filename.endswith(".description"):
64
+ filepath = os.path.join(directory, filename)
65
+ if os.path.getsize(filepath) == 0:
66
+ os.remove(filepath)
67
+ print(f"Removed empty description file {filepath}")
68
+
69
+
70
+
71
+
72
+
73
+ def get_internetarchive_metadata(self):
74
+ ia_metadata = {
75
+ 'scanner': [f'mediaferry (v{version})', f'yt-dlp (v{yt_dlp_version})'],
76
+ 'scandate': datetime.now().isoformat(),
77
+ 'collection': 'opensource_movies',
78
+ 'mediatype': 'movies'
79
+ }
80
+
81
+ # yt-dlp metadata -> IA item metadata
82
+ alias_keys = {
83
+ 'title': 'title',
84
+ 'description': 'description',
85
+ 'webpage_url': 'originalurl',
86
+ 'uploader': 'creator',
87
+ 'uploader_url': 'channel',
88
+ 'channel_url': 'channel',
89
+ }
90
+
91
+ for key, value in alias_keys.items():
92
+ if key in self.media_info and not value in ia_metadata:
93
+ ia_metadata[value] = re.sub('\r?\n', '<br>', self.media_info[key])
94
+
95
+ if urlparse(self.url).netloc == 'soundcloud.com':
96
+ ia_metadata['collection'] = 'opensource_audio'
97
+ ia_metadata['mediatype'] = 'audio'
98
+
99
+ if self.media_info.get('extractor_key') == 'TwitchClips' and self.media_info.get('creator', False):
100
+ ia_metadata['creator'] = self.media_info.get('creator')
101
+
102
+ if 'upload_date' in self.media_info:
103
+ date = datetime.strptime(self.media_info['upload_date'], '%Y%m%d')
104
+ ia_metadata["date"] = date.strftime('%Y-%m-%d')
105
+
106
+ subject = ["video", self.media_info.get('extractor_key')]
107
+ if 'categories' in self.media_info:
108
+ subject.extend(self.media_info['categories'])
109
+ if 'tags' in self.media_info:
110
+ subject.extend(self.media_info['tags'])
111
+ while len(";".join(subject).encode("utf-8")) > 255:
112
+ subject.pop()
113
+ ia_metadata['subject'] = ";".join(subject)
114
+
115
+ return ia_metadata
116
+
117
+
118
+ def progress_hook(d):
119
+ if True:
120
+ return
121
+ # causing errors
122
+
123
+ if d['status'] == 'downloading':
124
+ print("Downloading %s: %s/%s at %s/s, %s" % (
125
+ d.get('filename', '(unknown)'),
126
+ humanize.naturalsize(d.get('downloaded_bytes', 0)),
127
+ humanize.naturalsize(d.get('total_bytes', d.get('total_bytes_estimate', 0))),
128
+ humanize.naturalsize(d.get('speed', 0)),
129
+ d.get('eta', 'unknown')
130
+ ))
131
+
132
+ if d['status'] == 'finished':
133
+ print("Done downloading %s: %s at %s/s" % (
134
+ d.get('filename', '(unknown)'),
135
+ humanize.naturalsize(d.get('total_bytes', 0)),
136
+ humanize.naturalsize(d.get('total_bytes', 0) / d.get('elapsed', 1))
137
+ ))
138
+
139
+ if d['status'] == 'error':
140
+ print(json.dumps(d))
141
+ print("Error downloading...")
142
+
143
+
144
+ def get_ytdlp_options(config, directory) -> dict:
145
+ ytdlp_options = {
146
+ "outtmpl": os.path.join(directory, "%(id)s.%(ext)s"),
147
+ "restrictfilenames": True,
148
+ "quiet": not config.verbose,
149
+ "verbose": config.verbose,
150
+ "progress_with_newline": True,
151
+ "forcetitle": True,
152
+ "continuedl": True,
153
+ "retries": 3,
154
+ "fragment_retries": 3,
155
+ "forcejson": False,
156
+ "writeinfojson": True,
157
+ "writedescription": True,
158
+ "writethumbnail": True,
159
+ "writeannotations": True,
160
+ "writesubtitles": True,
161
+ "allsubtitles": True,
162
+ "ignoreerrors": True, # Allow full-channel downloads to continue even if some videos fail
163
+ "fixup": "detect_or_warn",
164
+ "nooverwrites": True, # Don't re-download files that already exist (ex. manual retry)
165
+ "consoletitle": True,
166
+ "prefer_ffmpeg": True,
167
+ "call_home": False,
168
+ "cookiefile": config.cookies,
169
+ "merge_output_format": "mkv"
170
+ #"proxy": args.proxy,
171
+ #"username": args.username,
172
+ #"password": args.password,
173
+ }
174
+
175
+ for key, value in list(ytdlp_options.items()):
176
+ if value is None:
177
+ del ytdlp_options[key]
178
+
179
+ return ytdlp_options
180
+
@@ -0,0 +1,53 @@
1
+ import argparse
2
+ import json
3
+ import os
4
+ from collections import defaultdict
5
+
6
+ from yt_dlp import YoutubeDL
7
+
8
+ from mediaferry.config import Config
9
+ from mediaferry.download import Media, get_ytdlp_options
10
+
11
+
12
+ def main():
13
+
14
+ parser = argparse.ArgumentParser(description="MediaFerry")
15
+ parser.add_argument("--verbose", action="store_true", help="Enable verbose output")
16
+ parser.add_argument("--force", action="store_true", help="Force download even if an archive.org item already exists")
17
+ parser.add_argument("url", help="URL of the media to download")
18
+ parser.add_argument("--metadata", action=ParseMetadata, default=defaultdict(list), help="Add metadata as key:value pairs")
19
+ # yt-dlp options
20
+ parser.add_argument("--cookies", type=str, default=None, help="Path to a cookies.txt file to use for downloading")
21
+ args = parser.parse_args()
22
+
23
+ config_args = {key: value for key, value in vars(args).items() if key != "url"}
24
+ config = Config(**config_args)
25
+ download_media(args.url, config)
26
+
27
+ def download_media(url, config):
28
+ print(f"Discovering {url}")
29
+ with YoutubeDL(get_ytdlp_options(config, ".")) as ydl:
30
+ media_info = ydl.sanitize_info(ydl.extract_info(url, download=False))
31
+
32
+ if media_info.get("_type", "video") == "playlist":
33
+ print("Found playlist!")
34
+ for entry in media_info["entries"]:
35
+ print(f"Downloading playlist entry {entry['webpage_url']}")
36
+ media: Media = Media(entry)
37
+ media.download(config)
38
+ else:
39
+ media: Media = Media(media_info)
40
+ media.download(config)
41
+
42
+ class ParseMetadata(argparse.Action):
43
+ def __call__(self, parser, namespace, values, option_string=None):
44
+ metadata = getattr(namespace, self.dest, defaultdict(list))
45
+ key, value = values.split(":", 1)
46
+ metadata[key].append(value)
47
+ setattr(namespace, self.dest, metadata)
48
+
49
+
50
+
51
+
52
+ if __name__ == "__main__":
53
+ main()
@@ -0,0 +1,25 @@
1
+ [build-system]
2
+ requires = ["poetry-core>=2.0.0,<3.0.0"]
3
+ build-backend = "poetry.core.masonry.api"
4
+
5
+ [project]
6
+ name = "mediaferry"
7
+ version = "0.2.1"
8
+ authors = [
9
+ {name = "DigitalDragon"}
10
+ ]
11
+ description = "yt-dlp download management tool"
12
+ readme = "README.md"
13
+ requires-python = ">=3.8"
14
+ dependencies = [
15
+ "internetarchive>=5.0.3",
16
+ "dataclasses-json",
17
+ "yt-dlp",
18
+ "humanize"
19
+ ]
20
+
21
+ [project.scripts]
22
+ mediaferry = "mediaferry.main:main"
23
+
24
+ [project.urls]
25
+ repository = "https://github.com/DigitalDwagon/MediaFerry"