CISCai commited on
Commit
e738e15
1 Parent(s): 737113e

Initial version

Browse files
Files changed (6) hide show
  1. LICENSE +21 -0
  2. README.md +4 -4
  3. _hf_explorer.py +200 -0
  4. _hf_gguf.py +338 -0
  5. app.py +724 -0
  6. requirements.txt +2 -0
LICENSE ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ MIT License
2
+
3
+ Copyright (c) 2024 Sigbjørn Skjæret
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.
README.md CHANGED
@@ -1,5 +1,5 @@
1
  ---
2
- title: Gguf Editor
3
  emoji: 🏢
4
  colorFrom: blue
5
  colorTo: purple
@@ -8,6 +8,6 @@ sdk_version: 4.42.0
8
  app_file: app.py
9
  pinned: false
10
  license: mit
11
- ---
12
-
13
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
1
  ---
2
+ title: GGUF Editor
3
  emoji: 🏢
4
  colorFrom: blue
5
  colorTo: purple
 
8
  app_file: app.py
9
  pinned: false
10
  license: mit
11
+ hf_oauth: true
12
+ hf_oauth_scopes:
13
+ - read-repos
_hf_explorer.py ADDED
@@ -0,0 +1,200 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import fnmatch
2
+ import gradio as gr
3
+ import posixpath
4
+ from gradio.components import Timer
5
+ from gradio.components.base import Component, server
6
+ from gradio.data_classes import GradioRootModel
7
+ from gradio_client.documentation import document
8
+ from huggingface_hub import HfFileSystem
9
+ from typing import Any, Callable, List, Literal, Sequence
10
+
11
+
12
+ class FileExplorerData(GradioRootModel):
13
+ # The outer list is the list of files selected, and the inner list
14
+ # is the path to the file as a list, split by the posixpath.sep.
15
+ root: List[List[str]]
16
+
17
+
18
+ # Hijack Gradio FileExplorer class for file browser functionality
19
+ @document()
20
+ class FileExplorer(Component):
21
+ """
22
+ Creates a file explorer component that allows users to browse files on Huggingface. As an input component,
23
+ it also allows users to select files to be used as input to a function, while as an output component, it displays selected files.
24
+ """
25
+
26
+ EVENTS = ["change"]
27
+ data_model = FileExplorerData
28
+
29
+ def __init__(
30
+ self,
31
+ glob: str = "**/*",
32
+ *,
33
+ value: str | list[str] | Callable | None = None,
34
+ file_count: Literal["single", "multiple"] = "multiple",
35
+ root_dir: str = None,
36
+ branch: str = "main",
37
+ token: gr.OAuthToken | None = None,
38
+ ignore_glob: str | None = None,
39
+ label: str | None = None,
40
+ every: Timer | float | None = None,
41
+ inputs: Component | Sequence[Component] | set[Component] | None = None,
42
+ show_label: bool | None = None,
43
+ container: bool = True,
44
+ scale: int | None = None,
45
+ min_width: int = 160,
46
+ height: int | float | str | None = None,
47
+ interactive: bool | None = None,
48
+ visible: bool = True,
49
+ elem_id: str | None = None,
50
+ elem_classes: list[str] | str | None = None,
51
+ render: bool = True,
52
+ key: int | str | None = None,
53
+ ):
54
+ """
55
+ Parameters:
56
+ glob: The glob-style pattern used to select which files to display, e.g. "*" to match all files, "*.png" to match all .png files, "**/*.txt" to match any .txt file in any subdirectory, etc. The default value matches all files and folders recursively. See the Python glob documentation at https://docs.python.org/3/library/glob.html for more information.
57
+ value: The file (or list of files, depending on the `file_count` parameter) to show as "selected" when the component is first loaded. If a callable is provided, it will be called when the app loads to set the initial value of the component. If not provided, no files are shown as selected.
58
+ file_count: Whether to allow single or multiple files to be selected. If "single", the component will return a single absolute file path as a string. If "multiple", the component will return a list of absolute file paths as a list of strings.
59
+ root_dir: Path to root directory to select files from. If not provided, defaults to current working directory.
60
+ branch: Branch name to browse.
61
+ token: Huggingface token.
62
+ ignore_glob: The glob-style, case-sensitive pattern that will be used to exclude files from the list. For example, "*.py" will exclude all .py files from the list. See the Python glob documentation at https://docs.python.org/3/library/glob.html for more information.
63
+ label: The label for this component. Appears above the component and is also used as the header if there are a table of examples for this component. If None and used in a `gr.Interface`, the label will be the name of the parameter this component is assigned to.
64
+ every: Continously calls `value` to recalculate it if `value` is a function (has no effect otherwise). Can provide a Timer whose tick resets `value`, or a float that provides the regular interval for the reset Timer.
65
+ inputs: Components that are used as inputs to calculate `value` if `value` is a function (has no effect otherwise). `value` is recalculated any time the inputs change.
66
+ show_label: if True, will display label.
67
+ container: If True, will place the component in a container - providing some extra padding around the border.
68
+ scale: relative size compared to adjacent Components. For example if Components A and B are in a Row, and A has scale=2, and B has scale=1, A will be twice as wide as B. Should be an integer. scale applies in Rows, and to top-level Components in Blocks where fill_height=True.
69
+ min_width: minimum pixel width, will wrap if not sufficient screen space to satisfy this value. If a certain scale value results in this Component being narrower than min_width, the min_width parameter will be respected first.
70
+ height: The maximum height of the file component, specified in pixels if a number is passed, or in CSS units if a string is passed. If more files are uploaded than can fit in the height, a scrollbar will appear.
71
+ interactive: if True, will allow users to select file(s); if False, will only display files. If not provided, this is inferred based on whether the component is used as an input or output.
72
+ visible: If False, component will be hidden.
73
+ elem_id: An optional string that is assigned as the id of this component in the HTML DOM. Can be used for targeting CSS styles.
74
+ elem_classes: An optional list of strings that are assigned as the classes of this component in the HTML DOM. Can be used for targeting CSS styles.
75
+ render: If False, component will not render be rendered in the Blocks context. Should be used if the intention is to assign event listeners now but render the component later.
76
+ key: if assigned, will be used to assume identity across a re-render. Components that have the same key across a re-render will have their value preserved.
77
+ """
78
+ self.root_dir = root_dir
79
+ self.branch = branch
80
+ self.fs = HfFileSystem(token = token)
81
+ self.glob = glob
82
+ self.ignore_glob = ignore_glob
83
+ valid_file_count = ["single", "multiple"]
84
+ if file_count not in valid_file_count:
85
+ raise ValueError(
86
+ f"Invalid value for parameter `file_count`: {file_count}. Please choose from one of: {valid_file_count}"
87
+ )
88
+ self.file_count = file_count
89
+ self.height = height
90
+
91
+ super().__init__(
92
+ label=label,
93
+ every=every,
94
+ inputs=inputs,
95
+ show_label=show_label,
96
+ container=container,
97
+ scale=scale,
98
+ min_width=min_width,
99
+ interactive=interactive,
100
+ visible=visible,
101
+ elem_id=elem_id,
102
+ elem_classes=elem_classes,
103
+ render=render,
104
+ key=key,
105
+ value=value,
106
+ )
107
+
108
+ def example_payload(self) -> Any:
109
+ return [["gradio", "app.py"]]
110
+
111
+ def example_value(self) -> Any:
112
+ return posixpath.join(["gradio", "app.py"])
113
+
114
+ def preprocess(self, payload: FileExplorerData | None) -> list[str] | str | None:
115
+ """
116
+ Parameters:
117
+ payload: List of selected files as a FileExplorerData object.
118
+ Returns:
119
+ Passes the selected file or directory as a `str` path (relative to `root`) or `list[str}` depending on `file_count`
120
+ """
121
+ if payload is None:
122
+ return None
123
+
124
+ if self.file_count == "single":
125
+ if len(payload.root) > 1:
126
+ raise ValueError(
127
+ f"Expected only one file, but {len(payload.root)} were selected."
128
+ )
129
+ elif len(payload.root) == 0:
130
+ return None
131
+ else:
132
+ return posixpath.normpath(posixpath.join(self.root_dir, *payload.root[0]))
133
+ files = []
134
+ for file in payload.root:
135
+ file_ = posixpath.normpath(posixpath.join(self.root_dir, *file))
136
+ files.append(file_)
137
+ return files
138
+
139
+ def _strip_root(self, path: str) -> str:
140
+ if path.startswith(self.root_dir):
141
+ return path[len(self.root_dir) + 1 :]
142
+ return path
143
+
144
+ def postprocess(self, value: str | list[str] | None) -> FileExplorerData | None:
145
+ """
146
+ Parameters:
147
+ value: Expects function to return a `str` path to a file, or `list[str]` consisting of paths to files.
148
+ Returns:
149
+ A FileExplorerData object containing the selected files as a list of strings.
150
+ """
151
+ if value is None:
152
+ return None
153
+
154
+ files = [value] if isinstance(value, str) else value
155
+ root = []
156
+ for file in files:
157
+ root.append(self._strip_root(file).split(posixpath.sep))
158
+
159
+ return FileExplorerData(root=root)
160
+
161
+ @server
162
+ def ls(self, subdirectory: list[str] | None = None) -> list[dict[str, str]] | None:
163
+ """
164
+ Returns:
165
+ a list of dictionaries, where each dictionary represents a file or subdirectory in the given subdirectory
166
+ """
167
+ if not self.root_dir:
168
+ return []
169
+
170
+ full_subdir_path = self._safe_join(subdirectory or [])
171
+
172
+ try:
173
+ # subdir_items = sorted(fs.ls(full_subdir_path, detail=True), key=lambda x: x.get('name'))
174
+ subdir_items = self.fs.ls(full_subdir_path, revision=self.branch, detail=True)
175
+ except Exception as e:
176
+ raise gr.Error(e)
177
+
178
+ files, folders = [], []
179
+ for item in subdir_items:
180
+ full_path = item.get('name')
181
+ item_name = posixpath.basename(full_path)
182
+ is_file = item.get('type') != 'directory'
183
+ valid_by_glob = fnmatch.fnmatch(full_path, self.glob)
184
+ if is_file and not valid_by_glob:
185
+ continue
186
+ if self.ignore_glob and fnmatch.fnmatch(full_path, self.ignore_glob):
187
+ continue
188
+ target = files if is_file else folders
189
+ target.append(
190
+ {
191
+ "name": item_name,
192
+ "type": "file" if is_file else "folder",
193
+ "valid": valid_by_glob,
194
+ }
195
+ )
196
+
197
+ return folders + files
198
+
199
+ def _safe_join(self, folders: list[str]) -> str:
200
+ return posixpath.join(self.root_dir, *folders) if folders else self.root_dir
_hf_gguf.py ADDED
@@ -0,0 +1,338 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import struct
2
+ from enum import IntEnum
3
+ from fsspec.spec import AbstractBufferedFile
4
+ from typing import Any, Iterator, NamedTuple
5
+
6
+
7
+ class GGUFValueType(IntEnum):
8
+ UINT8 = 0
9
+ INT8 = 1
10
+ UINT16 = 2
11
+ INT16 = 3
12
+ UINT32 = 4
13
+ INT32 = 5
14
+ FLOAT32 = 6
15
+ BOOL = 7
16
+ STRING = 8
17
+ ARRAY = 9
18
+ UINT64 = 10
19
+ INT64 = 11
20
+ FLOAT64 = 12
21
+
22
+
23
+ standard_metadata = {
24
+ "general.type": (GGUFValueType.STRING, "model"),
25
+ "general.architecture": (GGUFValueType.STRING, "llama"),
26
+ "general.quantization_version": (GGUFValueType.UINT32, 2),
27
+ "general.alignment": (GGUFValueType.UINT32, 32),
28
+ "general.file_type": (GGUFValueType.UINT32, 0),
29
+ "general.name": (GGUFValueType.STRING, ""),
30
+ "general.author": (GGUFValueType.STRING, ""),
31
+ "general.version": (GGUFValueType.STRING, ""),
32
+ "general.organization": (GGUFValueType.STRING, ""),
33
+ "general.finetune": (GGUFValueType.STRING, ""),
34
+ "general.basename": (GGUFValueType.STRING, ""),
35
+ "general.description": (GGUFValueType.STRING, ""),
36
+ "general.quantized_by": (GGUFValueType.STRING, ""),
37
+ "general.size_label": (GGUFValueType.STRING, ""),
38
+ "general.license": (GGUFValueType.STRING, ""),
39
+ "general.license.name": (GGUFValueType.STRING, ""),
40
+ "general.license.link": (GGUFValueType.STRING, ""),
41
+ "general.url": (GGUFValueType.STRING, ""),
42
+ "general.doi": (GGUFValueType.STRING, ""),
43
+ "general.uuid": (GGUFValueType.STRING, ""),
44
+ "general.repo_url": (GGUFValueType.STRING, ""),
45
+ "general.source.url": (GGUFValueType.STRING, ""),
46
+ "general.source.doi": (GGUFValueType.STRING, ""),
47
+ "general.source.uuid": (GGUFValueType.STRING, ""),
48
+ "general.source.repo_url": (GGUFValueType.STRING, ""),
49
+ "general.tags": (GGUFValueType.STRING, []),
50
+ "general.languages": (GGUFValueType.STRING, []),
51
+ "general.datasets": (GGUFValueType.STRING, []),
52
+ "split.no": (GGUFValueType.UINT16, 0),
53
+ "split.count": (GGUFValueType.UINT16, 0),
54
+ "split.tensors.count": (GGUFValueType.UINT32, 0),
55
+ "tokenizer.ggml.model": (GGUFValueType.STRING, "gpt2"),
56
+ "tokenizer.ggml.pre": (GGUFValueType.STRING, "llama-bpe"),
57
+ "tokenizer.ggml.tokens": (GGUFValueType.STRING, []),
58
+ "tokenizer.ggml.token_type": (GGUFValueType.INT32, []),
59
+ "tokenizer.ggml.scores": (GGUFValueType.FLOAT32, []),
60
+ "tokenizer.ggml.merges": (GGUFValueType.STRING, []),
61
+ "tokenizer.ggml.bos_token_id": (GGUFValueType.UINT32, 0),
62
+ "tokenizer.ggml.eos_token_id": (GGUFValueType.UINT32, 0),
63
+ "tokenizer.ggml.unknown_token_id": (GGUFValueType.UINT32, 0),
64
+ "tokenizer.ggml.seperator_token_id": (GGUFValueType.UINT32, 0),
65
+ "tokenizer.ggml.padding_token_id": (GGUFValueType.UINT32, 0),
66
+ "tokenizer.ggml.cls_token_id": (GGUFValueType.UINT32, 0),
67
+ "tokenizer.ggml.mask_token_id": (GGUFValueType.UINT32, 0),
68
+ "tokenizer.ggml.add_bos_token": (GGUFValueType.BOOL, False),
69
+ "tokenizer.ggml.add_eos_token": (GGUFValueType.BOOL, False),
70
+ "tokenizer.ggml.add_space_prefix": (GGUFValueType.BOOL, False),
71
+ "tokenizer.ggml.remove_extra_whitespaces": (GGUFValueType.BOOL, False),
72
+ "tokenizer.chat_template": (GGUFValueType.STRING, ""),
73
+ "tokenizer.chat_template.rag": (GGUFValueType.STRING, ""),
74
+ "tokenizer.chat_template.tool_use": (GGUFValueType.STRING, ""),
75
+ "tokenizer.chat_templates": (GGUFValueType.STRING, []),
76
+ "tokenizer.ggml.prefix_token_id": (GGUFValueType.UINT32, 0),
77
+ "tokenizer.ggml.suffix_token_id": (GGUFValueType.UINT32, 0),
78
+ "tokenizer.ggml.middle_token_id": (GGUFValueType.UINT32, 0),
79
+ "tokenizer.ggml.eot_token_id": (GGUFValueType.UINT32, 0),
80
+ "tokenizer.ggml.eom_token_id": (GGUFValueType.UINT32, 0),
81
+ "quantize.imatrix.file": (GGUFValueType.STRING, ""),
82
+ "quantize.imatrix.dataset": (GGUFValueType.STRING, ""),
83
+ "quantize.imatrix.entries_count": (GGUFValueType.INT32, 0),
84
+ "quantize.imatrix.chunks_count": (GGUFValueType.INT32, 0),
85
+ }
86
+
87
+
88
+ gguf_scalar_size: dict[GGUFValueType, int] = {
89
+ GGUFValueType.UINT8: 1,
90
+ GGUFValueType.INT8: 1,
91
+ GGUFValueType.UINT16: 2,
92
+ GGUFValueType.INT16: 2,
93
+ GGUFValueType.UINT32: 4,
94
+ GGUFValueType.INT32: 4,
95
+ GGUFValueType.FLOAT32: 4,
96
+ GGUFValueType.BOOL: 1,
97
+ GGUFValueType.UINT64: 8,
98
+ GGUFValueType.INT64: 8,
99
+ GGUFValueType.FLOAT64: 8,
100
+ }
101
+
102
+
103
+ gguf_scalar_pack: dict[GGUFValueType, str] = {
104
+ GGUFValueType.UINT8: "B",
105
+ GGUFValueType.INT8: "b",
106
+ GGUFValueType.UINT16: "H",
107
+ GGUFValueType.INT16: "h",
108
+ GGUFValueType.UINT32: "I",
109
+ GGUFValueType.INT32: "i",
110
+ GGUFValueType.FLOAT32: "f",
111
+ GGUFValueType.BOOL: "?",
112
+ GGUFValueType.UINT64: "Q",
113
+ GGUFValueType.INT64: "q",
114
+ GGUFValueType.FLOAT64: "d",
115
+ }
116
+
117
+
118
+ class GGUFData(NamedTuple):
119
+ type: GGUFValueType | None
120
+ value: Any
121
+ data: bytes
122
+
123
+
124
+ class HuggingGGUFstream:
125
+ fp: AbstractBufferedFile
126
+ header: dict[str, GGUFData]
127
+ metadata: dict[str, GGUFData]
128
+ endian: str
129
+ metaend: int
130
+ filesize: int
131
+
132
+ def __init__(
133
+ self,
134
+ fp: AbstractBufferedFile,
135
+ ) -> None:
136
+ self.fp = fp
137
+ self.header = {}
138
+ self.metadata = {}
139
+ self.endian = '<'
140
+ self.metaend = 0
141
+ self.filesize = fp.details.get('size')
142
+
143
+ if (data := self.fp.read(4)) != b'GGUF':
144
+ raise TypeError('File is not a GGUF')
145
+
146
+ self.header['magic'] = GGUFData(
147
+ type = None,
148
+ value = None,
149
+ data = data,
150
+ )
151
+
152
+ data = self._read_field(GGUFValueType.UINT32)
153
+ if data.value != 3:
154
+ if data.value == 3 << 24:
155
+ data.value = 3
156
+ self.endian = '>'
157
+ else:
158
+ raise TypeError('Unsupported GGUF version')
159
+ self.header['version'] = data
160
+
161
+ data = self._read_field(GGUFValueType.UINT64)
162
+ self.header['tensors'] = data
163
+
164
+ data = self._read_field(GGUFValueType.UINT64)
165
+ self.header['metadata'] = data
166
+
167
+ def _unpack_field(
168
+ self,
169
+ buffer: bytes,
170
+ field_type: GGUFValueType,
171
+ repeat: int = 1,
172
+ ) -> Any:
173
+ value = struct.unpack(f'{self.endian}{repeat}{gguf_scalar_pack.get(field_type)}', buffer)
174
+ return value[0] if repeat == 1 else value
175
+
176
+ def _pack_field(
177
+ self,
178
+ field_type: GGUFValueType,
179
+ *values,
180
+ ) -> bytes:
181
+ return struct.pack(f'{self.endian}{len(values)}{gguf_scalar_pack.get(field_type)}', *values)
182
+
183
+ def _pack_value(
184
+ self,
185
+ val_type: GGUFValueType,
186
+ value: Any,
187
+ ) -> bytes:
188
+ if isinstance(value, list):
189
+ data = self._pack_field(GGUFValueType.UINT32, val_type)
190
+ data += self._pack_field(GGUFValueType.UINT64, len(value))
191
+
192
+ if val_type == GGUFValueType.ARRAY:
193
+ raise TypeError('Array of arrays currently unsupported')
194
+ elif val_type == GGUFValueType.STRING:
195
+ if isinstance(value, list):
196
+ for v in value:
197
+ buf = str(v).encode('utf-8')
198
+ data += self._pack_field(GGUFValueType.UINT64, len(buf))
199
+ data += buf
200
+ else:
201
+ buf = str(value).encode('utf-8')
202
+ data = self._pack_field(GGUFValueType.UINT64, len(buf))
203
+ data += buf
204
+ elif val_type in gguf_scalar_pack:
205
+ if isinstance(value, list):
206
+ data += self._pack_field(val_type, *value)
207
+ else:
208
+ data = self._pack_field(val_type, value)
209
+ else:
210
+ raise TypeError('Unknown metadata type')
211
+
212
+ return data
213
+
214
+ def _read_field(
215
+ self,
216
+ field_type: GGUFValueType,
217
+ repeat: int = 1,
218
+ ) -> GGUFData:
219
+ data = self.fp.read(gguf_scalar_size.get(field_type) * repeat)
220
+ value = self._unpack_field(data, field_type, repeat = repeat)
221
+
222
+ return GGUFData(
223
+ type = field_type,
224
+ value = value,
225
+ data = data,
226
+ )
227
+
228
+ def _read_value(
229
+ self,
230
+ val_type: GGUFValueType,
231
+ ) -> GGUFData:
232
+ if val_type == GGUFValueType.ARRAY:
233
+ data = self._read_field(GGUFValueType.UINT32)
234
+ val_len = self._read_field(GGUFValueType.UINT64)
235
+
236
+ if data.value in gguf_scalar_pack:
237
+ val = self._read_field(data.value, repeat = val_len.value)
238
+ data = GGUFData(
239
+ type = val.type,
240
+ value = list(val.value),
241
+ data = data.data + val_len.data + val.data,
242
+ )
243
+ else:
244
+ v = []
245
+ d = [data.data, val_len.data]
246
+
247
+ for _ in range(val_len.value):
248
+ val = self._read_value(data.value)
249
+ d.append(val.data)
250
+ v.append(val.value)
251
+
252
+ data = GGUFData(
253
+ type = data.value,
254
+ value = v,
255
+ data = b''.join(d),
256
+ )
257
+ elif val_type == GGUFValueType.STRING:
258
+ data = self._read_field(GGUFValueType.UINT64)
259
+ val = self.fp.read(data.value)
260
+ data = GGUFData(
261
+ type = val_type,
262
+ value = val.decode('utf-8'),
263
+ data = data.data + val,
264
+ )
265
+ elif val_type in gguf_scalar_pack:
266
+ data = self._read_field(val_type)
267
+ else:
268
+ raise TypeError('Unknown metadata type')
269
+
270
+ return data
271
+
272
+ def _update_metacount(
273
+ self,
274
+ ) -> None:
275
+ old_count = self.header['metadata']
276
+ new_count = len(self.metadata)
277
+ self.header['metadata'] = GGUFData(
278
+ type = old_count.type,
279
+ value = new_count,
280
+ data = self._pack_field(old_count.type, new_count),
281
+ )
282
+
283
+ def read_metadata(
284
+ self,
285
+ ) -> Iterator[tuple[str, GGUFData]]:
286
+ if self.metadata:
287
+ for k, v in self.metadata.items():
288
+ yield k, v
289
+ else:
290
+ num_metadata = self.header['metadata'].value
291
+
292
+ for _ in range(num_metadata):
293
+ key = self._read_value(GGUFValueType.STRING)
294
+ val_type = self._read_field(GGUFValueType.UINT32)
295
+ val = self._read_value(val_type.value)
296
+
297
+ self.metadata[key.value] = val = GGUFData(
298
+ type = val.type,
299
+ value = val.value,
300
+ data = key.data + val_type.data + val.data,
301
+ )
302
+
303
+ yield key.value, val
304
+
305
+ self.metaend = self.fp.loc
306
+
307
+ def add_metadata(
308
+ self,
309
+ key: str,
310
+ type: GGUFValueType,
311
+ value: Any,
312
+ ) -> None:
313
+ data = self._pack_value(GGUFValueType.STRING, key)
314
+ data += self._pack_field(GGUFValueType.UINT32, GGUFValueType.ARRAY if isinstance(value, list) else type)
315
+ data += self._pack_value(type, value)
316
+
317
+ if (meta := self.metadata.get(key)):
318
+ self.filesize -= len(meta.data)
319
+
320
+ self.filesize += len(data)
321
+ self.metadata[key] = GGUFData(
322
+ type = type,
323
+ value = value,
324
+ data = data,
325
+ )
326
+
327
+ if not meta:
328
+ self._update_metacount()
329
+
330
+ def remove_metadata(
331
+ self,
332
+ key: str,
333
+ ) -> None:
334
+ if (meta := self.metadata.get(key)):
335
+ del self.metadata[key]
336
+
337
+ self.filesize -= len(meta.data)
338
+ self._update_metacount()
app.py ADDED
@@ -0,0 +1,724 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import json
3
+ import posixpath
4
+ from fastapi import HTTPException, Path, Query, Request
5
+ from fastapi.responses import StreamingResponse
6
+ from gradio_huggingfacehub_search import HuggingfaceHubSearch
7
+ from huggingface_hub import HfApi, HfFileSystem
8
+ from typing import Annotated, Any, NamedTuple
9
+ from urllib.parse import urlencode
10
+
11
+ from _hf_explorer import FileExplorer
12
+ from _hf_gguf import standard_metadata, GGUFValueType, HuggingGGUFstream
13
+
14
+
15
+ hfapi = HfApi()
16
+
17
+
18
+ class MetadataState(NamedTuple):
19
+ var: dict[str, Any]
20
+ key: dict[str, tuple[int, Any]]
21
+ add: dict[str, Any]
22
+ rem: set
23
+
24
+
25
+ def init_state(
26
+ ):
27
+ return MetadataState(
28
+ var = {},
29
+ key = {},
30
+ add = {},
31
+ rem = set(),
32
+ )
33
+
34
+
35
+ def human_readable_metadata(
36
+ typ: int,
37
+ val: Any,
38
+ ) -> tuple[str, Any]:
39
+ typ = GGUFValueType(typ).name
40
+
41
+ if typ == 'ARRAY':
42
+ val = '[[...], ...]'
43
+ elif isinstance(val, list):
44
+ typ = f'[{typ}][{len(val)}]'
45
+
46
+ if len(val) > 8:
47
+ val = str(val[:8])[:-1] + ', ...]'
48
+ else:
49
+ val = str(val)
50
+
51
+ return typ, val
52
+
53
+
54
+ with gr.Blocks(
55
+ ) as blocks:
56
+ with gr.Row():
57
+ hf_search = HuggingfaceHubSearch(
58
+ label = "Search Huggingface Hub",
59
+ placeholder = "Search for models on Huggingface",
60
+ search_type = "model",
61
+ sumbit_on_select = True,
62
+ scale = 2,
63
+ )
64
+
65
+ hf_branch = gr.Dropdown(
66
+ None,
67
+ label = "Branch",
68
+ scale = 1,
69
+ )
70
+
71
+ gr.LoginButton(
72
+ "Sign in to access gated/private repos",
73
+ scale = 1,
74
+ )
75
+
76
+ hf_file = FileExplorer(
77
+ visible=False,
78
+ )
79
+
80
+ with gr.Row():
81
+ with gr.Column():
82
+ meta_keys = gr.Dropdown(
83
+ None,
84
+ label = "Modify Metadata",
85
+ allow_custom_value = True,
86
+ visible = False,
87
+ )
88
+
89
+ with gr.Column():
90
+ meta_types = gr.Dropdown(
91
+ [e.name for e in GGUFValueType],
92
+ label = "Metadata Type",
93
+ type = "index",
94
+ visible = False,
95
+ )
96
+
97
+ with gr.Column():
98
+ btn_delete = gr.Button(
99
+ "Remove Key",
100
+ variant = 'stop',
101
+ visible = False,
102
+ )
103
+
104
+ meta_boolean = gr.Checkbox(
105
+ visible = False,
106
+ )
107
+
108
+ with gr.Row():
109
+ # Too slow unfortunately, needs a proper search box
110
+ # meta_lookup = gr.Dropdown(
111
+ # label = 'Lookup token',
112
+ # type = 'index',
113
+ # visible = False,
114
+ # )
115
+
116
+ meta_number = gr.Number(
117
+ visible = False,
118
+ )
119
+
120
+ meta_string = gr.Textbox(
121
+ visible = False,
122
+ )
123
+
124
+ meta_array = gr.Matrix(
125
+ None,
126
+ label = "Unsupported",
127
+ row_count = (1, 'fixed'),
128
+ height = "1rem",
129
+ interactive = False,
130
+ visible = False,
131
+ )
132
+
133
+ meta_changes = gr.HighlightedText(
134
+ None,
135
+ label = "Metadata Changes",
136
+ color_map = {'add': 'green', 'rem': 'red'},
137
+ interactive = False,
138
+ visible = False,
139
+ )
140
+
141
+ btn_download = gr.Button(
142
+ "Download GGUF",
143
+ variant = "primary",
144
+ visible = False,
145
+ )
146
+
147
+ file_meta = gr.Matrix(
148
+ None,
149
+ col_count = (3, "fixed"),
150
+ headers = [
151
+ "Metadata Name",
152
+ "Type",
153
+ "Value",
154
+ ],
155
+ datatype = ["str", "str", "str"],
156
+ column_widths = ["35%", "15%", "50%"],
157
+ wrap = True,
158
+ interactive = False,
159
+ visible = False,
160
+ )
161
+
162
+ meta_state = gr.State() # init_state
163
+ # BUG: For some reason using gr.State initial value turns tuple to list?
164
+ meta_state.value = init_state()
165
+
166
+ file_change_components = [
167
+ meta_changes,
168
+ file_meta,
169
+ meta_keys,
170
+ btn_download,
171
+ ]
172
+ state_change_components = [
173
+ meta_state,
174
+ ] + file_change_components
175
+
176
+
177
+ @gr.on(
178
+ triggers = [
179
+ hf_search.submit,
180
+ ],
181
+ inputs = [
182
+ hf_search,
183
+ ],
184
+ outputs = [
185
+ hf_branch,
186
+ ],
187
+ )
188
+ def get_branches(
189
+ repo: str,
190
+ oauth_token: gr.OAuthToken | None = None,
191
+ ):
192
+ branches = []
193
+
194
+ try:
195
+ refs = hfapi.list_repo_refs(
196
+ repo,
197
+ token = oauth_token.token if oauth_token else False,
198
+ )
199
+ branches = [b.name for b in refs.branches]
200
+ except Exception as e:
201
+ raise gr.Error(e)
202
+
203
+ return {
204
+ hf_branch: gr.Dropdown(
205
+ branches or None,
206
+ value = "main" if "main" in branches else None,
207
+ ),
208
+ }
209
+
210
+
211
+ @gr.on(
212
+ triggers = [
213
+ hf_search.submit,
214
+ hf_branch.input,
215
+ ],
216
+ inputs = [
217
+ hf_search,
218
+ hf_branch,
219
+ ],
220
+ outputs = [
221
+ hf_file,
222
+ ] + file_change_components,
223
+ )
224
+ def get_files(
225
+ repo: str,
226
+ branch: str | None,
227
+ oauth_token: gr.OAuthToken | None = None,
228
+ ):
229
+ return {
230
+ hf_file: FileExplorer(
231
+ "**/*.gguf",
232
+ file_count = "single",
233
+ root_dir = repo,
234
+ branch = branch,
235
+ token = oauth_token.token if oauth_token else None,
236
+ visible = True,
237
+ ),
238
+ meta_changes: gr.HighlightedText(
239
+ None,
240
+ visible = False,
241
+ ),
242
+ file_meta: gr.Matrix(
243
+ # None, # FIXME (see Dataframe bug below)
244
+ visible = False,
245
+ ),
246
+ meta_keys: gr.Dropdown(
247
+ None,
248
+ visible = False,
249
+ ),
250
+ btn_download: gr.Button(
251
+ visible = False,
252
+ ),
253
+ }
254
+
255
+
256
+ @gr.on(
257
+ triggers = [
258
+ hf_file.change,
259
+ ],
260
+ inputs = [
261
+ hf_file,
262
+ hf_branch,
263
+ ],
264
+ outputs = [
265
+ meta_state,
266
+ ] + file_change_components,
267
+ show_progress = 'minimal',
268
+ )
269
+ def load_metadata(
270
+ repo_file: str | None,
271
+ branch: str | None,
272
+ progress: gr.Progress = gr.Progress(),
273
+ oauth_token: gr.OAuthToken | None = None,
274
+ ):
275
+ m = []
276
+ meta = init_state()
277
+
278
+ yield {
279
+ meta_state: meta,
280
+ file_meta: gr.Matrix(
281
+ [['', '', '']] * 100, # FIXME: Workaround for Dataframe bug when user has selected data
282
+ visible = True,
283
+ ),
284
+ meta_changes: gr.HighlightedText(
285
+ None,
286
+ visible = False,
287
+ ),
288
+ meta_keys: gr.Dropdown(
289
+ None,
290
+ visible = False,
291
+ ),
292
+ btn_download: gr.Button(
293
+ visible = False,
294
+ ),
295
+ }
296
+
297
+ if not repo_file:
298
+ return
299
+
300
+ fs = HfFileSystem(
301
+ token = oauth_token.token if oauth_token else None,
302
+ )
303
+
304
+ try:
305
+ progress(0, desc = 'Loading file...')
306
+ with fs.open(
307
+ repo_file,
308
+ "rb",
309
+ revision = branch,
310
+ block_size = 8 * 1024 * 1024,
311
+ cache_type = "readahead",
312
+ ) as fp:
313
+ progress(0, desc = 'Reading header...')
314
+ gguf = HuggingGGUFstream(fp)
315
+ num_metadata = gguf.header['metadata'].value
316
+ metadata = gguf.read_metadata()
317
+
318
+ meta.var['repo_file'] = repo_file
319
+ meta.var['branch'] = branch
320
+
321
+ for k, v in progress.tqdm(metadata, desc = 'Reading metadata...', total = num_metadata, unit = f' of {num_metadata} metadata keys...'):
322
+ m.append([k, *human_readable_metadata(v.type, v.value)])
323
+ meta.key[k] = (v.type, v.value)
324
+
325
+ # FIXME
326
+ # yield {
327
+ # file_meta: gr.Matrix(
328
+ # m,
329
+ # ),
330
+ # }
331
+ except Exception as e:
332
+ raise gr.Error(e)
333
+
334
+ yield {
335
+ meta_state: meta,
336
+ file_meta: gr.Matrix(
337
+ m,
338
+ ),
339
+ meta_keys: gr.Dropdown(
340
+ sorted(meta.key.keys() | standard_metadata.keys()),
341
+ value = '',
342
+ visible = True,
343
+ ),
344
+ }
345
+
346
+
347
+ @gr.on(
348
+ triggers = [
349
+ meta_keys.change,
350
+ ],
351
+ inputs = [
352
+ meta_state,
353
+ meta_keys,
354
+ ],
355
+ outputs = [
356
+ meta_types,
357
+ btn_delete,
358
+ ],
359
+ )
360
+ def update_metakey(
361
+ meta: MetadataState,
362
+ key: str | None,
363
+ ):
364
+ typ = None
365
+ if (val := meta.key.get(key, standard_metadata.get(key))) is not None:
366
+ typ = GGUFValueType(val[0]).name
367
+ elif key and key.startswith('tokenizer.chat_template.'):
368
+ typ = GGUFValueType.STRING.name
369
+
370
+ return {
371
+ meta_types: gr.Dropdown(
372
+ value = typ,
373
+ interactive = False if key in meta.key else True,
374
+ visible = True if key else False,
375
+ ),
376
+ btn_delete: gr.Button(
377
+ visible = True if key in meta.key else False,
378
+ ),
379
+ }
380
+
381
+
382
+ @gr.on(
383
+ triggers = [
384
+ meta_keys.change,
385
+ meta_types.input,
386
+ ],
387
+ inputs = [
388
+ meta_state,
389
+ meta_keys,
390
+ meta_types,
391
+ ],
392
+ outputs = [
393
+ meta_boolean,
394
+ meta_number,
395
+ meta_string,
396
+ meta_array,
397
+ ],
398
+ )
399
+ def update_metatype(
400
+ meta: MetadataState,
401
+ key: str,
402
+ typ: int,
403
+ ):
404
+ val = None
405
+ if (data := meta.key.get(key, standard_metadata.get(key))) is not None:
406
+ typ = data[0]
407
+ val = data[1]
408
+ elif not key:
409
+ typ = None
410
+
411
+ if isinstance(val, list):
412
+ # TODO: Support arrays?
413
+ typ = GGUFValueType.ARRAY
414
+
415
+ match typ:
416
+ case GGUFValueType.INT8 | GGUFValueType.INT16 | GGUFValueType.INT32 | GGUFValueType.INT64 | GGUFValueType.UINT8 | GGUFValueType.UINT16 | GGUFValueType.UINT32 | GGUFValueType.UINT64 | GGUFValueType.FLOAT32 | GGUFValueType.FLOAT64:
417
+ is_number = True
418
+ case _:
419
+ is_number = False
420
+
421
+ return {
422
+ meta_boolean: gr.Checkbox(
423
+ value = val if typ == GGUFValueType.BOOL and data is not None else False,
424
+ visible = True if typ == GGUFValueType.BOOL else False,
425
+ ),
426
+ meta_number: gr.Number(
427
+ value = val if is_number and data is not None else 0,
428
+ precision = 10 if typ == GGUFValueType.FLOAT32 or typ == GGUFValueType.FLOAT64 else 0,
429
+ visible = True if is_number else False,
430
+ ),
431
+ meta_string: gr.Textbox(
432
+ value = val if typ == GGUFValueType.STRING else '',
433
+ visible = True if typ == GGUFValueType.STRING else False,
434
+ ),
435
+ meta_array: gr.Matrix(
436
+ visible = True if typ == GGUFValueType.ARRAY else False,
437
+ ),
438
+ }
439
+
440
+
441
+ # FIXME: Disabled for now due to Dataframe bug when user has selected data
442
+ # @gr.on(
443
+ # triggers = [
444
+ # file_meta.select,
445
+ # ],
446
+ # inputs = [
447
+ # ],
448
+ # outputs = [
449
+ # meta_keys,
450
+ # ],
451
+ # )
452
+ # def select_metakey(
453
+ # evt: gr.SelectData,
454
+ # ):
455
+ # return {
456
+ # meta_keys: gr.Dropdown(
457
+ # value = evt.row_value[0] if evt.selected else '',
458
+ # ),
459
+ # }
460
+
461
+
462
+ def notify_state_change(
463
+ meta: MetadataState,
464
+ request: gr.Request,
465
+ ):
466
+ changes = [(k, 'rem') for k in meta.rem]
467
+
468
+ for k, v in meta.add.items():
469
+ changes.append((k, 'add'))
470
+ changes.append((str(v[1]), None))
471
+
472
+ m = []
473
+ for k, v in meta.key.items():
474
+ m.append([k, *human_readable_metadata(v[0], v[1])])
475
+
476
+ link = str(request.request.url_for('download', repo_file = meta.var['repo_file']).include_query_params(branch = meta.var['branch']))
477
+ if meta.rem or meta.add:
478
+ link += '&' + urlencode(
479
+ {
480
+ 'rem': meta.rem,
481
+ 'add': [json.dumps([k, *v], ensure_ascii = False) for k, v in meta.add.items()],
482
+ },
483
+ doseq = True,
484
+ safe = '[]{}:"\',',
485
+ )
486
+
487
+ return {
488
+ meta_state: meta,
489
+ meta_changes: gr.HighlightedText(
490
+ changes,
491
+ visible = True if changes else False,
492
+ ),
493
+ file_meta: gr.Matrix(
494
+ m,
495
+ ),
496
+ meta_keys: gr.Dropdown(
497
+ sorted(meta.key.keys() | standard_metadata.keys()),
498
+ value = '',
499
+ ),
500
+ btn_download: gr.Button(
501
+ link = link,
502
+ visible = True if changes else False,
503
+ ),
504
+ }
505
+
506
+
507
+ @gr.on(
508
+ triggers = [
509
+ btn_delete.click,
510
+ ],
511
+ inputs = [
512
+ meta_state,
513
+ meta_keys,
514
+ ],
515
+ outputs = [
516
+ ] + state_change_components,
517
+ )
518
+ def rem_metadata(
519
+ meta: MetadataState,
520
+ key: str,
521
+ request: gr.Request,
522
+ ):
523
+ if key in meta.add:
524
+ del meta.add[key]
525
+
526
+ if key in meta.key:
527
+ del meta.key[key]
528
+
529
+ meta.rem.add(key)
530
+
531
+ return notify_state_change(
532
+ meta,
533
+ request,
534
+ )
535
+
536
+
537
+ def add_metadata(
538
+ meta: MetadataState,
539
+ key: str,
540
+ typ: int | None,
541
+ val: Any,
542
+ request: gr.Request,
543
+ ):
544
+ if not key or typ is None:
545
+ if key:
546
+ gr.Warning('Missing required value type')
547
+
548
+ return {
549
+ meta_changes: gr.HighlightedText(
550
+ )
551
+ }
552
+
553
+ if key in meta.rem:
554
+ meta.rem.remove(key)
555
+
556
+ meta.key[key] = meta.add[key] = (typ, val)
557
+
558
+ if key.startswith('tokenizer.chat_template.'):
559
+ template = key[24:]
560
+ if template not in meta.key.get('tokenizer.chat_templates', []):
561
+ templates = [x[24:] for x in meta.key.keys() if x.startswith('tokenizer.chat_template.')]
562
+ meta.key['tokenizer.chat_templates'] = meta.add['tokenizer.chat_templates'] = (GGUFValueType.STRING, templates)
563
+
564
+ return notify_state_change(
565
+ meta,
566
+ request,
567
+ )
568
+
569
+
570
+ meta_boolean.input(
571
+ add_metadata,
572
+ inputs = [
573
+ meta_state,
574
+ meta_keys,
575
+ meta_types,
576
+ meta_boolean,
577
+ ],
578
+ outputs = [
579
+ ] + state_change_components,
580
+ )
581
+
582
+ # meta_lookup.input(
583
+ # lambda token: gr.Number(value = token),
584
+ # inputs = meta_lookup,
585
+ # outputs = meta_number,
586
+ # )
587
+
588
+ meta_number.submit(
589
+ add_metadata,
590
+ inputs = [
591
+ meta_state,
592
+ meta_keys,
593
+ meta_types,
594
+ meta_number,
595
+ ],
596
+ outputs = [
597
+ ] + state_change_components,
598
+ )
599
+
600
+ meta_string.submit(
601
+ add_metadata,
602
+ inputs = [
603
+ meta_state,
604
+ meta_keys,
605
+ meta_types,
606
+ meta_string,
607
+ ],
608
+ outputs = [
609
+ ] + state_change_components,
610
+ )
611
+
612
+ meta_array.input(
613
+ add_metadata,
614
+ inputs = [
615
+ meta_state,
616
+ meta_keys,
617
+ meta_types,
618
+ meta_array,
619
+ ],
620
+ outputs = [
621
+ ] + state_change_components,
622
+ )
623
+
624
+
625
+ def stream_repo_file(
626
+ repo_file: str,
627
+ branch: str,
628
+ add_meta: list[str] | None,
629
+ rem_meta: list[str] | None,
630
+ token: str | None = None,
631
+ ):
632
+ fs = HfFileSystem(
633
+ token = token,
634
+ )
635
+
636
+ with fs.open(
637
+ repo_file,
638
+ "rb",
639
+ revision = branch,
640
+ block_size = 8 * 1024 * 1024,
641
+ cache_type = "readahead",
642
+ ) as fp:
643
+ if not rem_meta:
644
+ rem_meta = []
645
+
646
+ if not add_meta:
647
+ add_meta = []
648
+
649
+ gguf = HuggingGGUFstream(fp)
650
+ for _ in gguf.read_metadata():
651
+ pass
652
+
653
+ for k in rem_meta:
654
+ gguf.remove_metadata(k)
655
+
656
+ for k in add_meta:
657
+ k = json.loads(k)
658
+ if isinstance(k, list) and len(k) == 3:
659
+ gguf.add_metadata(*k)
660
+
661
+ yield gguf.filesize
662
+
663
+ yield b''.join((v.data for k, v in gguf.header.items()))
664
+
665
+ for k, v in gguf.metadata.items():
666
+ yield v.data
667
+
668
+ while True:
669
+ if not (data := fp.read(65536)):
670
+ break
671
+
672
+ yield data
673
+
674
+
675
+ if __name__ == "__main__":
676
+ blocks.queue(
677
+ max_size = 10,
678
+ default_concurrency_limit = 10,
679
+ )
680
+ app, local_url, share_url = blocks.launch(
681
+ show_api = False,
682
+ prevent_thread_lock = True,
683
+ )
684
+
685
+ async def download(
686
+ request: Request,
687
+ repo_file: Annotated[str, Path()],
688
+ branch: Annotated[str, Query()] = "main",
689
+ add: Annotated[list[str] | None, Query()] = None,
690
+ rem: Annotated[list[str] | None, Query()] = None,
691
+ ):
692
+ token = request.session.get('oauth_info', {}).get('access_token')
693
+
694
+ if posixpath.normpath(repo_file) != repo_file or '\\' in repo_file or repo_file.startswith('../') or repo_file.startswith('/') or repo_file.count('/') < 2:
695
+ raise HTTPException(
696
+ status_code = 404,
697
+ detail = 'Invalid repository',
698
+ )
699
+
700
+ stream = stream_repo_file(
701
+ repo_file,
702
+ branch,
703
+ add,
704
+ rem,
705
+ token = token,
706
+ )
707
+ size = next(stream)
708
+
709
+ return StreamingResponse(
710
+ stream,
711
+ headers = {
712
+ 'Content-Length': str(size),
713
+ },
714
+ media_type = 'application/octet-stream',
715
+ )
716
+
717
+ app.add_api_route(
718
+ "/download/{repo_file:path}",
719
+ download,
720
+ methods = ["GET"],
721
+ )
722
+ # app.openapi_schema = None
723
+ # app.setup()
724
+ blocks.block_thread()
requirements.txt ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ # gradio[oauth]==4.42.0
2
+ gradio_huggingfacehub_search==0.0.7