QQ2S3R commited on
Commit
9bb2bc4
·
verified ·
1 Parent(s): b5e3512

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +129 -135
app.py CHANGED
@@ -212,12 +212,10 @@ def init_molecule():
212
  }
213
 
214
  # 添加原子
215
- def add_atom(molecule, atom_type, x, y):
216
  molecule["atoms"].append({
217
  "id": len(molecule["atoms"]),
218
- "type": atom_type,
219
- "x": x,
220
- "y": y
221
  })
222
  return molecule
223
 
@@ -303,129 +301,6 @@ def visualize_molecule(molecule_json):
303
  logger.error(f"可视化分子失败: {str(e)}")
304
  return None
305
 
306
- # 分子构建界面
307
- def build_molecule_interface():
308
- # 初始化分子
309
- molecule = init_molecule()
310
-
311
- with gr.Blocks() as interface:
312
- gr.Markdown("### 构建分子")
313
-
314
- # 原子选择
315
- with gr.Row():
316
- atom_select = gr.Dropdown(
317
- label="选择原子类型",
318
- choices=ATOM_TYPES,
319
- value="C"
320
- )
321
- bond_select = gr.Dropdown(
322
- label="选择键类型",
323
- choices=BOND_TYPES,
324
- value="单键"
325
- )
326
-
327
- # 画布
328
- canvas = gr.Image(
329
- label="分子结构",
330
- interactive=True,
331
- tool="select",
332
- height=400
333
- )
334
-
335
- # 状态显示
336
- status = gr.Textbox(label="状态", interactive=False)
337
-
338
- # 操作按钮
339
- with gr.Row():
340
- add_atom_btn = gr.Button("添加原子")
341
- add_bond_btn = gr.Button("添加键")
342
- clear_btn = gr.Button("清除")
343
- generate_btn = gr.Button("生成分子")
344
-
345
- # 分子预览
346
- molecule_img = gr.Image(label="分子预览", interactive=False)
347
- molecule_smiles = gr.Textbox(label="生成的SMILES", interactive=False)
348
-
349
- # 存储分子结构的隐藏状态
350
- molecule_state = gr.State(molecule)
351
-
352
- # 原子位置存储
353
- last_click_pos = gr.State((0, 0))
354
-
355
- # 事件处理
356
- canvas.select(
357
- fn=lambda evt: {"x": evt.index[0], "y": evt.index[1]},
358
- outputs=last_click_pos
359
- )
360
-
361
- add_atom_btn.click(
362
- fn=lambda atom, pos, mol: add_atom(mol, atom, pos[0], pos[1]),
363
- inputs=[atom_select, last_click_pos, molecule_state],
364
- outputs=molecule_state
365
- ).then(
366
- fn=lambda mol: f"添加原子成功! 当前原子数: {len(mol['atoms'])}, 键数: {len(mol['bonds'])}",
367
- inputs=molecule_state,
368
- outputs=status
369
- )
370
-
371
- # 添加键需要选择两个原子
372
- atom1_state = gr.State(-1)
373
- atom2_state = gr.State(-1)
374
-
375
- canvas.select(
376
- fn=lambda evt, mol: {"atom_id": find_nearest_atom(mol, evt.index[0], evt.index[1])},
377
- inputs=molecule_state,
378
- outputs=atom1_state
379
- )
380
-
381
- canvas.select(
382
- fn=lambda evt, mol: {"atom_id": find_nearest_atom(mol, evt.index[0], evt.index[1])},
383
- inputs=molecule_state,
384
- outputs=atom2_state
385
- )
386
-
387
- add_bond_btn.click(
388
- fn=lambda bond, atom1, atom2, mol: add_bond(mol, atom1, atom2, bond),
389
- inputs=[bond_select, atom1_state, atom2_state, molecule_state],
390
- outputs=molecule_state
391
- ).then(
392
- fn=lambda mol: f"添加键成功! 当前原子数: {len(mol['atoms'])}, 键数: {len(mol['bonds'])}",
393
- inputs=molecule_state,
394
- outputs=status
395
- )
396
-
397
- clear_btn.click(
398
- fn=init_molecule,
399
- outputs=molecule_state
400
- ).then(
401
- fn=lambda: "已清除所有原子和键",
402
- outputs=status
403
- )
404
-
405
- generate_btn.click(
406
- fn=generate_smiles,
407
- inputs=molecule_state,
408
- outputs=molecule_smiles
409
- ).then(
410
- fn=visualize_molecule,
411
- inputs=molecule_state,
412
- outputs=molecule_img
413
- ).then(
414
- fn=lambda mol: f"分子生成完成! 原子数: {len(mol['atoms'])}, 键数: {len(mol['bonds'])}",
415
- inputs=molecule_state,
416
- outputs=status
417
- )
418
-
419
- return interface
420
-
421
- # 查找最近的原子
422
- def find_nearest_atom(molecule, x, y, radius=20):
423
- for atom in molecule["atoms"]:
424
- dist = ((atom["x"] - x)**2 + (atom["y"] - y)**2)**0.5
425
- if dist <= radius:
426
- return atom["id"]
427
- return -1
428
-
429
  # 使用TabbedInterface组织两种输入方式
