annabossler commited on
Commit
4a6a364
·
verified ·
1 Parent(s): 729c89b

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +32 -37
app.py CHANGED
@@ -2,48 +2,41 @@ import os
2
  import tempfile
3
  import numpy as np
4
  import gradio as gr
5
- from ase.io import read
6
  from ase.io.trajectory import Trajectory
7
  import hashlib
8
 
9
  # ==== Usar componente nativo Molecule3D ====
10
  try:
11
  from gradio_molecule3d import Molecule3D
12
- HAVE_MOL3D = True
13
  print("✅ gradio_molecule3d loaded successfully")
14
  except Exception as e:
15
  HAVE_MOL3D = False
16
  print(f"❌ gradio_molecule3d not available: {e}")
17
 
18
- # ==== Función para convertir trayectoria a archivo temporal XYZ ====
19
  def traj_to_molecule3d_file(traj_path):
20
  """
21
- Convierte una trayectoria ASE (.traj) a un archivo XYZ temporal para Molecule3D.
22
- Retorna el path del archivo temporal.
23
  """
24
  if not traj_path or not os.path.exists(traj_path):
25
  return None
26
-
27
  try:
28
  traj = Trajectory(traj_path)
29
  if len(traj) == 0:
30
  return None
31
-
32
  # Usar último frame para visualización estática
33
  atoms = traj[-1]
34
-
35
- # Crear archivo XYZ temporal
36
- with tempfile.NamedTemporaryFile(mode='w', suffix='.xyz', delete=False) as f:
37
- symbols = atoms.get_chemical_symbols()
38
- coords = atoms.get_positions()
39
-
40
- f.write(f"{len(symbols)}\n")
41
- f.write("Generated by OrbMol\n")
42
- for s, (x, y, z) in zip(symbols, coords):
43
- f.write(f"{s} {x:.6f} {y:.6f} {z:.6f}\n")
44
-
45
- return f.name
46
-
47
  except Exception as e:
48
  print(f"Error converting trajectory: {e}")
49
  return None
