merlemcdurrrmott commited on
Commit
e4a6491
·
verified ·
1 Parent(s): 19d30dc

Upload app/assets/api/upload.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. app/assets/api/upload.py +184 -0
app/assets/api/upload.py ADDED
@@ -0,0 +1,184 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import logging
2
+ import os
3
+ import uuid
4
+ from typing import Callable
5
+
6
+ from aiohttp import web
7
+
8
+ import folder_paths
9
+ from app.assets.api.schemas_in import ParsedUpload, UploadError
10
+ from app.assets.helpers import validate_blake3_hash
11
+
12
+
13
+ def normalize_and_validate_hash(s: str) -> str:
14
+ """Validate and normalize a hash string.
15
+
16
+ Returns canonical 'blake3:<hex>' or raises UploadError.
17
+ """
18
+ try:
19
+ return validate_blake3_hash(s)
20
+ except ValueError:
21
+ raise UploadError(400, "INVALID_HASH", "hash must be like 'blake3:<hex>'")
22
+
23
+
24
+ async def parse_multipart_upload(
25
+ request: web.Request,
26
+ check_hash_exists: Callable[[str], bool],
27
+ ) -> ParsedUpload:
28
+ """
29
+ Parse a multipart/form-data upload request.
30
+
31
+ Args:
32
+ request: The aiohttp request
33
+ check_hash_exists: Callable(hash_str) -> bool to check if a hash exists
34
+
35
+ Returns:
36
+ ParsedUpload with parsed fields and temp file path
37
+
38
+ Raises:
39
+ UploadError: On validation or I/O errors
40
+ """
41
+ if not (request.content_type or "").lower().startswith("multipart/"):
42
+ raise UploadError(
43
+ 415, "UNSUPPORTED_MEDIA_TYPE", "Use multipart/form-data for uploads."
44
+ )
45
+
46
+ reader = await request.multipart()
47
+
48
+ file_present = False
49
+ file_client_name: str | None = None
50
+ tags_raw: list[str] = []
51
+ provided_name: str | None = None
52
+ user_metadata_raw: str | None = None
53
+ provided_hash: str | None = None
54
+ provided_hash_exists: bool | None = None
55
+ provided_mime_type: str | None = None
56
+ provided_preview_id: str | None = None
57
+
58
+ file_written = 0
59
+ tmp_path: str | None = None
60
+
61
+ while True:
62
+ field = await reader.next()
63
+ if field is None:
64
+ break
65
+
66
+ fname = getattr(field, "name", "") or ""
67
+
68
+ if fname == "hash":
69
+ try:
70
+ s = ((await field.text()) or "").strip().lower()
71
+ except Exception:
72
+ raise UploadError(
73
+ 400, "INVALID_HASH", "hash must be like 'blake3:<hex>'"
74
+ )
75
+
76
+ if s:
77
+ provided_hash = normalize_and_validate_hash(s)
78
+ try:
79
+ provided_hash_exists = check_hash_exists(provided_hash)
80
+ except Exception as e:
81
+ logging.exception(
82
+ "check_hash_exists failed for hash=%s: %s", provided_hash, e
83
+ )
84
+ raise UploadError(
85
+ 500,
86
+ "HASH_CHECK_FAILED",
87
+ "Backend error while checking asset hash.",
88
+ )
89
+
90
+ elif fname == "file":
91
+ file_present = True
92
+ file_client_name = (field.filename or "").strip()
93
+
94
+ if provided_hash and provided_hash_exists is True:
95
+ # Hash exists - drain file but don't write to disk
96
+ try:
97
+ while True:
98
+ chunk = await field.read_chunk(8 * 1024 * 1024)
99
+ if not chunk:
100
+ break
101
+ file_written += len(chunk)
102
+ except Exception:
103
+ raise UploadError(
104
+ 500, "UPLOAD_IO_ERROR", "Failed to receive uploaded file."
105
+ )
106
+ continue
107
+
108
+ uploads_root = os.path.join(folder_paths.get_temp_directory(), "uploads")
109
+ unique_dir = os.path.join(uploads_root, uuid.uuid4().hex)
110
+ os.makedirs(unique_dir, exist_ok=True)
111
+ tmp_path = os.path.join(unique_dir, ".upload.part")
112
+
113
+ try:
114
+ with open(tmp_path, "wb") as f:
115
+ while True:
116
+ chunk = await field.read_chunk(8 * 1024 * 1024)
117
+ if not chunk:
118
+ break
119
+ f.write(chunk)
120
+ file_written += len(chunk)
121
+ except Exception:
122
+ delete_temp_file_if_exists(tmp_path)
123
+ raise UploadError(
124
+ 500, "UPLOAD_IO_ERROR", "Failed to receive and store uploaded file."
125
+ )
126
+
127
+ elif fname == "tags":
128
+ tags_raw.append((await field.text()) or "")
129
+ elif fname == "name":
130
+ provided_name = (await field.text()) or None
131
+ elif fname == "user_metadata":
132
+ user_metadata_raw = (await field.text()) or None
133
+ elif fname == "id":
134
+ raise UploadError(
135
+ 400,
136
+ "UNSUPPORTED_FIELD",
137
+ "Client-provided 'id' is not supported. Asset IDs are assigned by the server.",
138
+ )
139
+ elif fname == "mime_type":
140
+ provided_mime_type = ((await field.text()) or "").strip() or None
141
+ elif fname == "preview_id":
142
+ provided_preview_id = ((await field.text()) or "").strip() or None
143
+ if not file_present and not (provided_hash and provided_hash_exists):
144
+ raise UploadError(
145
+ 400, "MISSING_FILE", "Form must include a 'file' part or a known 'hash'."
146
+ )
147
+
148
+ if (
149
+ file_present
150
+ and file_written == 0
151
+ and not (provided_hash and provided_hash_exists)
152
+ ):
153
+ delete_temp_file_if_exists(tmp_path)
154
+ raise UploadError(400, "EMPTY_UPLOAD", "Uploaded file is empty.")
155
+
156
+ return ParsedUpload(
157
+ file_present=file_present,
158
+ file_written=file_written,
159
+ file_client_name=file_client_name,
160
+ tmp_path=tmp_path,
161
+ tags_raw=tags_raw,
162
+ provided_name=provided_name,
163
+ user_metadata_raw=user_metadata_raw,
164
+ provided_hash=provided_hash,
165
+ provided_hash_exists=provided_hash_exists,
166
+ provided_mime_type=provided_mime_type,
167
+ provided_preview_id=provided_preview_id,
168
+ )
169
+
170
+
171
+ def delete_temp_file_if_exists(tmp_path: str | None) -> None:
172
+ """Safely remove a temp file and its parent directory if empty."""
173
+ if tmp_path:
174
+ try:
175
+ if os.path.exists(tmp_path):
176
+ os.remove(tmp_path)
177
+ except OSError as e:
178
+ logging.debug("Failed to delete temp file %s: %s", tmp_path, e)
179
+ try:
180
+ parent = os.path.dirname(tmp_path)
181
+ if parent and os.path.isdir(parent):
182
+ os.rmdir(parent) # only succeeds if empty
183
+ except OSError:
184
+ pass