430
  with gr.Blocks(title="CrystalGAT") as demo:
431
  gr.Markdown("# CrystalGAT")
@@ -451,17 +326,67 @@ with gr.Blocks(title="CrystalGAT") as demo:
451
 
452
  with gr.Tab("构建分子"):
453
  gr.Markdown("### 构建分子结构")
454
- gr.Markdown("1. 选择原子类型和键类型")
455
- gr.Markdown("2. 点击'添加原子'按钮后在画布上点击放置原子")
456
- gr.Markdown("3. 点击'添加键'按钮后依次点击两个原子连接它们")
457
- gr.Markdown("4. 完成后点击'生成分子'按钮")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
458
 
459
- # 分子构建界面
460
- build_interface = build_molecule_interface()
 
461
 
462
  # 预测按钮
463
  submit_btn2 = gr.Button("使用此分子进行预测", variant="primary")
464
- build_smiles = gr.Textbox(visible=False) # 隐藏的SMILES存储
465
 
466
  # 输出区域 (两种输入方式共享)
467
  gr.Markdown("## 预测结果")
@@ -475,6 +400,75 @@ with gr.Blocks(title="CrystalGAT") as demo:
475
  brittle_text = gr.Text(label="Brittle")
476
  brittle_img = gr.Image(type="pil", label="Brittle attention visualization")
477
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
478
  # 设置交互
479
  # SMILES输入路径
480
  submit_btn1.click(
@@ -486,7 +480,7 @@ with gr.Blocks(title="CrystalGAT") as demo:
486
  # 分子构建预测路径
487
  submit_btn2.click(
488
  fn=lambda smiles: predict_all(smiles) if smiles else ("请输入有效的SMILES", None, "", None, "", None),
489
- inputs=build_smiles,
490
  outputs=[elastic_text, elastic_img, plastic_text, plastic_img, brittle_text, brittle_img]
491
  )
492
 
 
212
  }
213
 
214
  # 添加原子
215
+ def add_atom(molecule, atom_type):
216
  molecule["atoms"].append({
217
  "id": len(molecule["atoms"]),
218
+ "type": atom_type
 
 
219
  })
220
  return molecule
221
 
 
301
  logger.error(f"可视化分子失败: {str(e)}")
302
  return None
303
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
304
  # 使用TabbedInterface组织两种输入方式
305
  with gr.Blocks(title="CrystalGAT") as demo:
306
  gr.Markdown("# CrystalGAT")
 
326
 
327
  with gr.Tab("构建分子"):
328
  gr.Markdown("### 构建分子结构")
329
+ gr.Markdown("1. 添加原子:选择原子类型并点击'添加原子'按钮")
330
+ gr.Markdown("2. 添加键:选择两个原子和键类型,然后点击'添加'按钮")
331
+ gr.Markdown("3. 完成后点击'生成分子'按钮预览并预测")
332
+
333
+ # 初始化分子状态
334
+ molecule_state = gr.State(init_molecule())
335
+
336
+ with gr.Row():
337
+ # 原子选择
338
+ with gr.Column():
339
+ gr.Markdown("### 添加原子")
340
+ atom_select = gr.Dropdown(
341
+ label="选择原子类型",
342
+ choices=ATOM_TYPES,
343
+ value="C"
344
+ )
345
+ add_atom_btn = gr.Button("添加原子")
346
+ atoms_list = gr.Dataframe(
347
+ label="原子列表",
348
+ headers=["ID", "原子类型"],
349
+ datatype=["number", "str"],
350
+ interactive=False
351
+ )
352
+
353
+ # 键选择
354
+ with gr.Column():
355
+ gr.Markdown("### 添加键")
356
+ atom1_select = gr.Dropdown(
357
+ label="选择第一个原子",
358
+ choices=[],
359
+ interactive=True
360
+ )
361
+ atom2_select = gr.Dropdown(
362
+ label="选择第二个原子",
363
+ choices=[],
364
+ interactive=True
365
+ )
366
+ bond_select = gr.Dropdown(
367
+ label="选择键类型",
368
+ choices=BOND_TYPES,
369
+ value="单键"
370
+ )
371
+ add_bond_btn = gr.Button("添加键")
372
+ bonds_list = gr.Dataframe(
373
+ label="键列表",
374
+ headers=["原子1", "原子2", "键类型"],
375
+ datatype=["number", "number", "str"],
376
+ interactive=False
377
+ )
378
+
379
+ # 操作按钮
380
+ with gr.Row():
381
+ clear_btn = gr.Button("清除所有")
382
+ generate_btn = gr.Button("生成分子")
383
 