@@ -55,9 +48,9 @@ def traj_to_html(traj_path, width=520, height=520, interval_ms=200):
55
  """
56
  if not traj_path or not os.path.exists(traj_path):
57
  return "<div style='color:#b00; padding:20px;'>No trajectory file found</div>"
58
-
59
  viewer_id = f"viewer_{abs(hash(traj_path)) % 10000}"
60
-
61
  try:
62
  traj = Trajectory(traj_path)
63
  if len(traj) == 0:
@@ -95,11 +88,11 @@ if (typeof window.$3Dmol === 'undefined') {{
95
  function initViewer_{viewer_id}() {{
96
  var el = document.getElementById("{viewer_id}");
97
  if (!el || typeof $3Dmol === "undefined") return;
98
-
99
  var viewer = $3Dmol.createViewer(el, {{backgroundColor: 'white'}});
100
  var frames = {frames_json};
101
  var currentFrame = 0;
102
-
103
  function showFrame(frameIndex) {{
104
  viewer.clear();
105
  viewer.addModel(frames[frameIndex], "xyz");
@@ -107,9 +100,9 @@ function initViewer_{viewer_id}() {{
107
  viewer.zoomTo();
108
  viewer.render();
109
  }}
110
-
111
  showFrame(0);
112
-
113
  if (frames.length > 1) {{
114
  setInterval(function() {{
115
  currentFrame = (currentFrame + 1) % frames.length;
@@ -213,8 +206,8 @@ def md_wrapper(xyz_content, charge, spin, steps, tempK, timestep_fs, ensemble):
213
 
214
  # Usar Molecule3D si está disponible, sino HTML
215
  if HAVE_MOL3D:
216
- xyz_file = traj_to_molecule3d_file(traj_path)
217
- return (status, traj_path, log_text, script_text, explanation, xyz_file, "")
218
  else:
219
  html_value = traj_to_html(traj_path)
220
  return (status, traj_path, log_text, script_text, explanation, None, html_value)
@@ -244,8 +237,8 @@ def relax_wrapper(xyz_content, steps, fmax, charge, spin, relax_cell):
244
 
245
  # Usar Molecule3D si está disponible, sino HTML
246
  if HAVE_MOL3D:
247
- xyz_file = traj_to_molecule3d_file(traj_path)
248
- return (status, traj_path, log_text, script_text, explanation, xyz_file, "")
249
  else:
250
  html_value = traj_to_html(traj_path)
251
  return (status, traj_path, log_text, script_text, explanation, None, html_value)
@@ -254,8 +247,10 @@ def relax_wrapper(xyz_content, steps, fmax, charge, spin, relax_cell):
254
  return (f"Error: {e}", None, "", "", "", None, "")
255
  finally:
256
  if tmp_created and isinstance(path_or_str, str) and os.path.exists(path_or_str):
257
- try: os.remove(path_or_str)
258
- except Exception: pass
 
 
259
 
260
  # ==== Ejemplos (sin cambios) ====
261
  examples = [
@@ -317,7 +312,7 @@ with gr.Blocks(theme=gr.themes.Ocean(), title="OrbMol Demo") as demo:
317
  with gr.Column(variant="panel", min_width=520):
318
  md_status = gr.Textbox(label="MD Status", interactive=False)
319
  md_traj = gr.File(label="Trajectory (.traj)", interactive=False)
320
-
321
  # Usar Molecule3D si está disponible
322
  if HAVE_MOL3D:
323
  md_viewer = Molecule3D(label="3D Molecular Viewer")
@@ -325,7 +320,7 @@ with gr.Blocks(theme=gr.themes.Ocean(), title="OrbMol Demo") as demo:
325
  else:
326
  md_viewer = gr.HTML(visible=False) # Placeholder
327
  md_html = gr.HTML(label="Trajectory Viewer")
328
-
329
  md_log = gr.Textbox(label="Log", interactive=False, lines=15, max_lines=25)
330
  md_script = gr.Code(label="Reproduction Script", language="python", interactive=False, lines=20, max_lines=30)
331
  md_explain = gr.Markdown()
@@ -352,7 +347,7 @@ with gr.Blocks(theme=gr.themes.Ocean(), title="OrbMol Demo") as demo:
352
  with gr.Column(variant="panel", min_width=520):
353
  rlx_status = gr.Textbox(label="Status", interactive=False)
354
  rlx_traj = gr.File(label="Trajectory (.traj)", interactive=False)
355
-
356
  # Usar Molecule3D si está disponible
357
  if HAVE_MOL3D:
358
  rlx_viewer = Molecule3D(label="Final Structure")
@@ -360,7 +355,7 @@ with gr.Blocks(theme=gr.themes.Ocean(), title="OrbMol Demo") as demo:
360
  else:
361
  rlx_viewer = gr.HTML(visible=False) # Placeholder
362
  rlx_html = gr.HTML(label="Final Structure")
363
-
364
  rlx_log = gr.Textbox(label="Log", interactive=False, lines=15, max_lines=25)
365
  rlx_script = gr.Code(label="Reproduction Script", language="python", interactive=False, lines=20, max_lines=30)
366
  rlx_explain = gr.Markdown()
@@ -375,4 +370,4 @@ print("Starting OrbMol model loading…")
375
  _ = _load_orbmol_calc()
376
 
377
  if __name__ == "__main__":
378
- demo.launch(server_name="0.0.0.0", server_port=7860, show_error=True)
 
2
  import tempfile
3
  import numpy as np
4
  import gradio as gr
5
+ from ase.io import read, write
6
  from ase.io.trajectory import Trajectory
7
  import hashlib
8
 
9
  # ==== Usar componente nativo Molecule3D ====
10
  try:
11
  from gradio_molecule3d import Molecule3D
12
+ HAVE_MOL3D = True
13
  print("✅ gradio_molecule3d loaded successfully")
14
  except Exception as e:
15
  HAVE_MOL3D = False
16
  print(f"❌ gradio_molecule3d not available: {e}")
17
 
18
+ # ==== Función para convertir trayectoria a archivo temporal PDB ====
19
  def traj_to_molecule3d_file(traj_path):
20
  """
21
+ Convierte una trayectoria ASE (.traj) a un archivo PDB temporal para Molecule3D.
22
+ Retorna el path del archivo temporal (.pdb).
23
  """
24
  if not traj_path or not os.path.exists(traj_path):
25
  return None
 
26
  try:
27
  traj = Trajectory(traj_path)
28
  if len(traj) == 0:
29
  return None
30
+
31
  # Usar último frame para visualización estática
32
  atoms = traj[-1]
33
+
34
+ # Crear archivo PDB temporal (formato aceptado por Molecule3D)
35
+ with tempfile.NamedTemporaryFile(suffix=".pdb", delete=False) as f:
36
+ pdb_path = f.name
37
+ write(pdb_path, atoms) # extensión .pdb selecciona el formato automáticamente
38
+ return pdb_path
39
+
 
 
 
 
 
 
40
  except Exception as e:
41
  print(f"Error converting trajectory: {e}")
42
  return None
 
48
  """
