Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -53,19 +53,36 @@ def mol_img(smiles, size=(160,160)):
|
|
| 53 |
|
| 54 |
### 支援多格式匯入
|
| 55 |
def load_table(file):
|
| 56 |
-
|
| 57 |
-
if
|
| 58 |
-
return pd.
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 62 |
else:
|
| 63 |
-
|
| 64 |
-
pos = file.tell() if hasattr(file, "tell") else 0
|
| 65 |
-
raw = file.read(4096)
|
| 66 |
-
enc = chardet.detect(raw)["encoding"] or "utf-8"
|
| 67 |
-
file.seek(pos)
|
| 68 |
-
return pd.read_csv(file, encoding=enc)
|
| 69 |
|
| 70 |
def smiles_to_mol(smiles):
|
| 71 |
try:
|
|
@@ -75,13 +92,10 @@ def smiles_to_mol(smiles):
|
|
| 75 |
|
| 76 |
### 批量分子圖
|
| 77 |
def batch_mol_imgs(smiles_list):
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
n = len(imgs)
|
| 83 |
-
grid = Draw.MolsToGridImage([smiles_to_mol(s) for s in smiles_list[:25] if smiles_to_mol(s)],
|
| 84 |
-
molsPerRow=5, subImgSize=(160, 160))
|
| 85 |
buf = io.BytesIO()
|
| 86 |
grid.save(buf, format='PNG')
|
| 87 |
buf.seek(0)
|
|
|
|
| 53 |
|
| 54 |
### 支援多格式匯入
|
| 55 |
def load_table(file):
|
| 56 |
+
# 允許 file 為 None, gradio.NamedString, gradio.TempFile, file-like, 或字串路徑
|
| 57 |
+
if file is None:
|
| 58 |
+
return pd.DataFrame()
|
| 59 |
+
# 若是字串(Gradio新版直接給路徑字串)
|
| 60 |
+
if isinstance(file, str):
|
| 61 |
+
# 根據副檔名選擇讀取方式
|
| 62 |
+
if file.endswith('.csv'):
|
| 63 |
+
return pd.read_csv(file)
|
| 64 |
+
elif file.endswith(('.xls', '.xlsx')):
|
| 65 |
+
return pd.read_excel(file, engine="openpyxl")
|
| 66 |
+
elif file.endswith('.sdf'):
|
| 67 |
+
return PandasTools.LoadSDF(file)
|
| 68 |
+
else:
|
| 69 |
+
raise RuntimeError(f"不支援的檔案格式: {file}")
|
| 70 |
+
# 若是有 .name 屬性(TempFile, NamedString)
|
| 71 |
+
elif hasattr(file, "name"):
|
| 72 |
+
fname = file.name
|
| 73 |
+
if fname.endswith('.csv'):
|
| 74 |
+
return pd.read_csv(fname)
|
| 75 |
+
elif fname.endswith(('.xls', '.xlsx')):
|
| 76 |
+
return pd.read_excel(fname, engine="openpyxl")
|
| 77 |
+
elif fname.endswith('.sdf'):
|
| 78 |
+
return PandasTools.LoadSDF(fname)
|
| 79 |
+
else:
|
| 80 |
+
raise RuntimeError(f"不支援的檔案格式: {fname}")
|
| 81 |
+
# 若是有 read 方法的 file-like(極少見)
|
| 82 |
+
elif hasattr(file, "read"):
|
| 83 |
+
return pd.read_csv(file)
|
| 84 |
else:
|
| 85 |
+
raise RuntimeError("未知檔案型態")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 86 |
|
| 87 |
def smiles_to_mol(smiles):
|
| 88 |
try:
|
|
|
|
| 92 |
|
| 93 |
### 批量分子圖
|
| 94 |
def batch_mol_imgs(smiles_list):
|
| 95 |
+
mols = [Chem.MolFromSmiles(s) for s in smiles_list[:25] if Chem.MolFromSmiles(s)]
|
| 96 |
+
if len(mols)==0:
|
| 97 |
+
return Image.new("RGB", (800, 160), (255,255,255))
|
| 98 |
+
grid = Draw.MolsToGridImage(mols, molsPerRow=5, subImgSize=(160,160))
|
|
|
|
|
|
|
|
|
|
| 99 |
buf = io.BytesIO()
|
| 100 |
grid.save(buf, format='PNG')
|
| 101 |
buf.seek(0)
|