annabossler commited on
Commit
d7d9940
·
verified ·
1 Parent(s): 2f6c8f7

Upload 24 files

Browse files
gradio_molecule3d/.DS_Store ADDED
Binary file (8.2 kB). View file
 
gradio_molecule3d/backend/.DS_Store ADDED
Binary file (6.15 kB). View file
 
gradio_molecule3d/backend/gradio_molecule3d/.DS_Store ADDED
Binary file (6.15 kB). View file
 
gradio_molecule3d/backend/gradio_molecule3d/_init_.py ADDED
File without changes
gradio_molecule3d/backend/gradio_molecule3d/molecule3d.py ADDED
@@ -0,0 +1,357 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """gr.File() component"""
2
+
3
+ from __future__ import annotations
4
+
5
+ import tempfile
6
+ import warnings
7
+ from pathlib import Path
8
+ from typing import TYPE_CHECKING, Any, Callable, Literal, Sequence
9
+
10
+ import gradio_client.utils as client_utils
11
+ from gradio_client import handle_file
12
+
13
+ import gradio as gr
14
+ from gradio import processing_utils
15
+ from gradio.components.base import Component
16
+ from gradio.data_classes import FileData, ListFiles
17
+ from gradio.events import Events
18
+ from gradio.utils import NamedString
19
+ import ase.io
20
+ import numpy as np
21
+
22
+ if TYPE_CHECKING:
23
+ from gradio.components import Timer
24
+
25
+
26
+ def write_proteindatabank(fileobj, images, write_arrays=True):
27
+ """Write images to PDB-file.
28
+ From ASE, but edited to not use the upper-case element symbols.
29
+ """
30
+ rot_t = None
31
+ if hasattr(images, 'get_positions'):
32
+ images = [images]
33
+
34
+ # 1234567 123 6789012345678901 89 67 456789012345678901234567 890
35
+ format = ('ATOM %5d %4s %4s %4d %8.3f%8.3f%8.3f%6.2f%6.2f'
36
+ ' %2s \n')
37
+
38
+ # RasMol complains if the atom index exceeds 100000. There might
39
+ # be a limit of 5 digit numbers in this field.
40
+ MAXNUM = 100000
41
+
42
+ symbols = images[0].get_chemical_symbols()
43
+ natoms = len(symbols)
44
+
45
+ for n, atoms in enumerate(images):
46
+ if atoms.get_pbc().any():
47
+ currentcell = atoms.get_cell()
48
+ cellpar = currentcell.cellpar()
49
+ _, rot_t = currentcell.standard_form()
50
+ # ignoring Z-value, using P1 since we have all atoms defined
51
+ # explicitly
52
+ cellformat = 'CRYST1%9.3f%9.3f%9.3f%7.2f%7.2f%7.2f P 1\n'
53
+ fileobj.write(cellformat % (cellpar[0], cellpar[1], cellpar[2],
54
+ cellpar[3], cellpar[4], cellpar[5]))
55
+ fileobj.write('MODEL ' + str(n + 1) + '\n')
56
+ p = atoms.get_positions()
57
+ if rot_t is not None:
58
+ p = p.dot(rot_t.T)
59
+ occupancy = np.ones(len(atoms))
60
+ bfactor = np.zeros(len(atoms))
61
+ residuenames = ['MOL '] * len(atoms)
62
+ residuenumbers = np.ones(len(atoms))
63
+ names = atoms.get_chemical_symbols()
64
+ if write_arrays:
65
+ if 'occupancy' in atoms.arrays:
66
+ occupancy = atoms.get_array('occupancy')
67
+ if 'bfactor' in atoms.arrays:
68
+ bfactor = atoms.get_array('bfactor')
69
+ if 'residuenames' in atoms.arrays:
70
+ residuenames = atoms.get_array('residuenames')
71
+ if 'residuenumbers' in atoms.arrays:
72
+ residuenumbers = atoms.get_array('residuenumbers')
73
+ if 'atomtypes' in atoms.arrays:
74
+ names = atoms.get_array('atomtypes')
75
+ for a in range(natoms):
76
+ x, y, z = p[a]
77
+ occ = occupancy[a]
78
+ bf = bfactor[a]
79
+ resname = residuenames[a].ljust(4)
80
+ resseq = residuenumbers[a]
81
+ name = names[a]
82
+ fileobj.write(format % ((a + 1) % MAXNUM, name, resname, resseq,
83
+ x, y, z, occ, bf, symbols[a]))
84
+ fileobj.write('ENDMDL\n')
85
+
86
+ def find_minimum_repeats(atoms, min_length):
87
+ """
88
+ Find the minimum number of repeats in each unit cell direction
89
+ to meet at least `min_length` angstroms.
90
+ Parameters:
91
+ atoms (ase.Atoms): The ASE Atoms object.
92
+ min_length (float): The minimum length required in each direction.
93
+ Returns:
94
+ tuple: A tuple of integers representing the number of repeats
95
+ in the x, y, and z directions.
96
+ """
97
+ cell_lengths = atoms.get_cell().lengths() # Get the lengths of the unit cell
98
+ repeats = [max(1, int(np.ceil(min_length / length))) for length in cell_lengths]
99
+ return tuple(repeats)
100
+
101
+ def convert_file_to_pdb(file_path: str | Path, gradio_cache: str | Path) -> str:
102
+ # Read the file using ASE, and convert even if it's pdb to make sure all elements go lower case
103
+
104
+ try:
105
+ structures = ase.io.read(file_path, ':')
106
+ except Exception as e:
107
+ # Bad upload structure, no need to visualize
108
+ raise gr.Error(f'Error parsing file with ase: {str(e)}')
109
+
110
+ if all(structures[0].pbc):
111
+ # find the minimum number of repeats in each unit cell direction to meet at least 20 angstroms
112
+ repeats = find_minimum_repeats(structures[0], min_length=15.0)
113
+
114
+ structures = [s.repeat(repeats) if all(s.pbc) else s for s in structures]
115
+
116
+ # Create a temporary PDB file
117
+ with tempfile.NamedTemporaryFile(
118
+ delete=False, dir=gradio_cache, suffix=".pdb", mode='w',
119
+ ) as temp_pdb_file:
120
+ write_proteindatabank(temp_pdb_file, structures)
121
+ file_name = temp_pdb_file.name
122
+ return file_name
123
+
124
+
125
+ class Molecule3D(Component):
126
+ """
127
+ Creates a file component that allows uploading one or more generic files (when used as an input) or displaying generic files or URLs for download (as output).
128
+ Demo: zip_files, zip_to_json
129
+ """
130
+
131
+ EVENTS = [Events.change, Events.select, Events.clear, Events.upload, Events.delete]
132
+
133
+ def __init__(
134
+ self,
135
+ value: str | list[str] | Callable | None = None,
136
+ reps: Any | None = [],
137
+ config: Any | None = {
138
+ "backgroundColor": "white",
139
+ "orthographic": False,
140
+ "disableFog": False,
141
+ },
142
+ confidenceLabel: str | None = "pLDDT",
143
+ *,
144
+ file_count: Literal["single", "multiple", "directory"] = "single",
145
+ file_types: list[str] | None = None,
146
+ type: Literal["filepath", "binary"] = "filepath",
147
+ label: str | None = None,
148
+ every: Timer | float | None = None,
149
+ inputs: Component | Sequence[Component] | set[Component] | None = None,
150
+ show_label: bool | None = None,
151
+ container: bool = True,
152
+ scale: int | None = None,
153
+ min_width: int = 160,
154
+ height: int | float | None = None,
155
+ interactive: bool | None = None,
156
+ visible: bool = True,
157
+ elem_id: str | None = None,
158
+ elem_classes: list[str] | str | None = None,
159
+ render: bool = True,
160
+ key: int | str | None = None,
161
+ showviewer: bool = True
162
+ ):
163
+ """
164
+ Parameters:
165
+ value: Default file(s) to display, given as a str file path or URL, or a list of str file paths / URLs. If callable, the function will be called whenever the app loads to set the initial value of the component.
166
+ file_count: if single, allows user to upload one file. If "multiple", user uploads multiple files. If "directory", user uploads all files in selected directory. Return type will be list for each file in case of "multiple" or "directory".
167
+ file_types: List of file extensions or types of files to be uploaded (e.g. ['image', '.json', '.mp4']). "file" allows any file to be uploaded, "image" allows only image files to be uploaded, "audio" allows only audio files to be uploaded, "video" allows only video files to be uploaded, "text" allows only text files to be uploaded.
168
+ representations: list of representation objects
169
+ config: dictionary of config options
170
+ confidenceLabel: label for confidence values stored in the bfactor column of a pdb file
171
+ type: Type of value to be returned by component. "file" returns a temporary file object with the same base name as the uploaded file, whose full path can be retrieved by file_obj.name, "binary" returns an bytes object.
172
+ 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.
173
+ 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.
174
+ 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.
175
+ show_label: if True, will display label.
176
+ container: If True, will place the component in a container - providing some extra padding around the border.
177
+ 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.
178
+ 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.
179
+ 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.
180
+ interactive: if True, will allow users to upload a file; if False, can only be used to display files. If not provided, this is inferred based on whether the component is used as an input or output.
181
+ visible: If False, component will be hidden.
182
+ 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.
183
+ 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.
184
+ 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.
185
+ 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.
186
+ showviewer: If True, will display the 3Dmol.js viewer. If False, will not display the 3Dmol.js viewer.
187
+ """
188
+ file_count_valid_types = ["single", "multiple", "directory"]
189
+ self.file_count = file_count
190
+
191
+ if self.file_count not in file_count_valid_types:
192
+ raise ValueError(
193
+ f"Parameter file_count must be one of them: {file_count_valid_types}"
194
+ )
195
+ elif self.file_count in ["multiple", "directory"]:
196
+ self.data_model = ListFiles
197
+ else:
198
+ self.data_model = FileData
199
+ self.file_types = file_types
200
+ if file_types is not None and not isinstance(file_types, list):
201
+ raise ValueError(
202
+ f"Parameter file_types must be a list. Received {file_types.__class__.__name__}"
203
+ )
204
+ valid_types = [
205
+ "filepath",
206
+ "binary",
207
+ ]
208
+ if type not in valid_types:
209
+ raise ValueError(
210
+ f"Invalid value for parameter `type`: {type}. Please choose from one of: {valid_types}"
211
+ )
212
+ if file_count == "directory" and file_types is not None:
213
+ warnings.warn(
214
+ "The `file_types` parameter is ignored when `file_count` is 'directory'."
215
+ )
216
+ super().__init__(
217
+ label=label,
218
+ every=every,
219
+ inputs=inputs,
220
+ show_label=show_label,
221
+ container=container,
222
+ scale=scale,
223
+ min_width=min_width,
224
+ interactive=interactive,
225
+ visible=visible,
226
+ elem_id=elem_id,
227
+ elem_classes=elem_classes,
228
+ render=render,
229
+ key=key,
230
+ value=value,
231
+ )
232
+ self.type = type
233
+ self.height = height
234
+ self.reps = reps
235
+ self.config = config
236
+ self.confidenceLabel = confidenceLabel
237
+ self.showviewer = showviewer
238
+
239
+ def _process_single_file(self, f: FileData) -> NamedString | bytes:
240
+ file_name = f.path
241
+
242
+ file_name = convert_file_to_pdb(file_name, self.GRADIO_CACHE)
243
+
244
+ if self.type == "filepath":
245
+ return NamedString(file_name)
246
+ elif self.type == "binary":
247
+ with open(file_name, "rb") as file_data:
248
+ return file_data.read()
249
+ else:
250
+ raise ValueError(
251
+ "Unknown type: "
252
+ + str(type)
253
+ + ". Please choose from: 'filepath', 'binary'."
254
+ )
255
+
256
+ def preprocess(
257
+ self, payload: ListFiles | FileData | None
258
+ ) -> bytes | str | list[bytes] | list[str] | None:
259
+ """
260
+ Parameters:
261
+ payload: molecule3d information as a FileData object, or a list of FileData objects.
262
+ Returns:
263
+ Passes the file as a `str` or `bytes` object, or a list of `str` or list of `bytes` objects, depending on `type` and `file_count`.
264
+ """
265
+ if payload is None:
266
+ return None
267
+
268
+ if self.file_count == "single":
269
+ if isinstance(payload, ListFiles):
270
+ return self._process_single_file(payload[0])
271
+ return self._process_single_file(payload)
272
+ if isinstance(payload, ListFiles):
273
+ return [self._process_single_file(f) for f in payload] # type: ignore
274
+ return [self._process_single_file(payload)] # type: ignore
275
+
276
+ def _download_files(self, value: str | list[str]) -> str | list[str]:
277
+ downloaded_files = []
278
+ if isinstance(value, list):
279
+ for file in value:
280
+ if client_utils.is_http_url_like(file):
281
+ downloaded_file = processing_utils.save_url_to_cache(
282
+ file, self.GRADIO_CACHE
283
+ )
284
+ downloaded_files.append(downloaded_file)
285
+ else:
286
+ downloaded_files.append(file)
287
+ return downloaded_files
288
+ if client_utils.is_http_url_like(value):
289
+ downloaded_file = processing_utils.save_url_to_cache(
290
+ value, self.GRADIO_CACHE
291
+ )
292
+ return downloaded_file
293
+ else:
294
+ return value
295
+
296
+ def postprocess(self, value: str | list[str] | None) -> ListFiles | FileData | None:
297
+ """
298
+ Parameters:
299
+ value: Expects a `str` filepath or URL, or a `list[str]` of filepaths/URLs.
300
+ Returns:
301
+ molecule3d information as a FileData object, or a list of FileData objects.
302
+ """
303
+ if value is None:
304
+ return None
305
+ value = self._download_files(value)
306
+
307
+
308
+ if isinstance(value, list):
309
+ value = [convert_file_to_pdb(str(path), self.GRADIO_CACHE) for path in value]
310
+ return ListFiles(
311
+ root=[
312
+ FileData(
313
+ path=file,
314
+ orig_name=Path(file).name,
315
+ size=Path(file).stat().st_size,
316
+ )
317
+ for file in value
318
+ ]
319
+ )
320
+ else:
321
+ value = convert_file_to_pdb(str(value), self.GRADIO_CACHE)
322
+ if value is not None:
323
+ return FileData(
324
+ path=value,
325
+ orig_name=Path(value).name,
326
+ size=Path(value).stat().st_size,
327
+ )
328
+ else:
329
+ return None
330
+
331
+ def process_example(self, value: str | list | None) -> str:
332
+ if value is None:
333
+ return ""
334
+ elif isinstance(value, list):
335
+ return ", ".join([Path(file).name for file in value])
336
+ else:
337
+ return Path(value).name
338
+
339
+ def example_payload(self) -> Any:
340
+ if self.file_count == "single":
341
+ return handle_file(
342
+ "https://files.rcsb.org/view/1PGA.pdb"
343
+ )
344
+ else:
345
+ return [
346
+ handle_file(
347
+ "https://files.rcsb.org/view/1PGA.pdb"
348
+ )
349
+ ]
350
+
351
+ def example_value(self) -> Any:
352
+ if self.file_count == "single":
353
+ return "https://files.rcsb.org/view/1PGA.pdb"
354
+ else:
355
+ return [
356
+ "https://files.rcsb.org/view/1PGA.pdb"
357
+ ]
gradio_molecule3d/demo/_init_.py ADDED
File without changes
gradio_molecule3d/demo/app.py ADDED
@@ -0,0 +1,71 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ from gradio_molecule3d import Molecule3D
3
+
4
+
5
+ example = Molecule3D().example_value()
6
+
7
+
8
+ reps = [
9
+ {
10
+ "model": 0,
11
+ "chain": "",
12
+ "resname": "",
13
+ "style": "cartoon",
14
+ "color": "hydrophobicity",
15
+ # "residue_range": "",
16
+ "around": 0,
17
+ "byres": False,
18
+ # "visible": False,
19
+ # "opacity": 0.5
20
+ }
21
+ ]
22
+
23
+
24
+
25
+ def predict(x):
26
+ print("predict function", x)
27
+ print(x.name)
28
+ return x
29
+
30
+ # def update_color(mol, color):
31
+ # reps[0]['color'] = color
32
+ # print(reps)
33
+ # return Molecule3D(mol, reps=reps)
34
+
35
+ with gr.Blocks() as demo:
36
+ gr.Markdown("# Molecule3D")
37
+ # color_choices = ['redCarbon', 'greenCarbon', 'orangeCarbon', 'blackCarbon', 'blueCarbon', 'grayCarbon', 'cyanCarbon']
38
+
39
+ inp = Molecule3D(label="Molecule3D", reps=reps)
40
+ # cdr_color = gr.Dropdown(choices=color_choices, label="CDR color", value='redCarbon')
41
+ out = Molecule3D(label="Output", reps=reps)
42
+ # cdr_color.change(update_color, inputs=[inp,cdr_color], outputs=out)
43
+ btn = gr.Button("Predict")
44
+ gr.Markdown("""
45
+ You can configure the default rendering of the molecule by adding a list of representations
46
+ <pre>
47
+ reps = [
48
+ {
49
+ "model": 0,
50
+ "style": "cartoon",
51
+ "color": "whiteCarbon",
52
+ "residue_range": "",
53
+ "around": 0,
54
+ "opacity":1
55
+
56
+ },
57
+ {
58
+ "model": 0,
59
+ "chain": "A",
60
+ "resname": "HIS",
61
+ "style": "stick",
62
+ "color": "red"
63
+ }
64
+ ]
65
+ </pre>
66
+ """)
67
+ btn.click(predict, inputs=inp, outputs=out)
68
+
69
+
70
+ if __name__ == "__main__":
71
+ demo.launch()
gradio_molecule3d/demo/css.css ADDED
@@ -0,0 +1,157 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ html {
2
+ font-family: Inter;
3
+ font-size: 16px;
4
+ font-weight: 400;
5
+ line-height: 1.5;
6
+ -webkit-text-size-adjust: 100%;
7
+ background: #fff;
8
+ color: #323232;
9
+ -webkit-font-smoothing: antialiased;
10
+ -moz-osx-font-smoothing: grayscale;
11
+ text-rendering: optimizeLegibility;
12
+ }
13
+
14
+ :root {
15
+ --space: 1;
16
+ --vspace: calc(var(--space) * 1rem);
17
+ --vspace-0: calc(3 * var(--space) * 1rem);
18
+ --vspace-1: calc(2 * var(--space) * 1rem);
19
+ --vspace-2: calc(1.5 * var(--space) * 1rem);
20
+ --vspace-3: calc(0.5 * var(--space) * 1rem);
21
+ }
22
+
23
+ .app {
24
+ max-width: 748px !important;
25
+ }
26
+
27
+ .prose p {
28
+ margin: var(--vspace) 0;
29
+ line-height: var(--vspace * 2);
30
+ font-size: 1rem;
31
+ }
32
+
33
+ code {
34
+ font-family: "Inconsolata", sans-serif;
35
+ font-size: 16px;
36
+ }
37
+
38
+ h1,
39
+ h1 code {
40
+ font-weight: 400;
41
+ line-height: calc(2.5 / var(--space) * var(--vspace));
42
+ }
43
+
44
+ h1 code {
45
+ background: none;
46
+ border: none;
47
+ letter-spacing: 0.05em;
48
+ padding-bottom: 5px;
49
+ position: relative;
50
+ padding: 0;
51
+ }
52
+
53
+ h2 {
54
+ margin: var(--vspace-1) 0 var(--vspace-2) 0;
55
+ line-height: 1em;
56
+ }
57
+
58
+ h3,
59
+ h3 code {
60
+ margin: var(--vspace-1) 0 var(--vspace-2) 0;
61
+ line-height: 1em;
62
+ }
63
+
64
+ h4,
65
+ h5,
66
+ h6 {
67
+ margin: var(--vspace-3) 0 var(--vspace-3) 0;
68
+ line-height: var(--vspace);
69
+ }
70
+
71
+ .bigtitle,
72
+ h1,
73
+ h1 code {
74
+ font-size: calc(8px * 4.5);
75
+ word-break: break-word;
76
+ }
77
+
78
+ .title,
79
+ h2,
80
+ h2 code {
81
+ font-size: calc(8px * 3.375);
82
+ font-weight: lighter;
83
+ word-break: break-word;
84
+ border: none;
85
+ background: none;
86
+ }
87
+
88
+ .subheading1,
89
+ h3,
90
+ h3 code {
91
+ font-size: calc(8px * 1.8);
92
+ font-weight: 600;
93
+ border: none;
94
+ background: none;
95
+ letter-spacing: 0.1em;
96
+ text-transform: uppercase;
97
+ }
98
+
99
+ h2 code {
100
+ padding: 0;
101
+ position: relative;
102
+ letter-spacing: 0.05em;
103
+ }
104
+
105
+ blockquote {
106
+ font-size: calc(8px * 1.1667);
107
+ font-style: italic;
108
+ line-height: calc(1.1667 * var(--vspace));
109
+ margin: var(--vspace-2) var(--vspace-2);
110
+ }
111
+
112
+ .subheading2,
113
+ h4 {
114
+ font-size: calc(8px * 1.4292);
115
+ text-transform: uppercase;
116
+ font-weight: 600;
117
+ }
118
+
119
+ .subheading3,
120
+ h5 {
121
+ font-size: calc(8px * 1.2917);
122
+ line-height: calc(1.2917 * var(--vspace));
123
+
124
+ font-weight: lighter;
125
+ text-transform: uppercase;
126
+ letter-spacing: 0.15em;
127
+ }
128
+
129
+ h6 {
130
+ font-size: calc(8px * 1.1667);
131
+ font-size: 1.1667em;
132
+ font-weight: normal;
133
+ font-style: italic;
134
+ font-family: "le-monde-livre-classic-byol", serif !important;
135
+ letter-spacing: 0px !important;
136
+ }
137
+
138
+ #start .md > *:first-child {
139
+ margin-top: 0;
140
+ }
141
+
142
+ h2 + h3 {
143
+ margin-top: 0;
144
+ }
145
+
146
+ .md hr {
147
+ border: none;
148
+ border-top: 1px solid var(--block-border-color);
149
+ margin: var(--vspace-2) 0 var(--vspace-2) 0;
150
+ }
151
+ .prose ul {
152
+ margin: var(--vspace-2) 0 var(--vspace-1) 0;
153
+ }
154
+
155
+ .gap {
156
+ gap: 0;
157
+ }
gradio_molecule3d/frontend/.DS_Store ADDED
Binary file (6.15 kB). View file
 