49
  if not traj_path or not os.path.exists(traj_path):
50
  return "<div style='color:#b00; padding:20px;'>No trajectory file found</div>"
51
+
52
  viewer_id = f"viewer_{abs(hash(traj_path)) % 10000}"
53
+
54
  try:
55
  traj = Trajectory(traj_path)
56
  if len(traj) == 0:
 
88
  function initViewer_{viewer_id}() {{
89
  var el = document.getElementById("{viewer_id}");
90
  if (!el || typeof $3Dmol === "undefined") return;
91
+
92
  var viewer = $3Dmol.createViewer(el, {{backgroundColor: 'white'}});
93
  var frames = {frames_json};
94
  var currentFrame = 0;
95
+
96
  function showFrame(frameIndex) {{
97
  viewer.clear();
98
  viewer.addModel(frames[frameIndex], "xyz");
 
100
  viewer.zoomTo();
101
  viewer.render();
102
  }}
103
+
104
  showFrame(0);
105
+
106
  if (frames.length > 1) {{
107
  setInterval(function() {{
108
  currentFrame = (currentFrame + 1) % frames.length;
 
206
 
207
  # Usar Molecule3D si está disponible, sino HTML
208
  if HAVE_MOL3D:
209
+ pdb_file = traj_to_molecule3d_file(traj_path)
210
+ return (status, traj_path, log_text, script_text, explanation, pdb_file, "")
211
  else:
212
  html_value = traj_to_html(traj_path)
213
  return (status, traj_path, log_text, script_text, explanation, None, html_value)
 
237
 
238
  # Usar Molecule3D si está disponible, sino HTML
239
  if HAVE_MOL3D:
240
+ pdb_file = traj_to_molecule3d_file(traj_path)
241
+ return (status, traj_path, log_text, script_text, explanation, pdb_file, "")
242
  else:
243
  html_value = traj_to_html(traj_path)
244
  return (status, traj_path, log_text, script_text, explanation, None, html_value)
 
247
  return (f"Error: {e}", None, "", "", "", None, "")
248
  finally:
249
  if tmp_created and isinstance(path_or_str, str) and os.path.exists(path_or_str):
250
+ try:
251
+ os.remove(path_or_str)
252
+ except Exception:
253
+ pass
254
 
255
  # ==== Ejemplos (sin cambios) ====
256
  examples = [
 
312
  with gr.Column(variant="panel", min_width=520):
313
  md_status = gr.Textbox(label="MD Status", interactive=False)
314
  md_traj = gr.File(label="Trajectory (.traj)", interactive=False)
315
+
316
  # Usar Molecule3D si está disponible
317
  if HAVE_MOL3D:
318
  md_viewer = Molecule3D(label="3D Molecular Viewer")
 
320
  else:
321
  md_viewer = gr.HTML(visible=False) # Placeholder
322
  md_html = gr.HTML(label="Trajectory Viewer")
323
+
324
  md_log = gr.Textbox(label="Log", interactive=False, lines=15, max_lines=25)
325
  md_script = gr.Code(label="Reproduction Script", language="python", interactive=False, lines=20, max_lines=30)
326
  md_explain = gr.Markdown()
 
347
  with gr.Column(variant="panel", min_width=520):
348
  rlx_status = gr.Textbox(label="Status", interactive=False)
349
  rlx_traj = gr.File(label="Trajectory (.traj)", interactive=False)
350
+
351
  # Usar Molecule3D si está disponible
352
  if HAVE_MOL3D:
353
  rlx_viewer = Molecule3D(label="Final Structure")
 
355
  else:
356
  rlx_viewer = gr.HTML(visible=False) # Placeholder
357
  rlx_html = gr.HTML(label="Final Structure")
358
+
359
  rlx_log = gr.Textbox(label="Log", interactive=False, lines=15, max_lines=25)
360
  rlx_script = gr.Code(label="Reproduction Script", language="python", interactive=False, lines=20, max_lines=30)
361
  rlx_explain = gr.Markdown()
 
370
  _ = _load_orbmol_calc()
371
 
372
  if __name__ == "__main__":
373
+ demo.launch(server_name="0.0.0.0", server_port=7860, show_error=True)