hwg-ml-cli 0.1.0__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.

Potentially problematic release.


This version of hwg-ml-cli might be problematic. Click here for more details.

@@ -0,0 +1,9 @@
1
+ Metadata-Version: 2.4
2
+ Name: hwg-ml-cli
3
+ Version: 0.1.0
4
+ Summary: Add your description here
5
+ Requires-Python: >=3.13
6
+ Description-Content-Type: text/markdown
7
+ Requires-Dist: click>=8.5.0
8
+ Requires-Dist: requests>=2.34.2
9
+ Requires-Dist: tqdm>=4.70.0
@@ -0,0 +1,12 @@
1
+ src/__init__.py,sha256=Bk9y2irMgREfqa1Cd15nwzRXm5IbiUdcU8hXrA4OmTA,68
2
+ src/api.py,sha256=-RMHCuBplThJ_V8wHKYsaYZc8-GzPFzFFleW95xtqdA,2937
3
+ src/cli.py,sha256=eJUPepMSZI-U_FlK40yec9y9Frba_r46ot14eRgcCMc,4053
4
+ src/commands.py,sha256=xyRk2fCGxKl_F-D2aAmD-3T9j3ACWVYAdSxWZSHR3ac,3600
5
+ src/config.py,sha256=3Rv4WBInX-2ZCArtI8mEg-KTBCLNvFEuSPB3h7q_6ew,1705
6
+ src/download.py,sha256=mgZ5povMlKVH4p7amvaILSvUXLQUo-IU8Nu8_jSrxoU,3707
7
+ src/submit.py,sha256=pk3mbxYq-vJG8o-m1Jp_DNLudQC69l37C-oZrv1Dq2E,10371
8
+ hwg_ml_cli-0.1.0.dist-info/METADATA,sha256=0usR6RfTAUd-ynjE9nS-LNrU96Z2UXENTrbYMjlMDDI,241
9
+ hwg_ml_cli-0.1.0.dist-info/WHEEL,sha256=YVMoNqKzERt-wjUZwJ33xBGAwnFl-4cqbYkTtWa4itE,91
10
+ hwg_ml_cli-0.1.0.dist-info/entry_points.txt,sha256=awZeFnzrxxR-0XWGn6zg6VX0vdavhf-uEy273kiekJA,35
11
+ hwg_ml_cli-0.1.0.dist-info/top_level.txt,sha256=74rtVfumQlgAPzR5_2CgYN24MB0XARCg0t-gzk6gTrM,4
12
+ hwg_ml_cli-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.0.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ hwg-ml = src:cli
@@ -0,0 +1 @@
1
+ src
src/__init__.py ADDED
@@ -0,0 +1,7 @@
1
+ """
2
+ HWG-ML CLI Package
3
+ """
4
+
5
+ from .cli import cli
6
+
7
+ __all__ = ["cli"]
src/api.py ADDED
@@ -0,0 +1,100 @@
1
+ """
2
+ API client functions for fetching course data from the H4HN CMS.
3
+ """
4
+
5
+ import click
6
+ import requests
7
+
8
+ from .config import API_COURSES, API_LECTURES
9
+
10
+
11
+ def fetch_course_data(course_name):
12
+ """Fetch course data from API and return the target course."""
13
+ response = requests.get(API_COURSES, params={"populate": "lectures"})
14
+
15
+ if response.status_code != 200:
16
+ return (
17
+ None,
18
+ f"Failed to fetch data from API (status code: {response.status_code})",
19
+ )
20
+
21
+ courses = response.json().get("data", [])
22
+
23
+ # Find matching course
24
+ for course in courses:
25
+ if course.get("name") == course_name or course.get("slug") == course_name:
26
+ return course, None
27
+
28
+ # Course not found - prepare error message with available courses
29
+ available = "\n".join(
30
+ [f" - {c.get('name')} (slug: {c.get('slug')})" for c in courses]
31
+ )
32
+ return None, f"Course '{course_name}' not found\n\nAvailable courses:\n{available}"
33
+
34
+
35
+ def fetch_exercise_files(exercise_ids):
36
+ """Fetch detailed exercise data with files from API."""
37
+ response = requests.get(
38
+ API_LECTURES,
39
+ params={
40
+ "filters[documentId][$in]": exercise_ids,
41
+ "filters[type][$eq]": "exercise",
42
+ "populate": "*",
43
+ },
44
+ )
45
+
46
+ if response.status_code != 200:
47
+ return (
48
+ None,
49
+ f"Failed to fetch exercise files (status code: {response.status_code})",
50
+ )
51
+
52
+ return response.json().get("data", []), None
53
+
54
+
55
+ def fetch_lecture_files(lecture_ids):
56
+ """Fetch detailed lecture data with files from API."""
57
+ response = requests.get(
58
+ API_LECTURES,
59
+ params={
60
+ "filters[documentId][$in]": lecture_ids,
61
+ "filters[type][$eq]": "lecture",
62
+ "populate": "*",
63
+ },
64
+ )
65
+
66
+ if response.status_code != 200:
67
+ return (
68
+ None,
69
+ f"Failed to fetch lecture files (status code: {response.status_code})",
70
+ )
71
+
72
+ return response.json().get("data", []), None
73
+
74
+
75
+ def process_course_items(course, item_type, fetch_func):
76
+ """Common logic to fetch and sort course items (exercises or lectures)."""
77
+ # Get items from course
78
+ all_lectures = course.get("lectures", [])
79
+ items = [l for l in all_lectures if l.get("type") == item_type]
80
+
81
+ if not items:
82
+ return None, f"No {item_type}s found in course: {course.get('name')}"
83
+
84
+ click.echo(f"Found {len(items)} {item_type}(s) in course: {course.get('name')}")
85
+ click.echo(f"Fetching {item_type} files...")
86
+
87
+ # Fetch detailed data with files
88
+ item_ids = [item.get("documentId") for item in items]
89
+ items_with_files, error = fetch_func(item_ids)
90
+
91
+ if error:
92
+ return None, error
93
+
94
+ if not items_with_files:
95
+ return None, f"No {item_type}s found."
96
+
97
+ # Sort by start date
98
+ items_with_files.sort(key=lambda x: x.get("start", ""))
99
+
100
+ return items_with_files, None
src/cli.py ADDED
@@ -0,0 +1,175 @@
1
+ """
2
+ HWG-ML CLI - Main command line interface.
3
+ """
4
+
5
+ import sys
6
+ import click
7
+ import requests
8
+
9
+ from .commands import update_exercises, update_lectures
10
+ from .config import (
11
+ DEFAULT_COURSE,
12
+ DEFAULT_SUBMISSION_SERVER,
13
+ get_submission_token,
14
+ set_submission_token,
15
+ get_submission_server,
16
+ set_submission_server,
17
+ )
18
+ from .submit import submit_file
19
+
20
+
21
+ @click.group()
22
+ def cli():
23
+ """Utility commands for HWG-ML."""
24
+ pass
25
+
26
+
27
+ @click.group()
28
+ def exercises():
29
+ """Manage course exercises."""
30
+ pass
31
+
32
+
33
+ @click.group()
34
+ def lectures():
35
+ """Manage course lectures."""
36
+ pass
37
+
38
+
39
+ @click.group()
40
+ def config():
41
+ """Manage CLI configuration."""
42
+ pass
43
+
44
+
45
+ @exercises.command()
46
+ @click.option(
47
+ "--output",
48
+ "-o",
49
+ type=click.Path(),
50
+ default="exercises",
51
+ help="Output directory for exercises",
52
+ )
53
+ @click.option(
54
+ "--course",
55
+ "-c",
56
+ type=str,
57
+ default=DEFAULT_COURSE,
58
+ help="Course name or slug to filter exercises",
59
+ )
60
+ def update(output, course):
61
+ """Download new exercises from the H4HN CMS API."""
62
+ return update_exercises(output, course)
63
+
64
+
65
+ @lectures.command()
66
+ @click.option(
67
+ "--output",
68
+ "-o",
69
+ type=click.Path(),
70
+ default="lectures",
71
+ help="Output directory for lecture slides",
72
+ )
73
+ @click.option(
74
+ "--course",
75
+ "-c",
76
+ type=str,
77
+ default=DEFAULT_COURSE,
78
+ help="Course name or slug to filter lectures",
79
+ )
80
+ def update(output, course):
81
+ """Download lecture slides from the H4HN CMS API."""
82
+ return update_lectures(output, course)
83
+
84
+
85
+ @config.command()
86
+ @click.option(
87
+ "--token",
88
+ "-t",
89
+ required=True,
90
+ help="Access token for authentication",
91
+ )
92
+ @click.option(
93
+ "--server",
94
+ "-s",
95
+ default=DEFAULT_SUBMISSION_SERVER,
96
+ help="Submission server URL",
97
+ )
98
+ def init(token, server):
99
+ """Initialize submission configuration with your token."""
100
+ set_submission_token(token)
101
+ set_submission_server(server)
102
+ click.echo(f"✅ Configuration saved!")
103
+ click.echo(f" Token: {token[:8]}...")
104
+ click.echo(f" Server: {server}")
105
+
106
+
107
+ @config.command()
108
+ def show():
109
+ """Show current configuration."""
110
+ token = get_submission_token()
111
+ server = get_submission_server()
112
+
113
+ if token:
114
+ click.echo(f"Token: {token[:8]}...")
115
+ else:
116
+ click.echo("Token: Not configured")
117
+
118
+ click.echo(f"Server: {server}")
119
+
120
+
121
+ @click.command()
122
+ @click.argument("file", type=click.Path(exists=True))
123
+ @click.option(
124
+ "--token",
125
+ "-t",
126
+ default=None,
127
+ help="Access token for authentication (uses stored token if not provided)",
128
+ )
129
+ @click.option(
130
+ "--server",
131
+ "-s",
132
+ default=None,
133
+ help="Submission server URL (uses stored server if not provided)",
134
+ )
135
+ def submit(file, token, server):
136
+ """Submit a file or directory to the submission platform. Directories are automatically zipped."""
137
+ # Use stored token if not provided
138
+ if token is None:
139
+ token = get_submission_token()
140
+ if token is None:
141
+ click.echo(
142
+ "❌ Error: No token provided and no token configured.",
143
+ err=True,
144
+ )
145
+ click.echo(
146
+ " Run 'hwg-ml config init --token YOUR_TOKEN' to configure your token.",
147
+ err=True,
148
+ )
149
+ sys.exit(1)
150
+
151
+ # Use stored server if not provided
152
+ if server is None:
153
+ server = get_submission_server()
154
+ try:
155
+ result = submit_file(file, token, server)
156
+ sys.exit(0)
157
+ except FileNotFoundError as e:
158
+ click.echo(f"❌ Error: {e}", err=True)
159
+ sys.exit(1)
160
+ except requests.HTTPError as e:
161
+ click.echo(f"❌ HTTP Error: {e}", err=True)
162
+ if e.response is not None:
163
+ try:
164
+ error_detail = e.response.json()
165
+ click.echo(f" Details: {error_detail}", err=True)
166
+ except:
167
+ click.echo(f" Response: {e.response.text}", err=True)
168
+ sys.exit(1)
169
+ except Exception as e:
170
+ click.echo(f"❌ Unexpected error: {e}", err=True)
171
+ sys.exit(1)
172
+
173
+
174
+ if __name__ == "__main__":
175
+ cli()
src/commands.py ADDED
@@ -0,0 +1,125 @@
1
+ """
2
+ CLI command implementations for exercises and lectures.
3
+ """
4
+
5
+ from pathlib import Path
6
+
7
+ import click
8
+
9
+ from .api import (
10
+ fetch_course_data,
11
+ fetch_exercise_files,
12
+ fetch_lecture_files,
13
+ process_course_items,
14
+ )
15
+ from .config import DEFAULT_COURSE
16
+ from .download import (
17
+ download_and_extract_file,
18
+ download_lecture_file,
19
+ extract_exercise_number,
20
+ )
21
+
22
+
23
+ def update_exercises(output, course):
24
+ """Download new exercises from the H4HN CMS API."""
25
+ click.echo(f"Fetching course: {course}...")
26
+
27
+ # Fetch course data
28
+ target_course, error = fetch_course_data(course)
29
+ if error:
30
+ click.echo(f"❌ Error: {error}", err=True)
31
+ return 1
32
+
33
+ # Fetch and sort exercises
34
+ exercises_with_files, error = process_course_items(
35
+ target_course, "exercise", fetch_exercise_files
36
+ )
37
+ if error:
38
+ click.echo(f"❌ Error: {error}", err=True)
39
+ return 0 if "No exercise" in error else 1
40
+
41
+ # Create output directory
42
+ output_path = Path(output)
43
+ output_path.mkdir(parents=True, exist_ok=True)
44
+
45
+ # Process each exercise
46
+ for exercise in exercises_with_files:
47
+ topic = exercise.get("topic", "Unknown")
48
+ files = exercise.get("files", [])
49
+
50
+ if not files:
51
+ click.echo(f" ⚠️ {topic}: No files available")
52
+ continue
53
+
54
+ click.echo(f" 📦 {topic}: {len(files)} file(s)")
55
+
56
+ for file_info in files:
57
+ file_name = file_info.get("name", "unknown.zip")
58
+ exercise_num = extract_exercise_number(file_name)
59
+
60
+ if not exercise_num:
61
+ click.echo(
62
+ f" ⚠️ Skipping {file_name} - couldn't determine exercise number"
63
+ )
64
+ continue
65
+
66
+ # Download and extract file
67
+ result = download_and_extract_file(file_info, exercise_num, output_path)
68
+ click.echo(f" {result}")
69
+
70
+ click.echo(f"\n✓ All exercises extracted to {output_path}")
71
+ return 0
72
+
73
+
74
+ def update_lectures(output, course):
75
+ """Download lecture slides from the H4HN CMS API."""
76
+ click.echo(f"Fetching course: {course}...")
77
+
78
+ # Fetch course data
79
+ target_course, error = fetch_course_data(course)
80
+ if error:
81
+ click.echo(f"❌ Error: {error}", err=True)
82
+ return 1
83
+
84
+ # Fetch and sort lectures
85
+ lectures_with_files, error = process_course_items(
86
+ target_course, "lecture", fetch_lecture_files
87
+ )
88
+ if error:
89
+ click.echo(f"❌ Error: {error}", err=True)
90
+ return 0 if "No lecture" in error else 1
91
+
92
+ # Create output directory
93
+ output_path = Path(output)
94
+ output_path.mkdir(parents=True, exist_ok=True)
95
+
96
+ # Process each lecture
97
+ downloaded_count = 0
98
+ for lecture in lectures_with_files:
99
+ topic = lecture.get("topic", "Unknown")
100
+ files = lecture.get("files", [])
101
+
102
+ if not files:
103
+ continue
104
+
105
+ # Filter for PDF files
106
+ pdf_files = [f for f in files if f.get("name", "").lower().endswith(".pdf")]
107
+
108
+ if not pdf_files:
109
+ continue
110
+
111
+ click.echo(f" 📄 {topic}: {len(pdf_files)} PDF(s)")
112
+
113
+ for file_info in pdf_files:
114
+ result = download_lecture_file(file_info, output_path)
115
+ click.echo(f" {result}")
116
+ if "✓" in result:
117
+ downloaded_count += 1
118
+
119
+ if downloaded_count > 0:
120
+ click.echo(
121
+ f"\n✓ {downloaded_count} lecture slide(s) downloaded to {output_path}"
122
+ )
123
+ else:
124
+ click.echo(f"\n⏭️ All lecture slides already downloaded in {output_path}")
125
+ return 0
src/config.py ADDED
@@ -0,0 +1,69 @@
1
+ """
2
+ Configuration constants for the
3
+ """
4
+
5
+ import json
6
+ from pathlib import Path
7
+
8
+ # API Configuration
9
+ BASE_URL = "https://cms.h4hn.de"
10
+ API_COURSES = f"{BASE_URL}/api/courses"
11
+ API_LECTURES = f"{BASE_URL}/api/lectures"
12
+ DEFAULT_COURSE = "C29331 Machine Learning"
13
+
14
+ # Submission Configuration
15
+ DEFAULT_SUBMISSION_SERVER = "https://submissions.h4hn.de"
16
+
17
+ # Config file path
18
+ CONFIG_DIR = Path.home() / ".hwg-ml"
19
+ CONFIG_FILE = CONFIG_DIR / "config.json"
20
+
21
+
22
+ def ensure_config_dir():
23
+ """Ensure the config directory exists."""
24
+ CONFIG_DIR.mkdir(parents=True, exist_ok=True)
25
+
26
+
27
+ def load_config() -> dict:
28
+ """Load configuration from the config file."""
29
+ if not CONFIG_FILE.exists():
30
+ return {}
31
+
32
+ try:
33
+ with open(CONFIG_FILE, "r") as f:
34
+ return json.load(f)
35
+ except (json.JSONDecodeError, IOError):
36
+ return {}
37
+
38
+
39
+ def save_config(config: dict):
40
+ """Save configuration to the config file."""
41
+ ensure_config_dir()
42
+ with open(CONFIG_FILE, "w") as f:
43
+ json.dump(config, f, indent=2)
44
+
45
+
46
+ def get_submission_token() -> str:
47
+ """Get the stored submission token."""
48
+ config = load_config()
49
+ return config.get("submission_token")
50
+
51
+
52
+ def set_submission_token(token: str):
53
+ """Store the submission token."""
54
+ config = load_config()
55
+ config["submission_token"] = token
56
+ save_config(config)
57
+
58
+
59
+ def get_submission_server() -> str:
60
+ """Get the configured submission server URL."""
61
+ config = load_config()
62
+ return config.get("submission_server", DEFAULT_SUBMISSION_SERVER)
63
+
64
+
65
+ def set_submission_server(server: str):
66
+ """Store the submission server URL."""
67
+ config = load_config()
68
+ config["submission_server"] = server
69
+ save_config(config)
src/download.py ADDED
@@ -0,0 +1,107 @@
1
+ """
2
+ Download and extraction utilities for exercise and lecture files.
3
+ """
4
+
5
+ import re
6
+ import zipfile
7
+ from io import BytesIO
8
+
9
+ import requests
10
+
11
+ from .config import BASE_URL
12
+
13
+
14
+ def extract_exercise_number(filename):
15
+ """Extract exercise number from filename (e.g., 'e03_solution.zip' -> 'e03')."""
16
+ match = re.match(r"(e\d+)", filename)
17
+ return match.group(1) if match else None
18
+
19
+
20
+ def is_already_downloaded(exercise_dir, exercise_num, is_solution):
21
+ """Check if exercise files are already downloaded."""
22
+ if is_solution:
23
+ marker = exercise_dir / "Solution"
24
+ return marker.exists() and any(marker.iterdir())
25
+ else:
26
+ task_marker = exercise_dir / "Task"
27
+ explanation_files = (
28
+ list(exercise_dir.glob(f"{exercise_num}_explanation.*"))
29
+ if exercise_dir.exists()
30
+ else []
31
+ )
32
+ return (
33
+ task_marker.exists() and any(task_marker.iterdir())
34
+ ) or explanation_files
35
+
36
+
37
+ def extract_zip_file(zip_content, exercise_num, exercise_dir, output_path):
38
+ """Extract zip file contents to appropriate directory."""
39
+ with zipfile.ZipFile(BytesIO(zip_content)) as zip_ref:
40
+ for zip_info in zip_ref.filelist:
41
+ # Skip macOS metadata files and directories
42
+ if "__MACOSX" in zip_info.filename or "._" in zip_info.filename:
43
+ continue
44
+ if zip_info.is_dir():
45
+ continue
46
+
47
+ # Determine target path based on zip structure
48
+ if zip_info.filename.startswith(f"{exercise_num}/"):
49
+ target_path = output_path / zip_info.filename
50
+ else:
51
+ target_path = exercise_dir / zip_info.filename
52
+
53
+ target_path.parent.mkdir(parents=True, exist_ok=True)
54
+ target_path.write_bytes(zip_ref.read(zip_info.filename))
55
+
56
+
57
+ def download_and_extract_file(file_info, exercise_num, output_path):
58
+ """Download and extract a single exercise file."""
59
+ file_url = BASE_URL + file_info.get("url", "")
60
+ file_name = file_info.get("name", "unknown.zip")
61
+ exercise_dir = output_path / exercise_num
62
+
63
+ # Check if already downloaded
64
+ is_solution = "solution" in file_name.lower()
65
+ if is_already_downloaded(exercise_dir, exercise_num, is_solution):
66
+ return f"⏭️ {file_name} - already downloaded"
67
+
68
+ # Download file
69
+ response = requests.get(file_url)
70
+ if response.status_code != 200:
71
+ return f"❌ Failed to download {file_name}"
72
+
73
+ # Extract or save file
74
+ try:
75
+ if file_name.endswith(".zip"):
76
+ extract_zip_file(response.content, exercise_num, exercise_dir, output_path)
77
+ else:
78
+ target_path = exercise_dir / file_name
79
+ target_path.parent.mkdir(parents=True, exist_ok=True)
80
+ target_path.write_bytes(response.content)
81
+ return f"✓ {file_name}"
82
+ except Exception as e:
83
+ return f"❌ Error processing {file_name}: {str(e)}"
84
+
85
+
86
+ def download_lecture_file(file_info, output_path):
87
+ """Download a single lecture PDF file."""
88
+ file_url = BASE_URL + file_info.get("url", "")
89
+ file_name = file_info.get("name", "unknown.pdf")
90
+ target_path = output_path / file_name
91
+
92
+ # Check if already downloaded
93
+ if target_path.exists():
94
+ return f"⏭️ {file_name} - already downloaded"
95
+
96
+ # Download file
97
+ response = requests.get(file_url)
98
+ if response.status_code != 200:
99
+ return f"❌ Failed to download {file_name}"
100
+
101
+ # Save file
102
+ try:
103
+ target_path.parent.mkdir(parents=True, exist_ok=True)
104
+ target_path.write_bytes(response.content)
105
+ return f"✓ {file_name}"
106
+ except Exception as e:
107
+ return f"❌ Error saving {file_name}: {str(e)}"
src/submit.py ADDED
@@ -0,0 +1,340 @@
1
+ """
2
+ CLI for submitting files to the submission platform using presigned URLs.
3
+ Supports multipart upload for large files (> 50MB).
4
+ """
5
+
6
+ import os
7
+ import tempfile
8
+ import zipfile
9
+ import requests
10
+ from concurrent.futures import ThreadPoolExecutor, as_completed
11
+ from pathlib import Path
12
+ from tqdm import tqdm
13
+
14
+
15
+ # 50MB chunk size for multipart uploads
16
+ CHUNK_SIZE = 50 * 1024 * 1024
17
+ # Threshold for using multipart upload (50MB)
18
+ MULTIPART_THRESHOLD = 50 * 1024 * 1024
19
+ MULTIPART_CONCURRENCY = 4
20
+
21
+
22
+ class PartFileReader:
23
+ """Wrapper for reading a specific part of a file with progress tracking."""
24
+
25
+ def __init__(self, file_obj, size, progress_bar):
26
+ self.file = file_obj
27
+ self.remaining = size
28
+ self.bar = progress_bar
29
+
30
+ def read(self, size=-1):
31
+ if self.remaining <= 0:
32
+ return b""
33
+
34
+ to_read = self.remaining
35
+ if size >= 0:
36
+ to_read = min(size, self.remaining)
37
+
38
+ data = self.file.read(to_read)
39
+ if data:
40
+ read_len = len(data)
41
+ self.remaining -= read_len
42
+ self.bar.update(read_len)
43
+ return data
44
+
45
+
46
+ def print_submission_success(submission_id, version, is_late):
47
+ print(f"✅ Upload complete!")
48
+ print(f" Submission ID: {submission_id}")
49
+ print(f" Version: {version}")
50
+ print(f" Status: {'LATE SUBMISSION' if is_late else 'On time'}")
51
+
52
+
53
+ def create_zip_from_directory(directory_path: Path, output_path: Path = None) -> Path:
54
+ """
55
+ Create a zip file from a directory.
56
+
57
+ Args:
58
+ directory_path: Path to the directory to zip
59
+ output_path: Optional path for the output zip file. If not provided,
60
+ creates a temporary file.
61
+
62
+ Returns:
63
+ Path to the created zip file
64
+ """
65
+ if output_path is None:
66
+ # Create temporary file
67
+ fd, temp_path = tempfile.mkstemp(
68
+ suffix=".zip", prefix=f"{directory_path.name}_"
69
+ )
70
+ os.close(fd)
71
+ output_path = Path(temp_path)
72
+
73
+ print(f"📦 Zipping directory {directory_path.name}...")
74
+
75
+ # Count total files for progress
76
+ total_files = sum(1 for _ in directory_path.rglob("*") if _.is_file())
77
+
78
+ with zipfile.ZipFile(output_path, "w", zipfile.ZIP_DEFLATED) as zipf:
79
+ with tqdm(total=total_files, unit="file", desc="📁 Compressing") as pbar:
80
+ for file_path in directory_path.rglob("*"):
81
+ if file_path.is_file():
82
+ arcname = file_path.relative_to(directory_path.parent)
83
+ zipf.write(file_path, arcname)
84
+ pbar.update(1)
85
+
86
+ zip_size = output_path.stat().st_size
87
+ print(f"✅ Created zip file: {output_path.name} ({zip_size / 1024 / 1024:.2f} MB)")
88
+ return output_path
89
+
90
+
91
+ def submit_file_multipart(
92
+ file_path: Path,
93
+ token: str,
94
+ server_url: str,
95
+ ) -> dict:
96
+ """
97
+ Submit a large file using multipart upload.
98
+
99
+ Args:
100
+ file_path: Path to the file to submit
101
+ token: Access token for authentication
102
+ server_url: URL of the submission server
103
+
104
+ Returns:
105
+ Response from the server
106
+ """
107
+ file_size = file_path.stat().st_size
108
+ print(
109
+ f"📦 Preparing multipart upload for {file_path.name} ({file_size / 1024 / 1024:.2f} MB)..."
110
+ )
111
+
112
+ # Step 1: Initiate multipart upload
113
+ print("🔑 Initiating multipart upload...")
114
+ response = requests.post(
115
+ f"{server_url}/submit/multipart/initiate",
116
+ data={
117
+ "token": token,
118
+ "filename": file_path.name,
119
+ },
120
+ timeout=30,
121
+ )
122
+ response.raise_for_status()
123
+ result = response.json()
124
+
125
+ upload_id = result["upload_id"]
126
+ submission_id = result["submission_id"]
127
+ version = result["version"]
128
+ is_late = result["is_late"]
129
+ object_name = result["object_name"]
130
+ bucket_name = result["bucket_name"]
131
+
132
+ print(f"✅ Submission upload initiated (version {version})")
133
+
134
+ uploaded_parts = []
135
+
136
+ try:
137
+ # Create the progress bar
138
+ with tqdm(
139
+ total=file_size,
140
+ unit="B",
141
+ unit_scale=True,
142
+ unit_divisor=1024,
143
+ desc="📤 Uploading",
144
+ ) as pbar:
145
+
146
+ def upload_part(part_number: int, offset: int, size: int) -> dict:
147
+ part_response = requests.post(
148
+ f"{server_url}/submit/multipart/part",
149
+ data={
150
+ "token": token,
151
+ "upload_id": upload_id,
152
+ "part_number": str(part_number),
153
+ "object_name": object_name,
154
+ "bucket_name": bucket_name,
155
+ },
156
+ timeout=30,
157
+ )
158
+ part_response.raise_for_status()
159
+ part_data = part_response.json()
160
+ presigned_url = part_data["presigned_url"]
161
+
162
+ with open(file_path, "rb") as part_file:
163
+ part_file.seek(offset)
164
+ upload_response = requests.put(
165
+ presigned_url,
166
+ data=PartFileReader(part_file, size, pbar),
167
+ headers={
168
+ "Content-Type": "application/octet-stream",
169
+ "Content-Length": str(size),
170
+ },
171
+ timeout=300,
172
+ )
173
+ upload_response.raise_for_status()
174
+
175
+ etag = upload_response.headers.get("ETag", "").strip('"')
176
+ return {"part_number": part_number, "etag": etag}
177
+
178
+ parts = []
179
+ part_number = 1
180
+ offset = 0
181
+ while offset < file_size:
182
+ size = min(CHUNK_SIZE, file_size - offset)
183
+ parts.append((part_number, offset, size))
184
+ part_number += 1
185
+ offset += size
186
+
187
+ with ThreadPoolExecutor(max_workers=MULTIPART_CONCURRENCY) as executor:
188
+ futures = [
189
+ executor.submit(upload_part, p_num, off, sz)
190
+ for p_num, off, sz in parts
191
+ ]
192
+ for future in as_completed(futures):
193
+ uploaded_parts.append(future.result())
194
+
195
+ uploaded_parts.sort(key=lambda part: part["part_number"])
196
+
197
+ # Step 3: Complete multipart upload
198
+ complete_response = requests.post(
199
+ f"{server_url}/submit/multipart/complete?token={token}",
200
+ json={
201
+ "upload_id": upload_id,
202
+ "object_name": object_name,
203
+ "bucket_name": bucket_name,
204
+ "parts": uploaded_parts,
205
+ },
206
+ headers={
207
+ "Content-Type": "application/json",
208
+ },
209
+ timeout=60,
210
+ )
211
+ complete_response.raise_for_status()
212
+
213
+ print_submission_success(submission_id, version, is_late)
214
+
215
+ return result
216
+
217
+ except Exception as e:
218
+ # Abort multipart upload on error
219
+ print(f"❌ Error during upload, aborting multipart upload...")
220
+ try:
221
+ requests.post(
222
+ f"{server_url}/submit/multipart/abort",
223
+ data={
224
+ "token": token,
225
+ "upload_id": upload_id,
226
+ "object_name": object_name,
227
+ "bucket_name": bucket_name,
228
+ },
229
+ timeout=30,
230
+ )
231
+ except:
232
+ pass
233
+ raise e
234
+
235
+
236
+ def submit_file(
237
+ file_path: str,
238
+ token: str,
239
+ server_url: str = "https://submissions.h4hn.de",
240
+ ) -> dict:
241
+ """
242
+ Submit a file or directory to the submission platform using presigned URLs.
243
+ If a directory is provided, it will be zipped before upload.
244
+ Automatically uses multipart upload for files larger than 50MB.
245
+
246
+ Args:
247
+ file_path: Path to the file or directory to submit
248
+ token: Access token for authentication
249
+ server_url: URL of the submission server
250
+
251
+ Returns:
252
+ Response from the server
253
+ """
254
+ file_path = Path(file_path)
255
+
256
+ if not file_path.exists():
257
+ raise FileNotFoundError(f"File or directory not found: {file_path}")
258
+
259
+ # Handle directory by zipping it first
260
+ temp_zip = None
261
+ if file_path.is_dir():
262
+ temp_zip = create_zip_from_directory(file_path)
263
+ file_path = temp_zip
264
+
265
+ try:
266
+ return _submit_file_internal(file_path, token, server_url)
267
+ finally:
268
+ # Clean up temporary zip file if created
269
+ if temp_zip and temp_zip.exists():
270
+ temp_zip.unlink()
271
+
272
+
273
+ def _submit_file_internal(
274
+ file_path: Path,
275
+ token: str,
276
+ server_url: str,
277
+ ) -> dict:
278
+ """
279
+ Internal function to submit a file to the submission platform.
280
+
281
+ Args:
282
+ file_path: Path to the file to submit
283
+ token: Access token for authentication
284
+ server_url: URL of the submission server
285
+
286
+ Returns:
287
+ Response from the server
288
+ """
289
+
290
+ file_size = file_path.stat().st_size
291
+
292
+ # Use multipart upload for large files
293
+ if file_size > MULTIPART_THRESHOLD:
294
+ return submit_file_multipart(file_path, token, server_url)
295
+
296
+ # Standard upload for smaller files
297
+ print(
298
+ f"📦 Preparing to submit {file_path.name} ({file_size / 1024 / 1024:.2f} MB)..."
299
+ )
300
+
301
+ response = requests.post(
302
+ f"{server_url}/submit",
303
+ data={
304
+ "token": token,
305
+ "filename": file_path.name,
306
+ },
307
+ timeout=30,
308
+ )
309
+ response.raise_for_status()
310
+ result = response.json()
311
+
312
+ upload_url = result["upload_url"]
313
+ submission_id = result["submission_id"]
314
+ version = result["version"]
315
+ is_late = result["is_late"]
316
+
317
+ with open(file_path, "rb") as f:
318
+ with tqdm.wrapattr(
319
+ f,
320
+ "read",
321
+ total=file_size,
322
+ unit="B",
323
+ unit_scale=True,
324
+ unit_divisor=1024,
325
+ desc="📤 Uploading",
326
+ ) as wrapped_file:
327
+ upload_response = requests.put(
328
+ upload_url,
329
+ data=wrapped_file,
330
+ headers={
331
+ "Content-Type": "application/octet-stream",
332
+ "Content-Length": str(file_size),
333
+ },
334
+ timeout=300, # 5 minutes timeout for large files
335
+ )
336
+ upload_response.raise_for_status()
337
+
338
+ print_submission_success(submission_id, version, is_late)
339
+
340
+ return result