gradio_molecule3d/frontend/Example.svelte ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <script lang="ts">
2
+ import type { FileData } from "@gradio/client";
3
+
4
+ export let value: FileData | null;
5
+ export let type: "gallery" | "table";
6
+ export let selected = false;
7
+ </script>
8
+
9
+ <div
10
+ class:table={type === "table"}
11
+ class:gallery={type === "gallery"}
12
+ class:selected
13
+ >
14
+ {value ? (Array.isArray(value) ? value.join(", ") : value) : ""}
15
+ </div>
16
+
17
+ <style>
18
+ div {
19
+ overflow: hidden;
20
+ text-overflow: ellipsis;
21
+ white-space: nowrap;
22
+ }
23
+ .gallery {
24
+ display: flex;
25
+ align-items: center;
26
+ cursor: pointer;
27
+ padding: var(--size-1) var(--size-2);
28
+ text-align: left;
29
+ }
30
+ </style>
gradio_molecule3d/frontend/Index.svelte ADDED
@@ -0,0 +1,326 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <svelte:options accessors={true} />
2
+
3
+ <script context="module" lang="ts">
4
+ export { default as FilePreview } from "./shared/FilePreview.svelte";
5
+ export { default as BaseFileUpload } from "./shared/FileUpload.svelte";
6
+ export { default as BaseFile } from "./shared/File.svelte";
7
+ export { default as BaseExample } from "./Example.svelte";
8
+ </script>
9
+
10
+ <script lang="ts">
11
+ import "./style.css";
12
+ import type { Gradio, SelectData } from "@gradio/utils";
13
+ import File from "./shared/File.svelte";
14
+ import FileUpload from "./shared/FileUpload.svelte";
15
+ import type { FileData } from "@gradio/client";
16
+ import { Block, UploadText } from "@gradio/atoms";
17
+ import { StatusTracker } from "@gradio/statustracker";
18
+ import type { LoadingStatus } from "@gradio/statustracker";
19
+ export let elem_id = "";
20
+ export let elem_classes: string[] = [];
21
+ export let visible = true;
22
+ export let value: null | FileData | FileData[];
23
+ export let interactive: boolean;
24
+ export let root: string;
25
+ export let label: string;
26
+ export let show_label: boolean;
27
+ export let height: number | undefined = undefined;
28
+ //Molecule3D specific arguments
29
+ export let reps: any = [];
30
+ export let config: any = {};
31
+ export let confidenceLabel: string = "";
32
+ export let showviewer: boolean = true;
33
+ export let _selectable = false;
34
+ export let loading_status: LoadingStatus;
35
+ export let container = true;
36
+ export let scale: number | null = null;
37
+ export let min_width: number | undefined = undefined;
38
+ export let gradio: Gradio<{
39
+ change: never;
40
+ error: string;
41
+ upload: never;
42
+ clear: never;
43
+ select: SelectData;
44
+ clear_status: LoadingStatus;
45
+ delete: FileData;
46
+ }>;
47
+ export let file_count: "single" | "multiple" | "directory";
48
+ export let file_types: string[] = ["file"];
49
+ let old_value = value;
50
+ $: if (JSON.stringify(old_value) !== JSON.stringify(value)) {
51
+ gradio.dispatch("change");
52
+ old_value = value;
53
+ moldata = null;
54
+ retrieveContent(value);
55
+ }
56
+ $: if (JSON.stringify(reps) !== JSON.stringify(reps)) {
57
+ gradio.dispatch("change");
58
+ old_value = value;
59
+ // console.log("reps changed");
60
+ // console.log(reps);
61
+ moldata = null;
62
+ retrieveContent(value);
63
+ }
64
+ let dragging = false;
65
+ let pending_upload = false;
66
+ let keys_for_reps = {
67
+ model: {
68
+ type: Number,
69
+ default: 0,
70
+ },
71
+ chain: {
72
+ type: String,
73
+ default: "",
74
+ },
75
+ resname: {
76
+ type: String,
77
+ default: "",
78
+ },
79
+ style: {
80
+ type: String,
81
+ default: "cartoon",
82
+ choices: ["cartoon", "stick", "sphere", "surface"],
83
+ },
84
+ color: {
85
+ type: String,
86
+ default: "whiteCarbon",
87
+ choices: [
88
+ "whiteCarbon",
89
+ "orangeCarbon",
90
+ "redCarbon",
91
+ "blackCarbon",
92
+ "blueCarbon",
93
+ "grayCarbon",
94
+ "greenCarbon",
95
+ "cyanCarbon",
96
+ "alphafold",
97
+ "default",
98
+ "Jmol",
99
+ "chain",
100
+ "spectrum",
101
+ ],
102
+ },
103
+ opacity: {
104
+ type: Number,
105
+ default: 1,
106
+ },
107
+ residue_range: {
108
+ type: String,
109
+ default: "",
110
+ },
111
+ around: {
112
+ type: Number,
113
+ default: 0,
114
+ },
115
+ byres: {
116
+ type: Boolean,
117
+ default: false,
118
+ },
119
+ visible: {
120
+ type: Boolean,
121
+ default: true,
122
+ },
123
+ };
124
+ let moldata = null;
125
+ let allowed_extensions = ["pdb", "sdf", "mol2", "pdb1", "cif", "traj", "xyz"];
126
+ async function fetchFileContent(url) {
127
+ const response = await fetch(url);
128
+ const content = await response.text();
129
+ return content;
130
+ }
131
+ let promise = null;
132
+ let errors = [];
133
+ async function retrieveContent(value) {
134
+ if (value == null) {
135
+ return [];
136
+ } else if (Array.isArray(value)) {
137
+ let tempMoldata = [];
138
+ // get file extension
139
+ for (const element of value) {
140
+ let ext = element.orig_name.split(".").pop();
141
+ if (!allowed_extensions.includes(ext)) {
142
+ errors.push(
143
+ `Invalid file extension for ${
144
+ element.orig_name
145
+ }. Expected one of ${allowed_extensions.join(", ")}, got ${ext}`
146
+ );
147
+ moldata = null;
148
+ continue;
149
+ }
150
+ tempMoldata.push({
151
+ data: await fetchFileContent(element.url),
152
+ name: element.orig_name,
153
+ format: ext,
154
+ asFrames: false,
155
+ });
156
+ }
157
+ moldata = tempMoldata;
158
+ } else if (typeof value === "object" && value !== null) {
159
+ let ext = value.orig_name.split(".").pop();
160
+ if (!allowed_extensions.includes(ext)) {
161
+ errors.push(
162
+ `Invalid file extension for ${
163
+ value.orig_name
164
+ }. Expected one of ${allowed_extensions.join(", ")}, got ${ext}`
165
+ );
166
+ moldata = null;
167
+ } else {
168
+ let t = await fetchFileContent(value.url);
169
+ let ext = value.orig_name.split(".").pop();
170
+ if (ext === "pdb1") {
171
+ ext = "pdb";
172
+ }
173
+ moldata = [
174
+ { data: t, name: value.orig_name, format: ext, asFrames: false },
175
+ ];
176
+ }
177
+ } else {
178
+ moldata = null;
179
+ }
180
+ // value is object
181
+ }
182
+ // go through each rep, do a type check and add missing keys to the rep
183
+ let lenMoldata = 0;
184
+ $: lenMoldata = moldata ? moldata.length : 0;
185
+ let representations = [];
186
+ //first add all missing keys
187
+ $: {
188
+ reps.forEach((rep) => {
189
+ for (const [key, value] of Object.entries(keys_for_reps)) {
190
+ if (rep[key] === undefined) {
191
+ rep[key] = value["default"];
192
+ }
193
+ if (rep[key].constructor != value["type"]) {
194
+ errors.push(
195
+ `Invalid type for ${key} in reps. Expected ${
196
+ value["type"]
197
+ }, got ${typeof rep[key]}`
198
+ );
199
+ }
200
+ }
201
+ });
202
+ // then check if model does exist and add to representations
203
+ reps.forEach((rep) => {
204
+ if (rep["model"] <= lenMoldata) {
205
+ representations.push(rep);
206
+ }
207
+ });
208
+ }
209
+ $: promise = retrieveContent(value);
210
+ </script>
211
+
212
+ <Block
213
+ {visible}
214
+ variant={value ? "solid" : "dashed"}
215
+ border_mode={dragging ? "focus" : "base"}
216
+ padding={false}
217
+ {elem_id}
218
+ {elem_classes}
219
+ {container}
220
+ {scale}
221
+ {min_width}
222
+ allow_overflow={false}
223
+ >
224
+ <StatusTracker
225
+ autoscroll={gradio.autoscroll}
226
+ i18n={gradio.i18n}
227
+ {...loading_status}
228
+ status={pending_upload
229
+ ? "generating"
230
+ : loading_status?.status || "complete"}
231
+ on:clear_status={() => gradio.dispatch("clear_status", loading_status)}
232
+ />
233
+ {#if !interactive}
234
+ <File
235
+ on:select={({ detail }) => gradio.dispatch("select", detail)}
236
+ selectable={_selectable}
237
+ {value}
238
+ {label}
239
+ {show_label}
240
+ {height}
241
+ {representations}
242
+ {config}
243
+ {confidenceLabel}
244
+ {moldata}
245
+ {errors}
246
+ i18n={gradio.i18n}
247
+ molviewer={showviewer}
248
+ />
249
+ {:else}
250
+ <FileUpload
251
+ upload={gradio.client.upload}
252
+ stream_handler={gradio.client.stream}
253
+ {label}
254
+ {show_label}
255
+ {value}
256
+ {file_count}
257
+ {file_types}
258
+ selectable={_selectable}
259
+ {root}
260
+ {height}
261
+ {representations}
262
+ {config}
263
+ {confidenceLabel}
264
+ {moldata}
265
+ molviewer={showviewer}
266
+ max_file_size={gradio.max_file_size}
267
+ on:change={({ detail }) => {
268
+ value = detail;
269
+ }}
270
+ on:drag={({ detail }) => (dragging = detail)}
271
+ on:clear={() => gradio.dispatch("clear")}
272
+ on:select={({ detail }) => gradio.dispatch("select", detail)}
273
+ on:notfound={() =>
274
+ gradio.dispatch(
275
+ "error",
276
+ "identifier not found in database, check spelling"
277
+ )}
278
+ on:upload={() => gradio.dispatch("upload")}
279
+ on:error={({ detail }) => {
280
+ loading_status = loading_status || {};
281
+ loading_status.status = "error";
282
+ gradio.dispatch("error", detail);
283
+ }}
284
+ on:delete={({ detail }) => {
285
+ gradio.dispatch("delete", detail);
286
+ }}
287
+ i18n={gradio.i18n}
288
+ >
289
+ <UploadText i18n={gradio.i18n} type="file" />
290
+ </FileUpload>
291
+ {/if}
292
+
293
+ {#if errors.length > 0 && value !== null}
294
+ <div
295
+ class="flex m-2 p-4 mb-4 text-sm text-red-800 rounded-lg bg-red-50 dark:bg-gray-800 dark:text-red-400"
296
+ role="alert"
297
+ >
298
+ <svg
299
+ class="flex-shrink-0 inline w-4 h-4 mr-3 mt-[2px]"
300
+ xmlns="http://www.w3.org/2000/svg"
301
+ fill="none"
302
+ viewBox="0 0 24 24"
303
+ stroke-width="1.5"
304
+ stroke="currentColor"
305
+ >
306
+ <path
307
+ stroke-linecap="round"
308
+ stroke-linejoin="round"
309
+ d="M12 9v3.75m-9.303 3.376c-.866 1.5.217 3.374 1.948 3.374h14.71c1.73 0 2.813-1.874 1.948-3.374L13.949 3.378c-.866-1.5-3.032-1.5-3.898 0L2.697 16.126zM12 15.75h.007v.008H12v-.008z"
310
+ />
311
+ </svg>
312
+
313
+ <span class="sr-only">Error in the representations</span>
314
+ <div>
315
+ <span class="font-medium"
316
+ >Couldn't display Molecule. Fix the following problems:</span
317
+ >
318
+ <ul class="mt-1.5 ml-4 list-disc list-inside">
319
+ {#each errors as error}
320
+ <li>{error}</li>
321
+ {/each}
322
+ </ul>
323
+ </div>
324
+ </div>
325
+ {/if}
326
+ </Block>
gradio_molecule3d/frontend/gradio.config.js ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import tailwindcss from "@tailwindcss/vite";
2
+
3
+ export default {
4
+ plugins: [tailwindcss()],
5
+ svelte: {
6
+ preprocess: [],
7
+ },
8
+ build: {
9
+ target: "modules",
10
+ },
11
+ };
gradio_molecule3d/frontend/package-lock.json ADDED
The diff for this file is too large to render. See raw diff
 
gradio_molecule3d/frontend/package.json ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "name": "gradio_molecule3d",
3
+ "version": "0.9.2",
4
+ "description": "Gradio UI packages",
5
+ "type": "module",
6
+ "author": "",
7
+ "license": "ISC",
8
+ "private": false,
9
+ "dependencies": {
10
+ "@gradio/atoms": "^0.9.0",
11
+ "@gradio/client": "^1.6.0",
12
+ "@gradio/icons": "^0.8.0",
13
+ "@gradio/markdown": "^0.10.1",
14
+ "@gradio/statustracker": "^0.8.1",
15
+ "@gradio/upload": "^0.13.1",
16
+ "@gradio/utils": "^0.7.0",
17
+ "@gradio/wasm": "^0.14.1",
18
+ "@tailwindcss/vite": "^4.0.0-alpha.30",
19
+ "3dmol": "^2.4.0",
20
+ "tailwindcss": "^4.0.0-alpha.30"
21
+ },
22
+ "devDependencies": {
23
+ "@gradio/preview": "0.12.0"
24
+ },
25
+ "main": "./Index.svelte",
26
+ "main_changeset": true,
27
+ "exports": {
28
+ ".": {
29
+ "gradio": "./Index.svelte"
30
+ },
31
+ "./example": {
32
+ "gradio": "./Example.svelte"
33
+ },
34
+ "./package.json": "./package.json"
35
+ }
36
+ }
gradio_molecule3d/frontend/shared/.DS_Store ADDED
Binary file (6.15 kB). View file
 
gradio_molecule3d/frontend/shared/Example.svelte ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <script lang="ts">
2
+ import type { FileData } from "@gradio/client";
3
+
4
+ export let value: FileData | null;
5
+ export let type: "gallery" | "table";
6
+ export let selected = false;
7
+ </script>
8
+
9
+ <div
10
+ class:table={type === "table"}
11
+ class:gallery={type === "gallery"}
12
+ class:selected
13
+ >
14
+ {value ? (Array.isArray(value) ? value.join(", ") : value) : ""}
15
+ </div>
16
+
17
+ <style>
18
+ div {
19
+ overflow: hidden;
20
+ text-overflow: ellipsis;
21
+ white-space: nowrap;
22
+ }
23
+ .gallery {
24
+ display: flex;
25
+ align-items: center;
26
+ cursor: pointer;
27
+ padding: var(--size-1) var(--size-2);
28
+ text-align: left;
29
+ }
30
+ </style>
gradio_molecule3d/frontend/shared/Index.svelte ADDED
@@ -0,0 +1,326 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <svelte:options accessors={true} />
2
+
3
+ <script context="module" lang="ts">
4
+ export { default as FilePreview } from "./shared/FilePreview.svelte";
5
+ export { default as BaseFileUpload } from "./shared/FileUpload.svelte";
6
+ export { default as BaseFile } from "./shared/File.svelte";
7
+ export { default as BaseExample } from "./Example.svelte";
8
+ </script>
9
+
10
+ <script lang="ts">
11
+ import "./style.css";
12
+ import type { Gradio, SelectData } from "@gradio/utils";
13
+ import File from "./shared/File.svelte";
14
+ import FileUpload from "./shared/FileUpload.svelte";
15
+ import type { FileData } from "@gradio/client";
16
+ import { Block, UploadText } from "@gradio/atoms";
17
+ import { StatusTracker } from "@gradio/statustracker";
18
+ import type { LoadingStatus } from "@gradio/statustracker";
19
+ export let elem_id = "";
20
+ export let elem_classes: string[] = [];
21
+ export let visible = true;
22
+ export let value: null | FileData | FileData[];
23
+ export let interactive: boolean;
24
+ export let root: string;
25
+ export let label: string;
26
+ export let show_label: boolean;
27
+ export let height: number | undefined = undefined;
28
+ //Molecule3D specific arguments
29
+ export let reps: any = [];
30
+ export let config: any = {};
31
+ export let confidenceLabel: string = "";
32
+ export let showviewer: boolean = true;
33
+ export let _selectable = false;
34
+ export let loading_status: LoadingStatus;
35
+ export let container = true;
36
+ export let scale: number | null = null;
37
+ export let min_width: number | undefined = undefined;
38
+ export let gradio: Gradio<{
39
+ change: never;
40
+ error: string;
41
+ upload: never;
42
+ clear: never;
43
+ select: SelectData;
44
+ clear_status: LoadingStatus;
45
+ delete: FileData;
46
+ }>;
47
+ export let file_count: "single" | "multiple" | "directory";
48
+ export let file_types: string[] = ["file"];
49
+ let old_value = value;
50
+ $: if (JSON.stringify(old_value) !== JSON.stringify(value)) {
51
+ gradio.dispatch("change");
52
+ old_value = value;
53
+ moldata = null;
54
+ retrieveContent(value);
55
+ }
56
+ $: if (JSON.stringify(reps) !== JSON.stringify(reps)) {
57
+ gradio.dispatch("change");
58
+ old_value = value;
59
+ // console.log("reps changed");
60
+ // console.log(reps);
61
+ moldata = null;
62
+ retrieveContent(value);
63
+ }
64
+ let dragging = false;
65
+ let pending_upload = false;
66
+ let keys_for_reps = {
67
+ model: {
68
+ type: Number,
69
+ default: 0,
70
+ },
71
+ chain: {
72
+ type: String,
73
+ default: "",
74
+ },
75
+ resname: {
76
+ type: String,
77
+ default: "",
78
+ },
79
+ style: {
80
+ type: String,
81
+ default: "cartoon",
82
+ choices: ["cartoon", "stick", "sphere", "surface"],
83
+ },
84
+ color: {
85
+ type: String,
86
+ default: "whiteCarbon",
87
+ choices: [
88
+ "whiteCarbon",
89
+ "orangeCarbon",
90
+ "redCarbon",
91
+ "blackCarbon",
92
+ "blueCarbon",
93
+ "grayCarbon",
94
+ "greenCarbon",
95
+ "cyanCarbon",
96
+ "alphafold",
97
+ "default",
98
+ "Jmol",
99
+ "chain",
100
+ "spectrum",
101
+ ],
102
+ },
103
+ opacity: {
104
+ type: Number,
105
+ default: 1,
106
+ },
107
+ residue_range: {
108
+ type: String,
109
+ default: "",
110
+ },
111
+ around: {
112
+ type: Number,
113
+ default: 0,
114
+ },
115
+ byres: {
116
+ type: Boolean,
117
+ default: false,
118
+ },
119
+ visible: {
120
+ type: Boolean,
121
+ default: true,
122
+ },
123
+ };
124
+ let moldata = null;
125
+ let allowed_extensions = ["pdb", "sdf", "mol2", "pdb1", "cif", "traj", "xyz"];
126
+ async function fetchFileContent(url) {
127
+ const response = await fetch(url);
128
+ const content = await response.text();
129
+ return content;
130
+ }
131
+ let promise = null;
132
+ let errors = [];
133
+ async function retrieveContent(value) {
134
+ if (value == null) {
135
+ return [];
136
+ } else if (Array.isArray(value)) {
137
+ let tempMoldata = [];
138
+ // get file extension
139
+ for (const element of value) {
140
+ let ext = element.orig_name.split(".").pop();
141
+ if (!allowed_extensions.includes(ext)) {
142
+ errors.push(
143
+ `Invalid file extension for ${
144
+ element.orig_name
145
+ }. Expected one of ${allowed_extensions.join(", ")}, got ${ext}`
146
+ );
147
+ moldata = null;
148
+ continue;
149
+ }
150
+ tempMoldata.push({
151
+ data: await fetchFileContent(element.url),
152
+ name: element.orig_name,
153
+ format: ext,
154
+ asFrames: false,
155
+ });
156
+ }
157
+ moldata = tempMoldata;
158
+ } else if (typeof value === "object" && value !== null) {
159
+ let ext = value.orig_name.split(".").pop();
160
+ if (!allowed_extensions.includes(ext)) {
161
+ errors.push(
162
+ `Invalid file extension for ${
163
+ value.orig_name
164
+ }. Expected one of ${allowed_extensions.join(", ")}, got ${ext}`
165
+ );
166
+ moldata = null;
167
+ } else {
168
+ let t = await fetchFileContent(value.url);
169
+ let ext = value.orig_name.split(".").pop();
170
+ if (ext === "pdb1") {
171
+ ext = "pdb";
172
+ }
173
+ moldata = [
174
+ { data: t, name: value.orig_name, format: ext, asFrames: false },
175
+ ];
176
+ }
177
+ } else {
178
+ moldata = null;
179
+ }
180
+ // value is object
181
+ }
182
+ // go through each rep, do a type check and add missing keys to the rep
183
+ let lenMoldata = 0;
184
+ $: lenMoldata = moldata ? moldata.length : 0;
185
+ let representations = [];
186
+ //first add all missing keys
187
+ $: {
188
+ reps.forEach((rep) => {
189
+ for (const [key, value] of Object.entries(keys_for_reps)) {
190
+ if (rep[key] === undefined) {
191
+ rep[key] = value["default"];
192
+ }
193
+ if (rep[key].constructor != value["type"]) {
194
+ errors.push(
195
+ `Invalid type for ${key} in reps. Expected ${
196
+ value["type"]
197
+ }, got ${typeof rep[key]}`
198
+ );
199
+ }
200
+ }
201
+ });
202
+ // then check if model does exist and add to representations
203
+ reps.forEach((rep) => {
204
+ if (rep["model"] <= lenMoldata) {
205
+ representations.push(rep);
206
+ }
207
+ });
208
+ }
209
+ $: promise = retrieveContent(value);
210
+ </script>
211
+
212
+ <Block
213
+ {visible}
214
+ variant={value ? "solid" : "dashed"}
215
+ border_mode={dragging ? "focus" : "base"}
216
+ padding={false}
217
+ {elem_id}
218
+ {elem_classes}
219
+ {container}
220
+ {scale}
221
+ {min_width}
222
+ allow_overflow={false}
223
+ >
224
+ <StatusTracker
225
+ autoscroll={gradio.autoscroll}
226
+ i18n={gradio.i18n}
227
+ {...loading_status}
228
+ status={pending_upload
229
+ ? "generating"
230
+ : loading_status?.status || "complete"}
231
+ on:clear_status={() => gradio.dispatch("clear_status", loading_status)}
232
+ />
233
+ {#if !interactive}
234
+ <File
235
+ on:select={({ detail }) => gradio.dispatch("select", detail)}
236
+ selectable={_selectable}
237
+ {value}
238
+ {label}
239
+ {show_label}
240
+ {height}
241
+ {representations}
242
+ {config}
243
+ {confidenceLabel}
244
+ {moldata}
245
+ {errors}
246
+ i18n={gradio.i18n}
247
+ molviewer={showviewer}
248
+ />
249
+ {:else}
250
+ <FileUpload
251
+ upload={gradio.client.upload}
252
+ stream_handler={gradio.client.stream}
253
+ {label}
254
+ {show_label}
255
+ {value}
256
+ {file_count}
257
+ {file_types}
258
+ selectable={_selectable}
259
+ {root}
260
+ {height}
261
+ {representations}
262
+ {config}
263
+ {confidenceLabel}
264
+ {moldata}
265
+ molviewer={showviewer}
266
+ max_file_size={gradio.max_file_size}
267
+ on:change={({ detail }) => {
268
+ value = detail;
269
+ }}
270
+ on:drag={({ detail }) => (dragging = detail)}
271
+ on:clear={() => gradio.dispatch("clear")}
272
+ on:select={({ detail }) => gradio.dispatch("select", detail)}
273
+ on:notfound={() =>
274
+ gradio.dispatch(
275
+ "error",
276
+ "identifier not found in database, check spelling"
277
+ )}
278
+ on:upload={() => gradio.dispatch("upload")}
279
+ on:error={({ detail }) => {
280
+ loading_status = loading_status || {};
281
+ loading_status.status = "error";
282
+ gradio.dispatch("error", detail);
283
+ }}
284
+ on:delete={({ detail }) => {
285
+ gradio.dispatch("delete", detail);
286
+ }}
287
+ i18n={gradio.i18n}
288
+ >
289
+ <UploadText i18n={gradio.i18n} type="file" />
290
+ </FileUpload>
291
+ {/if}
292
+
293
+ {#if errors.length > 0 && value !== null}
294
+ <div
295
+ class="flex m-2 p-4 mb-4 text-sm text-red-800 rounded-lg bg-red-50 dark:bg-gray-800 dark:text-red-400"
296
+ role="alert"
297
+ >
298
+ <svg
299
+ class="flex-shrink-0 inline w-4 h-4 mr-3 mt-[2px]"
300
+ xmlns="http://www.w3.org/2000/svg"
301
+ fill="none"
302
+ viewBox="0 0 24 24"
303
+ stroke-width="1.5"
304
+ stroke="currentColor"
305
+ >
306
+ <path
307
+ stroke-linecap="round"
308
+ stroke-linejoin="round"
309
+ d="M12 9v3.75m-9.303 3.376c-.866 1.5.217 3.374 1.948 3.374h14.71c1.73 0 2.813-1.874 1.948-3.374L13.949 3.378c-.866-1.5-3.032-1.5-3.898 0L2.697 16.126zM12 15.75h.007v.008H12v-.008z"
310
+ />
311
+ </svg>
312
+
313
+ <span class="sr-only">Error in the representations</span>
314
+ <div>
315
+ <span class="font-medium"
316
+ >Couldn't display Molecule. Fix the following problems:</span
317
+ >
318
+ <ul class="mt-1.5 ml-4 list-disc list-inside">
319
+ {#each errors as error}
320
+ <li>{error}</li>
321
+ {/each}
322
+ </ul>
323
+ </div>
324
+ </div>
325
+ {/if}
326
+ </Block>
gradio_molecule3d/frontend/shared/gradio.config.js ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import tailwindcss from "@tailwindcss/vite";
2
+
3
+ export default {
4
+ plugins: [tailwindcss()],
5
+ svelte: {
6
+ preprocess: [],
7
+ },
8
+ build: {
9
+ target: "modules",
10
+ },
11
+ };
gradio_molecule3d/frontend/shared/package-lock.json ADDED
The diff for this file is too large to render. See raw diff
 
gradio_molecule3d/frontend/shared/package.json ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "name": "gradio_molecule3d",
3
+ "version": "0.9.2",
4
+ "description": "Gradio UI packages",
5
+ "type": "module",
6
+ "author": "",
7
+ "license": "ISC",
8
+ "private": false,
9
+ "dependencies": {
10
+ "@gradio/atoms": "^0.9.0",
11
+ "@gradio/client": "^1.6.0",
12
+ "@gradio/icons": "^0.8.0",
13
+ "@gradio/markdown": "^0.10.1",
14
+ "@gradio/statustracker": "^0.8.1",
15
+ "@gradio/upload": "^0.13.1",
16
+ "@gradio/utils": "^0.7.0",
17
+ "@gradio/wasm": "^0.14.1",
18
+ "@tailwindcss/vite": "^4.0.0-alpha.30",
19
+ "3dmol": "^2.4.0",
20
+ "tailwindcss": "^4.0.0-alpha.30"
21
+ },
22
+ "devDependencies": {
23
+ "@gradio/preview": "0.12.0"
24
+ },
25
+ "main": "./Index.svelte",
26
+ "main_changeset": true,
27
+ "exports": {
28
+ ".": {
29
+ "gradio": "./Index.svelte"
30
+ },
31
+ "./example": {
32
+ "gradio": "./Example.svelte"
33
+ },
34
+ "./package.json": "./package.json"
35
+ }
36
+ }
gradio_molecule3d/frontend/shared/style.css ADDED
@@ -0,0 +1 @@
 
 
1
+ @import "tailwindcss";
gradio_molecule3d/frontend/style.css ADDED
@@ -0,0 +1 @@
 
 
1
+ @import "tailwindcss";
gradio_molecule3d/package.json ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ {
2
+ "devDependencies": {
3
+ "@gradio/preview": "^0.13.0"
4
+ }
5
+ }
gradio_molecule3d/pyproject.toml ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [build-system]
2
+ requires = [
3
+ "hatchling",
4
+ "hatch-requirements-txt",
5
+ "hatch-fancy-pypi-readme>=22.5.0",
6
+ ]
7
+ build-backend = "hatchling.build"
8
+
9
+ [project]
10
+ name = "gradio_molecule3d"
11
+ version = "0.0.7"
12
+ description = "Python library for easily interacting with trained machine learning models"
13
+ readme = "README.md"
14
+ license = "Apache-2.0"
15
+ requires-python = ">=3.8"
16
+ authors = [{ name = "YOUR NAME", email = "YOUREMAIL@domain.com" }]
17
+ keywords = [
18
+ "machine learning",
19
+ "reproducibility",
20
+ "visualization",
21
+ "gradio",
22
+ "gradio custom component",
23
+ "gradio-template-File",
24
+ "protein"
25
+ ]
26
+ # Add dependencies here
27
+ dependencies = ["gradio>=4.0,<6.0"]
28
+ classifiers = [
29
+ 'Development Status :: 3 - Alpha',
30
+ 'Operating System :: OS Independent',
31
+ 'Programming Language :: Python :: 3',
32
+ 'Programming Language :: Python :: 3 :: Only',
33
+ 'Programming Language :: Python :: 3.8',
34
+ 'Programming Language :: Python :: 3.9',
35
+ 'Programming Language :: Python :: 3.10',
36
+ 'Programming Language :: Python :: 3.11',
37
+ 'Topic :: Scientific/Engineering',
38
+ 'Topic :: Scientific/Engineering :: Artificial Intelligence',
39
+ 'Topic :: Scientific/Engineering :: Visualization',
40
+ ]
41
+
42
+
43
+ [project.optional-dependencies]
44
+ dev = ["build", "twine"]
45
+
46
+ [tool.hatch.build]
47
+ artifacts = ["/backend/gradio_molecule3d/templates", "*.pyi", "/Users/zulissi/micromamba/envs/gradio/lib/python3.12/site-packages/gradio_molecule3d/templates", "/private/home/zulissi/conda_envs/fairchem_020625/lib/python3.12/site-packages/gradio_molecule3d/templates"]
48
+
49
+ [tool.hatch.build.targets.wheel]
50
+ packages = ["/backend/gradio_molecule3d"]