Spaces:
Sleeping

Materealize / app.py
jaehwanchoi's picture
Publish the final 100 candidates with CIFs and synthesis reports
28b51ff verified
Raw History Blame Contribute Delete
7.34 kB
"""Materealize: browse the 100 published candidates and their saved reports."""
from pathlib import Path
import os
import random
from tempfile import TemporaryDirectory
import gradio as gr
from catalogue import ARCHIVE, CONDITIONED, GENERATION_COUNTS, TARGET_COUNTS, UNCONDITIONAL, load_catalogue
ROOT = Path(__file__).resolve().parent
PUBLIC_CACHE = TemporaryDirectory(prefix='materealize-final-')
ENTRIES = load_catalogue(ROOT / 'data', Path(PUBLIC_CACHE.name))
ALL = 'all'
ARCHIVE_URL = f'https://huggingface.co/spaces/SNU-MICC/Materealize/resolve/main/data/{ARCHIVE}?download=true'
def group_ids(mode, target):
return [c.id for c in ENTRIES.values() if c.generation == mode
and (mode == UNCONDITIONAL or target == ALL or str(c.target) == target)]
def choices(ids):
result = []
for entry_id in ids:
c = ENTRIES[entry_id]
label = f'{c.id} | {c.formula}'
if c.generation == CONDITIONED:
label += f' | {c.predicted:.3f} eV'
result.append((label, c.id))
return result
def preview_cards(ids):
return [(str(ENTRIES[k].file('preview.png')), f'{ENTRIES[k].number} | {ENTRIES[k].formula}') for k in ids]
def detail(entry_id):
c = ENTRIES[entry_id]
cif, report = c.file('structure.cif'), c.file('synthesis_report.txt')
heading = f'### {c.formula}\n\n`{c.id}`'
if c.generation == CONDITIONED:
heading += (f'   路   Target: {c.target} eV'
f'   路   Predicted: **{c.predicted:.3f} eV**')
else:
heading += '   路   Unconditional'
return (heading, report.read_bytes().decode('utf-8'), cif.read_bytes().decode('utf-8'),
str(c.file('preview.png')), str(report), str(cif))
def select_target(mode, target):
ids = group_ids(mode, target)
if not ids:
return (gr.skip(),) * (3 + len(details))
return (ids[:5], gr.update(value=preview_cards(ids[:5]), selected_index=None),
gr.update(choices=choices(ids), value=ids[0]), *detail(ids[0]))
def select_mode(mode):
return (gr.update(visible=mode == CONDITIONED, value=ALL), *select_target(mode, ALL))
def refresh_previews(mode, target):
group = group_ids(mode, target)
ids = sorted(random.sample(group, min(5, len(group))))
return ids, gr.update(value=preview_cards(ids), selected_index=None)
def select_material(mode, target, entry_id):
if entry_id not in group_ids(mode, target):
return (gr.skip(),) * len(details)
return detail(entry_id)
def select_card(mode, target, ids, event: gr.SelectData):
if not isinstance(event.index, int) or not 0 <= event.index < len(ids):
return (gr.skip(),) * (1 + len(details))
entry_id = ids[event.index]
if entry_id not in group_ids(mode, target):
return (gr.skip(),) * (1 + len(details))
return entry_id, *detail(entry_id)
initial_group = group_ids(CONDITIONED, ALL)
initial_ids = initial_group[:5]
initial = detail(initial_ids[0])
TEXT = dict(interactive=False, autoscroll=False, show_copy_button=True, show_label=False, lines=15, max_lines=24)
CSS = """
#candidate-previews .grid-wrap { min-height: 0; max-height: none; height: auto; overflow: visible; }
#candidate-previews .grid-container {
grid-template-columns: repeat(5, minmax(0, 1fr)); grid-template-rows: none; grid-auto-rows: 146px;
}
#candidate-previews .thumbnail-item { aspect-ratio: auto; }
#candidate-previews .thumbnail-item img { box-sizing: border-box; padding-bottom: 22px; }
#candidate-previews .caption-label { max-width: 100%; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
@media (max-width: 640px) {
#candidate-previews .grid-container { grid-template-columns: repeat(3, minmax(0, 1fr)); grid-auto-rows: 106px; }
#candidate-previews .caption-label { font-size: 11px; }
}
"""
with gr.Blocks(title='Materealize', theme=gr.themes.Base(), css=CSS, analytics_enabled=False) as demo:
gr.Image(str(ROOT / 'logo.png'), label='Materealize', show_label=False, container=False,
height=75, interactive=False, show_download_button=False, show_fullscreen_button=False)
gr.Markdown('**Materealize | Synthesis candidate explorer** &nbsp; 路 &nbsp; 100 candidates\n\n'
'These are precomputed predictions for hypothetical structures, not experimentally validated syntheses.')
gr.Markdown('### 1. Candidate structures')
preview_ids = gr.State(initial_ids)
mode = gr.Radio([(f'Bandgap-conditioned ({GENERATION_COUNTS[CONDITIONED]})', CONDITIONED),
(f'Unconditional ({GENERATION_COUNTS[UNCONDITIONAL]})', UNCONDITIONAL)],
value=CONDITIONED, label='Generation mode', interactive=True)
with gr.Row():
target = gr.Dropdown([('All target bandgaps', ALL)] + [(f'{k} eV ({n})', k) for k, n in TARGET_COUNTS.items()],
value=ALL, label='Target bandgap', interactive=True, scale=3)
refresh = gr.Button('Show another five structures', scale=1)
gallery = gr.Gallery(value=preview_cards(initial_ids), label='Crystal structures', columns=5, elem_id='candidate-previews',
rows=1, height='auto', object_fit='contain', allow_preview=False, interactive=False,
show_share_button=False, show_fullscreen_button=False, show_download_button=False, format='png')
gr.Markdown('### 2. Candidate details')
material = gr.Dropdown(choices(initial_group), value=initial_ids[0], label='Candidate',
filterable=True, interactive=True)
title = gr.Markdown(initial[0])
with gr.Tabs():
with gr.Tab('Synthesis report'):
report = gr.Textbox(initial[1], label='Synthesis report', **TEXT)
report_file = gr.DownloadButton('Download synthesis report (.txt)', value=initial[4], size='sm')
with gr.Tab('Crystal structure'):
with gr.Row():
image = gr.Image(initial[3], label='Projection of the candidate CIF', height=260,
interactive=False, show_download_button=False, scale=1, format='png')
cif = gr.Textbox(initial[2], label='Original CIF', scale=2, **TEXT)
cif_file = gr.DownloadButton('Download structure (.cif)', value=initial[5], size='sm')
details = [title, report, cif, image, report_file, cif_file]
selection = [preview_ids, gallery, material, *details]
mode.input(select_mode, mode, [target, *selection], api_name=False)
target.input(select_target, [mode, target], selection, api_name=False)
refresh.click(refresh_previews, [mode, target], [preview_ids, gallery], api_name=False)
material.input(select_material, [mode, target, material], details, api_name='candidate')
gallery.select(select_card, [mode, target, preview_ids], [material, *details], api_name=False)
gr.Markdown(f'[Download all 100 candidates (.zip)]({ARCHIVE_URL}) 路 [SNU MICC](https://micc.snu.ac.kr)')
if __name__ == '__main__':
host = os.getenv('SPACE_HOST')
if not host and os.getenv('SPACE_ID') == 'SNU-MICC/Materealize':
host = 'snu-micc-materealize.hf.space'
origin = f'https://{host}' if host and host.endswith('.hf.space') else None
demo.launch(show_api=False, allowed_paths=[PUBLIC_CACHE.name], root_path=origin, ssr_mode=False)