384
+ # 分子预览
385
+ molecule_img = gr.Image(label="分子预览", interactive=False)
386
+ molecule_smiles = gr.Textbox(label="生成的SMILES", interactive=False)
387
 
388
  # 预测按钮
389
  submit_btn2 = gr.Button("使用此分子进行预测", variant="primary")
 
390
 
391
  # 输出区域 (两种输入方式共享)
392
  gr.Markdown("## 预测结果")
 
400
  brittle_text = gr.Text(label="Brittle")
401
  brittle_img = gr.Image(type="pil", label="Brittle attention visualization")
402
 
403
+ # 更新原子选择下拉菜单
404
+ def update_atom_dropdowns(molecule):
405
+ atom_ids = [f"{i}: {atom['type']}" for i, atom in enumerate(molecule["atoms"])]
406
+ return gr.Dropdown.update(choices=atom_ids), gr.Dropdown.update(choices=atom_ids)
407
+
408
+ # 更新原子列表
409
+ def update_atoms_list(molecule):
410
+ atoms_data = [[i, atom["type"]] for i, atom in enumerate(molecule["atoms"])]
411
+ return atoms_data
412
+
413
+ # 更新键列表
414
+ def update_bonds_list(molecule):
415
+ bonds_data = []
416
+ for bond in molecule["bonds"]:
417
+ atom1_type = molecule["atoms"][bond["atom1"]]["type"]
418
+ atom2_type = molecule["atoms"][bond["atom2"]]["type"]
419
+ bonds_data.append([
420
+ f"{bond['atom1']}: {atom1_type}",
421
+ f"{bond['atom2']}: {atom2_type}",
422
+ bond["type"]
423
+ ])
424
+ return bonds_data
425
+
426
+ # 事件处理
427
+ add_atom_btn.click(
428
+ fn=lambda atom, mol: add_atom(mol, atom),
429
+ inputs=[atom_select, molecule_state],
430
+ outputs=molecule_state
431
+ ).then(
432
+ fn=update_atoms_list,
433
+ inputs=molecule_state,
434
+ outputs=atoms_list
435
+ ).then(
436
+ fn=update_atom_dropdowns,
437
+ inputs=molecule_state,
438
+ outputs=[atom1_select, atom2_select]
439
+ )
440
+
441
+ add_bond_btn.click(
442
+ fn=lambda atom1, atom2, bond, mol: add_bond(mol, int(atom1.split(":")[0]), int(atom2.split(":")[0]), bond),
443
+ inputs=[atom1_select, atom2_select, bond_select, molecule_state],
444
+ outputs=molecule_state
445
+ ).then(
446
+ fn=update_bonds_list,
447
+ inputs=molecule_state,
448
+ outputs=bonds_list
449
+ )
450
+
451
+ clear_btn.click(
452
+ fn=init_molecule,
453
+ outputs=molecule_state
454
+ ).then(
455
+ fn=lambda: [[], []],
456
+ outputs=[atoms_list, bonds_list]
457
+ ).then(
458
+ fn=lambda: (gr.Dropdown.update(choices=[]), gr.Dropdown.update(choices=[])),
459
+ outputs=[atom1_select, atom2_select]
460
+ )
461
+
462
+ generate_btn.click(
463
+ fn=generate_smiles,
464
+ inputs=molecule_state,
465
+ outputs=molecule_smiles
466
+ ).then(
467
+ fn=visualize_molecule,
468
+ inputs=molecule_state,
469
+ outputs=molecule_img
470
+ )
471
+
472
  # 设置交互
473
  # SMILES输入路径
474
  submit_btn1.click(
 
480
  # 分子构建预测路径
481
  submit_btn2.click(
482
  fn=lambda smiles: predict_all(smiles) if smiles else ("请输入有效的SMILES", None, "", None, "", None),
483
+ inputs=molecule_smiles,
484
  outputs=[elastic_text, elastic_img, plastic_text, plastic_img, brittle_text, brittle_img]
485
  )
486