Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -17,63 +17,45 @@ except ImportError as e:
|
|
| 17 |
MOLECULE3D_AVAILABLE = False
|
| 18 |
print(f"❌ gradio_molecule3d import failed: {e}")
|
| 19 |
|
| 20 |
-
# ====
|
| 21 |
-
def
|
| 22 |
-
"""
|
| 23 |
-
print(f"\n=== DEBUG PDB CREATION ===")
|
| 24 |
-
print(f"Input trajectory: {traj_path}")
|
| 25 |
-
print(f"Trajectory exists: {os.path.exists(traj_path) if traj_path else False}")
|
| 26 |
-
|
| 27 |
-
if not traj_path or not os.path.exists(traj_path):
|
| 28 |
-
return None, "No trajectory file"
|
| 29 |
-
|
| 30 |
try:
|
| 31 |
-
#
|
| 32 |
-
|
| 33 |
-
print(f"Trajectory frames: {len(traj)}")
|
| 34 |
-
|
| 35 |
-
if len(traj) == 0:
|
| 36 |
-
return None, "Empty trajectory"
|
| 37 |
-
|
| 38 |
-
# Step 2: Get atoms
|
| 39 |
-
atoms = traj[-1]
|
| 40 |
-
print(f"Atoms count: {len(atoms)}")
|
| 41 |
-
print(f"Chemical symbols: {atoms.get_chemical_symbols()[:5]}...") # First 5
|
| 42 |
-
|
| 43 |
-
# Step 3: Create cache directory
|
| 44 |
-
cache_dir = os.path.join(tempfile.gettempdir(), "gradio_cache")
|
| 45 |
os.makedirs(cache_dir, exist_ok=True)
|
| 46 |
print(f"Cache directory: {cache_dir}")
|
| 47 |
-
print(f"Cache dir exists: {os.path.exists(cache_dir)}")
|
| 48 |
|
| 49 |
-
#
|
| 50 |
-
|
| 51 |
-
pdb_filename = f"mol_{
|
| 52 |
pdb_path = os.path.join(cache_dir, pdb_filename)
|
| 53 |
-
print(f"
|
| 54 |
|
| 55 |
-
#
|
| 56 |
write(pdb_path, atoms, format='pdb')
|
| 57 |
-
print(f"PDB written, exists: {os.path.exists(pdb_path)}")
|
| 58 |
|
|
|
|
| 59 |
if os.path.exists(pdb_path):
|
| 60 |
file_size = os.path.getsize(pdb_path)
|
| 61 |
-
print(f"PDB
|
| 62 |
|
| 63 |
-
# Read first few lines
|
| 64 |
with open(pdb_path, 'r') as f:
|
| 65 |
-
first_lines = f.read(
|
| 66 |
-
print(f"PDB
|
| 67 |
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
|
|
|
|
|
|
| 71 |
|
| 72 |
except Exception as e:
|
| 73 |
-
print(f"
|
| 74 |
import traceback
|
| 75 |
traceback.print_exc()
|
| 76 |
-
return None
|
| 77 |
|
| 78 |
# ==== Simple molecule viewer using HTML + 3Dmol.js ====
|
| 79 |
def create_simple_molecule_viewer(atoms_or_pdb_path, viewer_id="mol_viewer"):
|
|
@@ -177,6 +159,33 @@ def _load_orbmol_calc():
|
|
| 177 |
_MODEL_CALC = ORBCalculator(orbff, device="cpu")
|
| 178 |
return _MODEL_CALC
|
| 179 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 180 |
def predict_molecule(structure_file, charge=0, spin_multiplicity=1):
|
| 181 |
"""Single Point Energy + fuerzas (OrbMol)"""
|
| 182 |
try:
|
|
@@ -205,18 +214,25 @@ def predict_molecule(structure_file, charge=0, spin_multiplicity=1):
|
|
| 205 |
max_force = float(np.max(np.linalg.norm(forces, axis=1)))
|
| 206 |
lines += ["", f"Max Force: {max_force:.4f} eV/Å"]
|
| 207 |
|
| 208 |
-
#
|
| 209 |
-
|
|
|
|
| 210 |
|
| 211 |
# Create viewer
|
| 212 |
if MOLECULE3D_AVAILABLE:
|
| 213 |
-
pdb_path
|
| 214 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 215 |
else:
|
| 216 |
html_viewer = create_simple_molecule_viewer(atoms, f"spe_viewer_{hash(file_path) % 10000}")
|
| 217 |
return "\n".join(lines), "Calculation completed with OrbMol", debug_info, html_viewer
|
| 218 |
except Exception as e:
|
| 219 |
error_msg = f"Error during calculation: {e}"
|
|
|
|
|
|
|
| 220 |
return error_msg, "Error", str(e), None if MOLECULE3D_AVAILABLE else ""
|
| 221 |
|
| 222 |
# ==== Simulaciones ====
|
|
@@ -248,9 +264,26 @@ def md_wrapper(structure_file, charge, spin, steps, tempK, timestep_fs, ensemble
|
|
| 248 |
print(f"MD completed, trajectory: {traj_path}")
|
| 249 |
|
| 250 |
if MOLECULE3D_AVAILABLE:
|
| 251 |
-
|
| 252 |
-
|
| 253 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 254 |
else:
|
| 255 |
# Create HTML viewer from last frame
|
| 256 |
traj = Trajectory(traj_path)
|
|
|
|
| 17 |
MOLECULE3D_AVAILABLE = False
|
| 18 |
print(f"❌ gradio_molecule3d import failed: {e}")
|
| 19 |
|
| 20 |
+
# ==== PDB creation for Molecule3D ====
|
| 21 |
+
def create_pdb_for_molecule3d(atoms):
|
| 22 |
+
"""Create a PDB file specifically for Molecule3D viewer"""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 23 |
try:
|
| 24 |
+
# Create gradio cache directory
|
| 25 |
+
cache_dir = os.path.join(tempfile.gettempdir(), "gradio")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 26 |
os.makedirs(cache_dir, exist_ok=True)
|
| 27 |
print(f"Cache directory: {cache_dir}")
|
|
|
|
| 28 |
|
| 29 |
+
# Create unique filename based on atomic positions
|
| 30 |
+
pos_hash = hashlib.md5(atoms.get_positions().tobytes()).hexdigest()[:12]
|
| 31 |
+
pdb_filename = f"mol_{pos_hash}.pdb"
|
| 32 |
pdb_path = os.path.join(cache_dir, pdb_filename)
|
| 33 |
+
print(f"Creating PDB: {pdb_path}")
|
| 34 |
|
| 35 |
+
# Write PDB file using ASE
|
| 36 |
write(pdb_path, atoms, format='pdb')
|
|
|
|
| 37 |
|
| 38 |
+
# Verify file was created and has content
|
| 39 |
if os.path.exists(pdb_path):
|
| 40 |
file_size = os.path.getsize(pdb_path)
|
| 41 |
+
print(f"PDB created successfully: {file_size} bytes")
|
| 42 |
|
| 43 |
+
# Read and log first few lines for verification
|
| 44 |
with open(pdb_path, 'r') as f:
|
| 45 |
+
first_lines = f.read(200)
|
| 46 |
+
print(f"PDB preview: {first_lines[:100]}...")
|
| 47 |
|
| 48 |
+
if file_size > 0:
|
| 49 |
+
return pdb_path
|
| 50 |
+
|
| 51 |
+
print("PDB file was not created or is empty")
|
| 52 |
+
return None
|
| 53 |
|
| 54 |
except Exception as e:
|
| 55 |
+
print(f"Error creating PDB for Molecule3D: {e}")
|
| 56 |
import traceback
|
| 57 |
traceback.print_exc()
|
| 58 |
+
return None
|
| 59 |
|
| 60 |
# ==== Simple molecule viewer using HTML + 3Dmol.js ====
|
| 61 |
def create_simple_molecule_viewer(atoms_or_pdb_path, viewer_id="mol_viewer"):
|
|
|
|
| 159 |
_MODEL_CALC = ORBCalculator(orbff, device="cpu")
|
| 160 |
return _MODEL_CALC
|
| 161 |
|
| 162 |
+
def create_pdb_for_molecule3d(atoms):
|
| 163 |
+
"""Create a PDB file specifically for Molecule3D viewer"""
|
| 164 |
+
try:
|
| 165 |
+
# Create gradio cache directory
|
| 166 |
+
cache_dir = os.path.join(tempfile.gettempdir(), "gradio")
|
| 167 |
+
os.makedirs(cache_dir, exist_ok=True)
|
| 168 |
+
|
| 169 |
+
# Create unique filename
|
| 170 |
+
unique_id = hashlib.md5(str(atoms.get_positions().tostring()).encode()).hexdigest()[:12]
|
| 171 |
+
pdb_filename = f"mol_{unique_id}.pdb"
|
| 172 |
+
pdb_path = os.path.join(cache_dir, pdb_filename)
|
| 173 |
+
|
| 174 |
+
# Write PDB file
|
| 175 |
+
write(pdb_path, atoms, format='pdb')
|
| 176 |
+
|
| 177 |
+
# Verify file was created
|
| 178 |
+
if os.path.exists(pdb_path) and os.path.getsize(pdb_path) > 0:
|
| 179 |
+
print(f"✅ PDB created for Molecule3D: {pdb_path} ({os.path.getsize(pdb_path)} bytes)")
|
| 180 |
+
return pdb_path
|
| 181 |
+
else:
|
| 182 |
+
print("❌ PDB file was not created properly")
|
| 183 |
+
return None
|
| 184 |
+
|
| 185 |
+
except Exception as e:
|
| 186 |
+
print(f"❌ Error creating PDB: {e}")
|
| 187 |
+
return None
|
| 188 |
+
|
| 189 |
def predict_molecule(structure_file, charge=0, spin_multiplicity=1):
|
| 190 |
"""Single Point Energy + fuerzas (OrbMol)"""
|
| 191 |
try:
|
|
|
|
| 214 |
max_force = float(np.max(np.linalg.norm(forces, axis=1)))
|
| 215 |
lines += ["", f"Max Force: {max_force:.4f} eV/Å"]
|
| 216 |
|
| 217 |
+
# Create debug info
|
| 218 |
+
symbols = atoms.get_chemical_symbols()
|
| 219 |
+
debug_info = f"Molecule: {len(atoms)} atoms\nElements: {', '.join(set(symbols))}\nFormula: {''.join(sorted(symbols))}"
|
| 220 |
|
| 221 |
# Create viewer
|
| 222 |
if MOLECULE3D_AVAILABLE:
|
| 223 |
+
pdb_path = create_pdb_for_molecule3d(atoms)
|
| 224 |
+
if pdb_path:
|
| 225 |
+
debug_info += f"\nPDB created: ✅ {os.path.basename(pdb_path)}"
|
| 226 |
+
else:
|
| 227 |
+
debug_info += f"\nPDB creation: ❌ Failed"
|
| 228 |
+
return "\n".join(lines), "Calculation completed with OrbMol", debug_info, pdb_path
|
| 229 |
else:
|
| 230 |
html_viewer = create_simple_molecule_viewer(atoms, f"spe_viewer_{hash(file_path) % 10000}")
|
| 231 |
return "\n".join(lines), "Calculation completed with OrbMol", debug_info, html_viewer
|
| 232 |
except Exception as e:
|
| 233 |
error_msg = f"Error during calculation: {e}"
|
| 234 |
+
import traceback
|
| 235 |
+
traceback.print_exc()
|
| 236 |
return error_msg, "Error", str(e), None if MOLECULE3D_AVAILABLE else ""
|
| 237 |
|
| 238 |
# ==== Simulaciones ====
|
|
|
|
| 264 |
print(f"MD completed, trajectory: {traj_path}")
|
| 265 |
|
| 266 |
if MOLECULE3D_AVAILABLE:
|
| 267 |
+
# Read last frame from trajectory
|
| 268 |
+
try:
|
| 269 |
+
traj = Trajectory(traj_path)
|
| 270 |
+
last_atoms = traj[-1]
|
| 271 |
+
print(f"Read trajectory: {len(traj)} frames, last frame has {len(last_atoms)} atoms")
|
| 272 |
+
|
| 273 |
+
pdb_path = create_pdb_for_molecule3d(last_atoms)
|
| 274 |
+
|
| 275 |
+
debug_info = f"Trajectory: {len(traj)} frames\nLast frame: {len(last_atoms)} atoms"
|
| 276 |
+
if pdb_path:
|
| 277 |
+
debug_info += f"\nPDB: ✅ {os.path.basename(pdb_path)}"
|
| 278 |
+
else:
|
| 279 |
+
debug_info += f"\nPDB: ❌ Creation failed"
|
| 280 |
+
|
| 281 |
+
return (status, traj_path, log_text, script_text, explanation, pdb_path, debug_info)
|
| 282 |
+
|
| 283 |
+
except Exception as traj_error:
|
| 284 |
+
print(f"Error reading trajectory: {traj_error}")
|
| 285 |
+
debug_info = f"Trajectory error: {traj_error}"
|
| 286 |
+
return (status, traj_path, log_text, script_text, explanation, None, debug_info)
|
| 287 |
else:
|
| 288 |
# Create HTML viewer from last frame
|
| 289 |
traj = Trajectory(traj_path)
|