Spaces:
Sleeping
Sleeping
Download app.py from Bingdo/process_parameter: direct link, hf CLI and curl.
- Browser
- Download file 57.9 kB
-
https://huggingface.co/spaces/Bingdo/process_parameter/resolve/main/app.py
- Command line
-
hf download hf://spaces/Bingdo/process_parameter/app.py
-
curl -L -o app.py https://huggingface.co/spaces/Bingdo/process_parameter/resolve/main/app.py
57.9 kB
"""
Material Process Parameters - Report Viewer
Read-only viewer for pre-generated synthesis parameter reports.
Deployed on Hugging Face Spaces: Bingdo/process_parameter
"""
import streamlit as st
import json
import re
from pathlib import Path
from datetime import datetime
from typing import Optional, Dict, Any
from urllib.parse import urlparse
# --- Configuration ---
OUTPUT_DIR = "reports"
# --- Page Configuration ---
st.set_page_config(
page_title="Material Process Parameters",
page_icon="π¬",
layout="wide",
initial_sidebar_state="expanded"
)
# --- Custom CSS ---
st.markdown("""
<style>
.main-header {
font-size: 2.5rem;
font-weight: 700;
color: #1f77b4;
margin-bottom: 0.5rem;
}
.sub-header {
font-size: 1.2rem;
color: #666;
margin-bottom: 2rem;
}
.metric-card {
background-color: #ffffff;
border-radius: 10px;
padding: 1rem;
box-shadow: 0 2px 4px rgba(0,0,0,0.1);
text-align: center;
}
.stTabs [data-baseweb="tab-list"] {
gap: 8px;
}
.stTabs [data-baseweb="tab"] {
padding: 10px 20px;
}
</style>
""", unsafe_allow_html=True)
# --- Report Loading Functions ---
def scan_existing_reports(output_dir: str) -> list:
"""Scan output directory for existing report folders."""
output_path = Path(output_dir)
if not output_path.exists():
return []
reports = []
for folder in sorted(output_path.iterdir(), reverse=True):
if folder.is_dir() and not folder.name.startswith('.'):
final_output = folder / "07_final_output.json"
if final_output.exists():
folder_name = folder.name
# Detect backend type from folder name
is_adk = folder_name.endswith('_adk')
backend_label = "Gemini" if is_adk else "OpenAI"
backend_icon = "β¨" if is_adk else "π€"
# Strip _adk suffix for parsing
parse_name = folder_name[:-4] if is_adk else folder_name
# Extract material name and timestamp from folder name
parts = parse_name.rsplit('_', 2)
if len(parts) >= 3:
material_name = parts[0].replace('_', ' ').title()
date_str = parts[1]
time_str = parts[2]
try:
timestamp = datetime.strptime(f"{date_str}_{time_str}", "%Y%m%d_%H%M%S")
display_time = timestamp.strftime("%Y-%m-%d %H:%M")
except ValueError:
display_time = folder_name
else:
material_name = folder_name
display_time = ""
reports.append({
'folder': str(folder),
'folder_name': folder_name,
'material': material_name,
'timestamp': display_time,
'backend': 'gemini_adk' if is_adk else 'openai',
'backend_label': backend_label,
'backend_icon': backend_icon,
'display': f"{backend_icon} {material_name} ({display_time}) [{backend_label}]" if display_time else f"{backend_icon} {material_name} [{backend_label}]"
})
return reports
def load_report_from_folder(folder_path: str) -> Optional[Dict]:
"""Load report from a session folder and transform to expected format."""
folder = Path(folder_path)
final_output_path = folder / "07_final_output.json"
if not final_output_path.exists():
return None
try:
with open(final_output_path, 'r') as f:
data = json.load(f)
# Handle comparison_matrices (may be nested dict or direct list)
comparison_data = data.get('comparison_matrices', {})
if isinstance(comparison_data, dict):
comparison_obj = comparison_data
elif isinstance(comparison_data, list):
comparison_obj = {'comparison_matrices': comparison_data}
else:
comparison_obj = {'comparison_matrices': []}
# Load parameter extraction data
param_data = data.get('parameter_data', {})
# Load from 03_experiment_extraction folder if exists (Gemini ADK format)
experiment_folder = folder / "03_experiment_extraction"
if experiment_folder.exists() and experiment_folder.is_dir():
for exp_file in experiment_folder.glob("*_experiments.json"):
try:
with open(exp_file, 'r') as f:
exp_data = json.load(f)
method_name = exp_data.get('method_name', exp_file.stem.replace('_experiments', ''))
param_data[method_name] = exp_data
except (json.JSONDecodeError, IOError):
pass
# Load references.json for full reference data
references_path = folder / "references.json"
all_references = []
url_to_ref_id = {}
if references_path.exists():
try:
with open(references_path, 'r') as f:
refs_data = json.load(f)
all_references = refs_data.get('sources', [])
for ref in all_references:
ref_id = ref.get('id', '')
ref_url = ref.get('url', '')
if ref_id and ref_url:
url_to_ref_id[ref_url] = ref_id
url_to_ref_id[ref_url.rstrip('/')] = ref_id
except (json.JSONDecodeError, IOError):
pass
# Transform to the format expected by render functions
results = {
'method_taxonomy': {
'methods': data.get('synthesis_methods', [])
},
'parameter_extraction': param_data,
'research_teams': {
'team_registry': data.get('research_teams', {})
},
'parameter_comparison': comparison_obj,
'data_gaps': data.get('data_gaps', {}),
'final_output': {
'markdown_report': data.get('markdown_report', ''),
'references': data.get('references', []),
'material': data.get('material', {}),
},
'all_references': all_references,
'_url_to_ref_id': url_to_ref_id,
}
# Handle research_teams if it's already in the right format
if isinstance(data.get('research_teams'), dict):
if 'teams' in data['research_teams']:
results['research_teams']['team_registry'] = data['research_teams']
elif 'team_registry' in data['research_teams']:
results['research_teams'] = data['research_teams']
# Build reference lookup dict from the references array (by ID)
ref_lookup = {ref.get('id'): ref for ref in all_references if ref.get('id')}
if not ref_lookup:
references = data.get('references', [])
ref_lookup = {ref.get('id'): ref for ref in references if ref.get('id')}
results['_ref_lookup'] = ref_lookup
return results
except (json.JSONDecodeError, IOError) as e:
st.error(f"Error loading report: {e}")
return None
# --- Helper Functions ---
def parse_raw_output(raw_output: str) -> list:
"""Parse raw_output field that may contain markdown-wrapped JSON."""
if not raw_output:
return []
try:
text = raw_output.strip()
text = re.sub(r'^```(?:json)?\s*\n?', '', text)
text = re.sub(r'\n?```\s*$', '', text)
text = text.strip()
text = re.sub(r'([\]\}"])\s+//[^\n]*', r'\1', text)
text = re.sub(r'^\s*//[^\n]*\n', '', text, flags=re.MULTILINE)
json_match = re.search(r'[\[\{][\s\S]*[\]\}]', text)
if json_match:
parsed = json.loads(json_match.group())
if isinstance(parsed, list):
return parsed
elif isinstance(parsed, dict) and 'parameters' in parsed:
return parsed.get('parameters', [])
except (json.JSONDecodeError, Exception):
pass
return []
def parse_raw_output_dict(raw_output: str) -> dict:
"""Parse raw_output field that may contain markdown-wrapped JSON dict."""
if not raw_output:
return {}
try:
text = raw_output.strip()
text = re.sub(r'^```(?:json)?\s*\n?', '', text)
text = re.sub(r'\n?```\s*$', '', text)
text = text.strip()
text = re.sub(r'([\]\}"])\s+//[^\n]*', r'\1', text)
text = re.sub(r'^\s*//[^\n]*\n', '', text, flags=re.MULTILINE)
json_match = re.search(r'\{[\s\S]*\}', text)
if json_match:
parsed = json.loads(json_match.group())
if isinstance(parsed, dict):
return parsed
except (json.JSONDecodeError, Exception):
pass
return {}
def get_ref_lookup(results: Dict) -> dict:
"""Extract reference lookup dict from results."""
ref_lookup = results.get('_ref_lookup', {})
if ref_lookup:
return ref_lookup
references = results.get('final_output', {}).get('references', [])
if references:
return {ref.get('id'): ref for ref in references if ref.get('id')}
return {}
def format_source_link(source_id: str, ref_lookup: dict) -> str:
"""Format a source ID as a clickable HTML link."""
if not source_id or source_id == 'N/A':
return source_id
ref = ref_lookup.get(source_id)
if ref and ref.get('url'):
return f'<a href="{ref["url"]}" target="_blank">{source_id}</a>'
return source_id
# --- Render Functions ---
def render_results_summary(results: Dict):
"""Render summary metrics."""
col1, col2, col3, col4 = st.columns(4)
methods = results.get('method_taxonomy', {}).get('methods', [])
with col1:
st.metric("Synthesis Methods", len(methods))
team_registry = results.get('research_teams', {}).get('team_registry', {})
teams = team_registry.get('teams', [])
if not teams and 'raw_output' in team_registry:
parsed_registry = parse_raw_output_dict(team_registry['raw_output'])
teams = parsed_registry.get('teams', [])
with col2:
st.metric("Research Teams", len(teams))
# Count experiments for ADK format
param_data = results.get('parameter_extraction', {})
total_experiments = 0
for method_data in param_data.values():
if isinstance(method_data, dict):
experiments = method_data.get('experiments', [])
if experiments:
total_experiments += len(experiments)
else:
total_experiments += len(method_data.get('parameters', []))
with col3:
st.metric("Experiments/Params", total_experiments)
refs = results.get('all_references', []) or results.get('final_output', {}).get('references', [])
with col4:
st.metric("References", len(refs))
def render_methods_tab(results: Dict):
"""Render the synthesis methods tab."""
methods = results.get('method_taxonomy', {}).get('methods', [])
ref_lookup = get_ref_lookup(results)
if not methods:
st.info("No synthesis methods found.")
return
st.markdown(f"### Found {len(methods)} Synthesis Methods")
categories = {}
for method in methods:
cat = method.get('method_category', 'other')
if cat not in categories:
categories[cat] = []
categories[cat].append(method)
for category, cat_methods in categories.items():
with st.expander(f"**{category.replace('-', ' ').title()}** ({len(cat_methods)} methods)", expanded=True):
for method in cat_methods:
col1, col2 = st.columns([1, 2])
with col1:
st.markdown(f"**{method.get('method_name', 'Unknown')}**")
with col2:
variants = method.get('sub_variants', [])
if variants:
st.caption(f"Variants: {', '.join(variants)}")
# Show typical parameters if available
typical_params = method.get('typical_parameters', '')
if typical_params:
st.caption(typical_params)
sources = method.get('source_ids', [])
if sources:
source_links = [format_source_link(s, ref_lookup) for s in sources[:5]]
sources_html = f'<small style="color: #666;">Sources: {", ".join(source_links)}</small>'
st.markdown(sources_html, unsafe_allow_html=True)
def render_experiments_adk_format(method_data: Dict, ref_lookup: dict, url_to_ref_id: dict = None):
"""Render experiments in Gemini ADK format with experiments array."""
method_name = method_data.get('method_name', 'Unknown Method')
experiments = method_data.get('experiments', [])
parameter_summary = method_data.get('parameter_summary', {})
sources_used = method_data.get('sources_used', [])
extraction_stats = method_data.get('extraction_stats', {})
url_to_ref_id = url_to_ref_id or {}
# Summary metrics
col1, col2, col3, col4 = st.columns(4)
with col1:
st.metric("Experiments", len(experiments))
with col2:
st.metric("Sources", len(sources_used))
with col3:
total_params = sum(len(exp.get('parameters', {})) for exp in experiments)
st.metric("Parameters", total_params)
with col4:
status = method_data.get('extraction_status', 'unknown')
status_icon = "β
" if status == 'success' else "β οΈ"
st.metric("Status", f"{status_icon} {status.title()}")
# Extraction stats
if extraction_stats:
with st.expander("π Extraction Statistics", expanded=False):
stats_cols = st.columns(4)
methods = extraction_stats.get('extraction_methods', {})
with stats_cols[0]:
st.metric("PDF", methods.get('pdf', 0))
with stats_cols[1]:
st.metric("Tavily", methods.get('tavily', 0))
with stats_cols[2]:
st.metric("Crawl4AI", methods.get('crawl4ai', 0))
with stats_cols[3]:
st.metric("Snippet", methods.get('scholar_snippet', 0))
st.markdown("---")
# Parameter Summary
if parameter_summary:
with st.expander("π Parameter Summary", expanded=True):
summary_items = []
for key, value in parameter_summary.items():
if isinstance(value, list):
value = ", ".join(str(v) for v in value)
summary_items.append({
"Parameter": key.replace('_', ' ').title(),
"Value": str(value)
})
if summary_items:
st.dataframe(
summary_items,
hide_index=True,
use_container_width=True,
column_config={
'Parameter': st.column_config.TextColumn('Parameter', width='medium'),
'Value': st.column_config.TextColumn('Value', width='large'),
}
)
# Individual Experiments
st.markdown("### Experiments")
for idx, exp in enumerate(experiments):
exp_id = exp.get('experiment_id', f'Experiment {idx + 1}')
description = exp.get('description', '')
with st.expander(f"π§ͺ **{exp_id}**", expanded=idx < 3):
# Description
if description:
st.info(description)
# Two column layout for parameters and precursors
col1, col2 = st.columns(2)
# Parameters
params = exp.get('parameters', {})
with col1:
if params:
st.markdown("**π Parameters:**")
param_table = []
for param_name, param_value in params.items():
value_str = str(param_value)
param_table.append({
"Parameter": param_name.replace('_', ' ').title(),
"Value": value_str
})
st.dataframe(
param_table,
hide_index=True,
use_container_width=True,
column_config={
'Parameter': st.column_config.TextColumn('Parameter', width='medium'),
'Value': st.column_config.TextColumn('Value', width='medium'),
}
)
# Precursors
precursors = exp.get('precursors', [])
with col2:
if precursors:
st.markdown("**π§ͺ Precursors:**")
for p in precursors:
st.markdown(f"β’ {p}")
# Conditions
conditions = exp.get('conditions', {})
if conditions:
with st.container(border=True):
st.markdown("**βοΈ Conditions:**")
cond_cols = st.columns(2)
cond_items = list(conditions.items())
for i, (k, v) in enumerate(cond_items):
key_name = k.replace('_', ' ').title()
if isinstance(v, list):
v_str = ", ".join(str(item) for item in v)
else:
v_str = str(v)
with cond_cols[i % 2]:
st.markdown(f"**{key_name}:** {v_str}")
# Source URL(s)
source_url = exp.get('source_url', '')
source_urls = exp.get('source_urls', [])
all_urls = []
if source_url:
all_urls.append(source_url)
if source_urls:
all_urls.extend(source_urls)
if all_urls:
ref_links = []
for url in all_urls:
ref_id = url_to_ref_id.get(url) or url_to_ref_id.get(url.rstrip('/'))
if ref_id:
ref_links.append(f"[{ref_id}]({url})")
else:
try:
domain = urlparse(url).netloc
ref_links.append(f"[{domain}]({url})")
except:
ref_links.append(f"[Link]({url})")
st.markdown(f"**π Source:** {' | '.join(ref_links)}")
# All Sources Used
if sources_used:
with st.expander(f"π All Sources ({len(sources_used)})", expanded=False):
for url in sources_used:
ref_id = url_to_ref_id.get(url) or url_to_ref_id.get(url.rstrip('/'))
if ref_id:
ref_info = ref_lookup.get(ref_id, {})
title = ref_info.get('title', '')
year = ref_info.get('year', '')
display_title = f" - {title}" if title else ""
display_year = f" ({year})" if year else ""
st.markdown(f"- **[{ref_id}]({url})**{display_title}{display_year}")
else:
try:
domain = urlparse(url).netloc
st.markdown(f"- [{domain}]({url})")
except:
st.markdown(f"- [Link]({url})")
def render_param_table_with_links(param_table: list, ref_lookup: dict):
"""Render parameter table with clickable source links as HTML."""
if not param_table:
return
html = '''<table style="width:100%; border-collapse: collapse; margin: 1rem 0;">
<thead>
<tr style="background-color: #f0f2f6; border-bottom: 2px solid #ddd;">
<th style="padding: 8px; text-align: left;">Parameter</th>
<th style="padding: 8px; text-align: left;">Value</th>
<th style="padding: 8px; text-align: left;">Unit</th>
<th style="padding: 8px; text-align: left;">Source</th>
<th style="padding: 8px; text-align: left;">Context</th>
</tr>
</thead>
<tbody>'''
for row in param_table:
source_id = row.get('Source', 'N/A')
source_html = format_source_link(source_id, ref_lookup)
param_name = str(row.get('Parameter', '')).replace('<', '<').replace('>', '>')
value = str(row.get('Value', '')).replace('<', '<').replace('>', '>')
unit = str(row.get('Unit', '')).replace('<', '<').replace('>', '>')
context = str(row.get('Context', '')).replace('<', '<').replace('>', '>')
html += f'''
<tr style="border-bottom: 1px solid #eee;">
<td style="padding: 8px;">{param_name}</td>
<td style="padding: 8px;">{value}</td>
<td style="padding: 8px;">{unit}</td>
<td style="padding: 8px;">{source_html}</td>
<td style="padding: 8px;">{context}</td>
</tr>'''
html += '</tbody></table>'
st.markdown(html, unsafe_allow_html=True)
def render_params_grouped_by_source(params_by_source: dict, ref_lookup: dict):
"""Render parameters grouped by source with visual distinction."""
colors = [
('#e3f2fd', '#1565c0', 'blue'),
('#f3e5f5', '#7b1fa2', 'violet'),
('#e8f5e9', '#2e7d32', 'green'),
('#fff3e0', '#e65100', 'orange'),
('#fce4ec', '#c2185b', 'red'),
('#e0f7fa', '#00838f', 'gray'),
]
for idx, (source_id, params) in enumerate(params_by_source.items()):
bg_color, border_color, st_color = colors[idx % len(colors)]
ref = ref_lookup.get(source_id, {})
ref_title = ref.get('title', '')
ref_url = ref.get('url', '')
param_count = len(params)
expander_title = f"π {source_id} β {param_count} parameters"
with st.expander(expander_title, expanded=True):
if ref_url:
st.markdown(f"**Source:** [{source_id}]({ref_url})", unsafe_allow_html=True)
else:
st.markdown(f"**Source:** {source_id}")
if ref_title:
st.caption(ref_title[:150] + ('...' if len(ref_title) > 150 else ''))
table_rows = []
for param in params:
table_rows.append({
'Parameter': param.get('Parameter', ''),
'Value': param.get('Value', ''),
'Unit': param.get('Unit', ''),
'Context': param.get('Context', ''),
})
st.dataframe(
table_rows,
use_container_width=True,
hide_index=True,
column_config={
'Parameter': st.column_config.TextColumn('Parameter', width='medium'),
'Value': st.column_config.TextColumn('Value', width='small'),
'Unit': st.column_config.TextColumn('Unit', width='small'),
'Context': st.column_config.TextColumn('Context', width='large'),
}
)
def render_parameters_tab(results: Dict):
"""Render the parameters tab."""
param_data = results.get('parameter_extraction', {})
ref_lookup = get_ref_lookup(results)
url_to_ref_id = results.get('_url_to_ref_id', {})
if not param_data:
st.info("No parameters extracted.")
return
st.markdown("### Process Parameters by Method")
method_select = st.selectbox(
"Select Method",
options=list(param_data.keys()),
key="param_method_select"
)
if method_select:
method_params = param_data.get(method_select, {})
# Check for Gemini ADK format (has 'experiments' array)
experiments = method_params.get('experiments', [])
if experiments:
render_experiments_adk_format(method_params, ref_lookup, url_to_ref_id)
return
# Legacy format
params = method_params.get('parameters', [])
if not params and 'raw_output' in method_params:
params = parse_raw_output(method_params['raw_output'])
if params:
sample_param = params[0] if params else {}
is_new_format = 'source_urls' in sample_param or 'evidence_snippets' in sample_param or 'consensus_level' in sample_param
if is_new_format:
render_params_new_format(params, method_params.get('method_name', method_select), ref_lookup)
else:
params_by_source = {}
for entry in params if isinstance(params, list) else []:
if isinstance(entry, dict):
nested_params = entry.get('parameters', [])
source_id = entry.get('source_id', 'N/A')
if nested_params and isinstance(nested_params, list):
for p in nested_params:
if isinstance(p, dict):
src = p.get('source_id', source_id)
if src not in params_by_source:
params_by_source[src] = []
params_by_source[src].append({
"Parameter": p.get('parameter_name', p.get('parameter_type', 'Unknown')),
"Value": p.get('value', 'N/A'),
"Unit": p.get('unit', ''),
"Context": p.get('context', '')[:80] + '...' if len(p.get('context', '')) > 80 else p.get('context', ''),
})
else:
src = entry.get('source_id', 'N/A')
if src not in params_by_source:
params_by_source[src] = []
params_by_source[src].append({
"Parameter": entry.get('parameter_name', entry.get('parameter_type', 'Unknown')),
"Value": entry.get('value', 'N/A'),
"Unit": entry.get('unit', ''),
"Context": entry.get('context', '')[:80] + '...' if len(entry.get('context', '')) > 80 else entry.get('context', ''),
})
if params_by_source:
st.markdown(f"**{len(params_by_source)} sources** with **{sum(len(p) for p in params_by_source.values())} parameters** extracted")
st.markdown("---")
render_params_grouped_by_source(params_by_source, ref_lookup)
else:
st.json(method_params)
else:
st.json(method_params)
def render_params_new_format(params: list, method_name: str, ref_lookup: dict):
"""Render parameters in the new format with source_urls, evidence_snippets, etc."""
params_by_type = {}
for param in params:
param_type = param.get('parameter_type', 'other')
if param_type not in params_by_type:
params_by_type[param_type] = []
params_by_type[param_type].append(param)
total_params = len(params)
all_sources = set()
for p in params:
for url in p.get('source_urls', []):
all_sources.add(url)
col1, col2, col3 = st.columns(3)
with col1:
st.metric("Total Parameters", total_params)
with col2:
st.metric("Parameter Types", len(params_by_type))
with col3:
st.metric("Unique Sources", len(all_sources))
st.markdown("---")
type_icons = {
'temperature': 'π‘οΈ',
'pressure': 'π',
'voltage': 'β‘',
'current': 'π',
'time': 'β±οΈ',
'composition': 'π§ͺ',
'flow_rate': 'π¨',
'power': 'πͺ',
'other': 'π',
}
for param_type, type_params in params_by_type.items():
icon = type_icons.get(param_type, 'π')
with st.expander(f"{icon} **{param_type.replace('_', ' ').title()}** ({len(type_params)} parameters)", expanded=True):
for param in type_params:
render_single_param_card(param, ref_lookup)
def render_single_param_card(param: dict, ref_lookup: dict):
"""Render a single parameter as a styled card."""
name = param.get('name', param.get('parameter_type', 'Unknown'))
value = param.get('value', 'N/A')
unit = param.get('unit', '')
conditions = param.get('conditions', '')
confidence = param.get('confidence', 0)
consensus_level = param.get('consensus_level', 'unknown')
value_range = param.get('value_range', {})
evidence_snippets = param.get('evidence_snippets', [])
source_urls = param.get('source_urls', [])
with st.container(border=True):
col_name, col_badges = st.columns([3, 1])
with col_name:
st.markdown(f"**{name}**")
with col_badges:
if consensus_level == 'multiple_agree':
st.success("Multiple Agree", icon="β
")
elif consensus_level == 'conflicting':
st.error("Conflicting", icon="β οΈ")
else:
st.info("Single Source", icon="π")
col_val, col_conf = st.columns([3, 1])
with col_val:
st.markdown(f"### {value} {unit}")
with col_conf:
if confidence >= 0.9:
st.success(f"Conf: {confidence:.0%}")
elif confidence >= 0.7:
st.warning(f"Conf: {confidence:.0%}")
else:
st.error(f"Conf: {confidence:.0%}")
if value_range and value_range.get('min') and value_range.get('max'):
range_min = value_range.get('min', '')
range_max = value_range.get('max', '')
typical = value_range.get('typical', '')
if range_min != range_max:
range_text = f"**Range:** {range_min} - {range_max} {unit}"
if typical and typical != value:
range_text += f" | **Typical:** {typical} {unit}"
st.caption(range_text)
if conditions:
st.info(f"**Conditions:** {conditions}", icon="βΉοΈ")
if evidence_snippets or source_urls:
col_ev, col_src = st.columns(2)
with col_ev:
if evidence_snippets:
with st.popover("π Evidence Snippets"):
for snippet in evidence_snippets:
st.markdown(f"> *\"{snippet}\"*")
with col_src:
if source_urls:
with st.popover(f"π Sources ({len(source_urls)})"):
for url in source_urls:
try:
domain = urlparse(url).netloc
st.markdown(f"- [{domain}]({url})")
except:
st.markdown(f"- [Link]({url})")
def render_teams_tab(results: Dict):
"""Render the research teams tab."""
team_data = results.get('research_teams', {})
team_registry = team_data.get('team_registry', {})
teams = team_registry.get('teams', [])
ref_lookup = get_ref_lookup(results)
if not teams and 'raw_output' in team_registry:
parsed_registry = parse_raw_output_dict(team_registry['raw_output'])
teams = parsed_registry.get('teams', [])
if not team_registry.get('geographic_distribution'):
team_registry = parsed_registry
if not teams:
st.info("No research teams identified.")
return
st.markdown(f"### {len(teams)} Research Teams Identified")
geo_dist = team_registry.get('geographic_distribution', {})
if geo_dist:
st.markdown("#### Geographic Distribution")
cols = st.columns(min(len(geo_dist), 4))
for idx, (country, count) in enumerate(geo_dist.items()):
with cols[idx % 4]:
st.metric(country, count)
st.markdown("---")
for team in teams:
with st.expander(f"**{team.get('team_name', team.get('team_id', 'Unknown'))}** - {team.get('institution', 'N/A')}"):
col1, col2 = st.columns(2)
with col1:
st.markdown(f"**Country:** {team.get('country', 'N/A')}")
pis = team.get('principal_investigators', [])
if pis:
st.markdown(f"**PIs:** {', '.join(pis)}")
with col2:
methods = team.get('focus_methods', [])
if methods:
st.markdown(f"**Focus Methods:** {', '.join(methods)}")
papers = team.get('key_papers', [])
if papers:
paper_links = [format_source_link(p, ref_lookup) for p in papers[:5]]
st.markdown(f"**Key Papers:** {', '.join(paper_links)}", unsafe_allow_html=True)
contributions = team.get('notable_contributions', [])
if contributions:
st.markdown("**Notable Contributions:**")
for c in contributions:
st.markdown(f"- {c}")
def render_comparison_table_with_links(values: list, ref_lookup: dict):
"""Render comparison values table with clickable source links as HTML."""
if not values:
return
html = '''<table style="width:100%; border-collapse: collapse; margin: 0.5rem 0;">
<thead>
<tr style="background-color: #f0f2f6; border-bottom: 2px solid #ddd;">
<th style="padding: 8px; text-align: left;">Team</th>
<th style="padding: 8px; text-align: left;">Value</th>
<th style="padding: 8px; text-align: left;">Source</th>
<th style="padding: 8px; text-align: left;">Year</th>
<th style="padding: 8px; text-align: left;">Notes</th>
</tr>
</thead>
<tbody>'''
for v in values:
team = str(v.get('team_name', v.get('team_id', 'Unknown'))).replace('<', '<').replace('>', '>')
value = str(v.get('value', 'N/A')).replace('<', '<').replace('>', '>')
source_id = v.get('source_id', '')
source_html = format_source_link(source_id, ref_lookup)
year = str(v.get('year', '') or '').replace('<', '<').replace('>', '>')
notes = v.get('notes', '') or ''
notes_display = (notes[:80] + '...') if len(notes) > 80 else notes
notes_display = notes_display.replace('<', '<').replace('>', '>')
html += f'''
<tr style="border-bottom: 1px solid #eee;">
<td style="padding: 8px;">{team}</td>
<td style="padding: 8px;">{value}</td>
<td style="padding: 8px;">{source_html}</td>
<td style="padding: 8px;">{year}</td>
<td style="padding: 8px;">{notes_display}</td>
</tr>'''
html += '</tbody></table>'
st.markdown(html, unsafe_allow_html=True)
def render_comparison_tab(results: Dict):
"""Render the comparison matrices tab."""
comparison_data = results.get('parameter_comparison', {})
ref_lookup = get_ref_lookup(results)
if not comparison_data:
st.info("No comparison data available.")
return
st.markdown("### Cross-Team Parameter Comparison")
material_name = comparison_data.get('material_name') or comparison_data.get('material')
if material_name:
st.markdown(f"**Material:** {material_name}")
# Check for Gemini ADK format (has cross_team_comparison_matrices)
cross_team = comparison_data.get('cross_team_comparison_matrices', {})
if cross_team:
render_comparison_adk_format(comparison_data, ref_lookup)
return
# Legacy format handling
matrices = comparison_data.get('comparison_matrices', [])
if matrices:
for matrix in matrices:
if not isinstance(matrix, dict):
continue
method_name = matrix.get('method_name', 'Unknown Method')
method_category = matrix.get('method_category', '')
teams_compared = matrix.get('teams_compared', [])
with st.expander(f"**{method_name}** ({method_category})", expanded=True):
if teams_compared:
st.caption(f"Teams compared: {', '.join(teams_compared)}")
comparisons = matrix.get('parameter_comparisons', [])
if comparisons:
for comp in comparisons:
param_name = comp.get('parameter_name', 'Parameter')
param_type = comp.get('parameter_type', '')
st.markdown(f"#### {param_name}")
if param_type:
st.caption(f"Type: {param_type}")
values = comp.get('values_by_team', [])
if values:
render_comparison_table_with_links(values, ref_lookup)
consensus = comp.get('consensus_value')
if consensus:
if isinstance(consensus, dict):
consensus_val = consensus.get('consensus_value', str(consensus))
confidence = consensus.get('consensus_confidence', '')
sources = consensus.get('consensus_sources', [])
consensus_text = f"{consensus_val}"
if confidence:
consensus_text += f" (confidence: {confidence})"
if sources:
source_links = [format_source_link(s, ref_lookup) for s in sources]
st.markdown(f'<div style="padding: 1rem; background-color: #d4edda; border-radius: 0.25rem; margin: 0.5rem 0;"><strong>Consensus:</strong> {consensus_text} [Sources: {", ".join(source_links)}]</div>', unsafe_allow_html=True)
else:
st.success(f"Consensus: {consensus_text}")
else:
st.success(f"Consensus: {consensus}")
typical_range = comp.get('typical_range')
if typical_range:
st.info(f"Typical Range: {typical_range}")
st.markdown("---")
key_diffs = matrix.get('key_differences', [])
if key_diffs:
st.markdown("##### Key Differences")
for diff in key_diffs:
if isinstance(diff, str):
st.markdown(f"- {diff}")
elif isinstance(diff, dict):
diff_text = diff.get('difference', '')
st.markdown(f"**{diff_text}**")
best_practices = matrix.get('best_practices', [])
if best_practices:
st.markdown("##### Best Practices")
for bp in best_practices:
st.markdown(f"- {bp}")
else:
st.json(comparison_data)
def render_comparison_adk_format(comparison_data: Dict, ref_lookup: dict):
"""Render comparison matrices in Gemini ADK format."""
cross_team = comparison_data.get('cross_team_comparison_matrices', {})
insights = comparison_data.get('comparative_insights', {})
# Team Methodology Matrix
team_matrix = cross_team.get('team_methodology_matrix', [])
if team_matrix:
with st.expander("π₯ **Team Methodology Matrix**", expanded=True):
st.markdown("Overview of which synthesis methods each team specializes in:")
table_data = []
for team in team_matrix:
table_data.append({
"Team": team.get('team_name', 'Unknown'),
"HPHT": team.get('hpht_synthesis', '-'),
"CVD": team.get('cvd_synthesis', '-'),
"PVD": team.get('pvd_synthesis', '-'),
"Specialization": team.get('specialization', '-'),
})
st.dataframe(
table_data,
hide_index=True,
use_container_width=True,
column_config={
'Team': st.column_config.TextColumn('Team', width='medium'),
'HPHT': st.column_config.TextColumn('HPHT', width='small'),
'CVD': st.column_config.TextColumn('CVD', width='small'),
'PVD': st.column_config.TextColumn('PVD', width='small'),
'Specialization': st.column_config.TextColumn('Specialization', width='large'),
}
)
# HPHT Parameter Benchmarking
hpht_benchmark = cross_team.get('hpht_parameter_benchmarking', [])
if hpht_benchmark:
with st.expander("π¬ **HPHT Parameter Benchmarking**", expanded=True):
st.markdown("Comparison of HPHT synthesis parameters across experiments:")
table_data = []
for exp in hpht_benchmark:
pressure = exp.get('pressure_gpa', '-')
temp = exp.get('temperature_celsius', '-')
table_data.append({
"Experiment": exp.get('experiment_id', 'Unknown'),
"Team": exp.get('associated_team', '-'),
"Pressure (GPa)": str(pressure),
"Temp (Β°C)": str(temp),
"Precursor": exp.get('precursor_type', '-'),
"Outcome": exp.get('outcome', '-'),
})
st.dataframe(
table_data,
hide_index=True,
use_container_width=True,
)
# CVD Performance Matrix
cvd_matrix = cross_team.get('cvd_performance_matrix', [])
if cvd_matrix:
with st.expander("π¨ **CVD Performance Matrix**", expanded=True):
st.markdown("Comparison of CVD synthesis performance:")
table_data = []
for exp in cvd_matrix:
table_data.append({
"Team": exp.get('team_name', 'Unknown'),
"Experiment": exp.get('experiment_id', '-'),
"cBN Content": exp.get('cbn_content', '-'),
"Temp (Β°C)": str(exp.get('temperature_celsius', '-')),
"Crystal Size": exp.get('crystal_size', '-'),
"Precursors": exp.get('gas_precursors', '-'),
})
st.dataframe(
table_data,
hide_index=True,
use_container_width=True,
)
# Comparative Insights
if insights:
st.markdown("---")
st.markdown("### π Comparative Insights")
geo_leadership = insights.get('geographic_leadership', {})
if geo_leadership:
with st.expander("π **Geographic Leadership**", expanded=True):
for region, description in geo_leadership.items():
st.markdown(f"**{region}:** {description}")
tradeoffs = insights.get('technical_tradeoffs', {})
if tradeoffs:
with st.expander("βοΈ **Technical Tradeoffs**", expanded=True):
for tradeoff_name, description in tradeoffs.items():
st.info(f"**{tradeoff_name.replace('_', ' ').title()}:** {description}")
research_gaps = insights.get('research_gaps_identified', [])
if research_gaps:
with st.expander("π **Research Gaps Identified**", expanded=True):
for gap in research_gaps:
st.warning(gap)
def render_gaps_tab(results: Dict):
"""Render the data gaps tab."""
gap_data = results.get('data_gaps', {})
if not gap_data:
st.info("No gap analysis available.")
return
st.markdown("### Data Gaps Analysis")
material_name = gap_data.get('material_name')
if material_name:
st.markdown(f"**Material:** {material_name}")
# Check for Gemini ADK format
gaps_by_method = gap_data.get('gaps_by_method', [])
is_adk_format = gaps_by_method and isinstance(gaps_by_method[0], dict) and 'gap_severity' in gaps_by_method[0]
if is_adk_format:
render_gaps_adk_format(gap_data)
return
# Legacy format
col1, col2 = st.columns(2)
with col1:
well_doc = gap_data.get('well_documented_methods', [])
st.markdown("#### Well Documented Methods")
if well_doc:
for m in well_doc:
st.success(f"β
{m}")
else:
st.info("None identified")
with col2:
poor_doc = gap_data.get('poorly_documented_methods', [])
st.markdown("#### Needs More Research")
if poor_doc:
for m in poor_doc:
st.warning(f"β οΈ {m}")
else:
st.info("None identified")
critical = gap_data.get('critical_gaps', [])
if critical:
st.markdown("#### Critical Gaps")
for gap in critical:
st.error(f"β {gap}")
if gaps_by_method:
st.markdown("#### Gaps by Method")
for gap in gaps_by_method:
with st.expander(f"{gap.get('method_name', 'Unknown')} - Priority: {gap.get('priority', 'N/A')}"):
missing = gap.get('missing_parameters', [])
if missing:
st.markdown("**Missing Parameters:**")
for p in missing:
st.markdown(f"- {p}")
queries = gap.get('suggested_search_queries', [])
if queries:
st.markdown("**Suggested Searches:**")
for q in queries:
st.code(q)
def render_gaps_adk_format(gap_data: Dict):
"""Render data gaps in Gemini ADK format."""
gaps_by_method = gap_data.get('gaps_by_method', [])
overall_assessment = gap_data.get('overall_assessment', '')
recommendations = gap_data.get('recommendations', [])
# Sort by severity
severity_order = {'Critical': 0, 'High': 1, 'Moderate': 2, 'Low': 3, 'Minimal': 4}
sorted_gaps = sorted(gaps_by_method, key=lambda x: severity_order.get(x.get('gap_severity', 'Low'), 5))
# Summary metrics
col1, col2, col3, col4 = st.columns(4)
critical_count = sum(1 for g in gaps_by_method if g.get('gap_severity') == 'Critical')
high_count = sum(1 for g in gaps_by_method if g.get('gap_severity') == 'High')
moderate_count = sum(1 for g in gaps_by_method if g.get('gap_severity') == 'Moderate')
low_count = sum(1 for g in gaps_by_method if g.get('gap_severity') in ['Low', 'Minimal'])
with col1:
st.metric("Critical", critical_count)
with col2:
st.metric("High", high_count)
with col3:
st.metric("Moderate", moderate_count)
with col4:
st.metric("Low/Minimal", low_count)
st.markdown("---")
# Gaps by Method
st.markdown("### Gaps by Method")
for gap in sorted_gaps:
method = gap.get('method', 'Unknown')
severity = gap.get('gap_severity', 'Unknown')
missing_count = gap.get('missing_parameters_count', 0)
description = gap.get('description', '')
if severity == 'Critical':
icon = "π΄"
elif severity == 'High':
icon = "π "
elif severity == 'Moderate':
icon = "π‘"
else:
icon = "π’"
with st.expander(f"{icon} **{method}** - {severity} ({missing_count} missing params)", expanded=severity in ['Critical', 'High']):
if severity == 'Critical':
st.error(f"**Severity:** {severity}")
elif severity == 'High':
st.warning(f"**Severity:** {severity}")
elif severity == 'Moderate':
st.info(f"**Severity:** {severity}")
else:
st.success(f"**Severity:** {severity}")
st.markdown(f"**Missing Parameters Count:** {missing_count}")
if description:
st.markdown(f"**Description:** {description}")
# Overall Assessment
if overall_assessment:
st.markdown("---")
st.markdown("### Overall Assessment")
st.info(overall_assessment)
# Recommendations
if recommendations:
st.markdown("### Recommendations")
for i, rec in enumerate(recommendations, 1):
st.markdown(f"{i}. {rec}")
def replace_source_refs_with_links(text: str, ref_lookup: dict) -> str:
"""Replace source references like [S1], S1, etc. with clickable HTML links."""
if not ref_lookup:
return text
def replace_match(match):
source_id = match.group(1)
ref = ref_lookup.get(source_id)
if ref and ref.get('url'):
return f'<a href="{ref["url"]}" target="_blank">[{source_id}]</a>'
return match.group(0)
text = re.sub(r'\[(S\d+)\]', replace_match, text)
return text
def render_report_tab(results: Dict):
"""Render the final report tab."""
final_output = results.get('final_output', {})
markdown_report = final_output.get('markdown_report', '')
ref_lookup = get_ref_lookup(results)
if markdown_report:
report_text = markdown_report.strip()
if report_text.startswith('```'):
report_text = re.sub(r'^```(?:markdown)?\s*\n?', '', report_text)
report_text = re.sub(r'\n?```\s*$', '', report_text)
report_text = replace_source_refs_with_links(report_text, ref_lookup)
st.markdown(report_text, unsafe_allow_html=True)
else:
st.info("No report available.")
st.json(final_output)
st.markdown("---")
col1, col2 = st.columns(2)
with col1:
if markdown_report:
st.download_button(
label="π₯ Download Markdown Report",
data=markdown_report,
file_name="process_parameter_report.md",
mime="text/markdown"
)
with col2:
json_data = json.dumps(final_output, indent=2, default=str)
st.download_button(
label="π₯ Download JSON Data",
data=json_data,
file_name="process_parameter_data.json",
mime="application/json"
)
def render_references_tab(results: Dict):
"""Render the references tab showing all sources from references.json."""
all_references = results.get('all_references', [])
if not all_references:
all_references = results.get('final_output', {}).get('references', [])
if not all_references:
st.info("No references available.")
return
st.markdown("### References")
st.markdown(f"**Total References:** {len(all_references)}")
# Filter controls
col1, col2 = st.columns(2)
with col1:
source_types = list(set(ref.get('source_type', 'unknown') for ref in all_references))
source_types = ['All'] + sorted([s for s in source_types if s])
selected_type = st.selectbox("Filter by Source Type", source_types, key="ref_type_filter")
with col2:
search_query = st.text_input("Search (ID, title, URL)", "", key="ref_search")
st.markdown("---")
# Filter references
filtered_refs = all_references
if selected_type != 'All':
filtered_refs = [r for r in filtered_refs if r.get('source_type') == selected_type]
if search_query:
search_lower = search_query.lower()
filtered_refs = [r for r in filtered_refs if
search_lower in r.get('id', '').lower() or
search_lower in r.get('title', '').lower() or
search_lower in r.get('url', '').lower()]
st.markdown(f"**Showing:** {len(filtered_refs)} references")
# Build table data
table_data = []
for ref in filtered_refs:
ref_id = ref.get('id', '')
title = ref.get('title', '')
url = ref.get('url', '')
year = ref.get('year', '')
source_type = ref.get('source_type', '')
display_title = title[:80] + '...' if len(title) > 80 else title
table_data.append({
"ID": ref_id,
"Title": display_title,
"Year": str(year) if year else "",
"Type": source_type,
"URL": url,
})
if table_data:
st.dataframe(
table_data,
hide_index=True,
use_container_width=True,
column_config={
'ID': st.column_config.TextColumn('ID', width='small'),
'Title': st.column_config.TextColumn('Title', width='large'),
'Year': st.column_config.TextColumn('Year', width='small'),
'Type': st.column_config.TextColumn('Type', width='small'),
'URL': st.column_config.LinkColumn('URL', width='medium'),
}
)
# Expandable detail view
st.markdown("### Reference Details")
for ref in filtered_refs[:50]:
ref_id = ref.get('id', 'Unknown')
title = ref.get('title', 'No title')
url = ref.get('url', '')
year = ref.get('year', '')
source_type = ref.get('source_type', '')
snippet = ref.get('snippet', '')
with st.expander(f"**{ref_id}** - {title[:60]}{'...' if len(title) > 60 else ''}"):
st.markdown(f"**ID:** {ref_id}")
st.markdown(f"**Title:** {title}")
if year:
st.markdown(f"**Year:** {year}")
st.markdown(f"**Source Type:** {source_type}")
if url:
st.markdown(f"**URL:** [{url[:60]}{'...' if len(url) > 60 else ''}]({url})")
if snippet:
st.markdown("**Snippet:**")
st.text(snippet[:500] + '...' if len(snippet) > 500 else snippet)
if len(filtered_refs) > 50:
st.info(f"Showing first 50 of {len(filtered_refs)} references. Use filters to narrow results.")
# Download button
st.markdown("---")
refs_json = json.dumps(filtered_refs, indent=2, default=str)
st.download_button(
label="π₯ Download References (JSON)",
data=refs_json,
file_name="references.json",
mime="application/json"
)
# --- Main App ---
def main():
# Header
st.markdown('<p class="main-header">π¬ Material Process Parameters</p>', unsafe_allow_html=True)
st.markdown('<p class="sub-header">Browse synthesis process parameters for advanced materials</p>', unsafe_allow_html=True)
# Sidebar: Report selector
st.sidebar.markdown("### Select Report")
reports = scan_existing_reports(OUTPUT_DIR)
if not reports:
st.warning("No reports available. Please add report data to the 'reports/' folder.")
st.info("""
Expected folder structure:
```
reports/
βββ material_name_YYYYMMDD_HHMMSS/
β βββ 07_final_output.json
β βββ 03_experiment_extraction/ (optional, ADK format)
β βββ references.json (optional)
```
""")
return
# Report selector
report_options = {r['display']: r for r in reports}
selected_display = st.sidebar.selectbox(
"Choose a report to view",
options=list(report_options.keys()),
key="report_selector"
)
if selected_display:
selected_report = report_options[selected_display]
st.sidebar.caption(f"π {selected_report['folder_name']}")
# Show backend info
backend_icon = selected_report.get('backend_icon', 'π€')
backend_label = selected_report.get('backend_label', 'OpenAI')
st.sidebar.info(f"{backend_icon} Generated with {backend_label}")
# Load and display the selected report
results = load_report_from_folder(selected_report['folder'])
if results:
# Summary metrics
render_results_summary(results)
st.markdown("---")
# Tabbed results view
tabs = st.tabs([
"π Methods",
"βοΈ Parameters",
"π₯ Teams",
"βοΈ Comparison",
"π Gaps",
"π Report",
"π References"
])
with tabs[0]:
render_methods_tab(results)
with tabs[1]:
render_parameters_tab(results)
with tabs[2]:
render_teams_tab(results)
with tabs[3]:
render_comparison_tab(results)
with tabs[4]:
render_gaps_tab(results)
with tabs[5]:
render_report_tab(results)
with tabs[6]:
render_references_tab(results)
else:
st.error("Failed to load the selected report.")
# About section in sidebar
st.sidebar.markdown("---")
st.sidebar.markdown("### About")
st.sidebar.info("""
This viewer displays pre-generated synthesis parameter reports for advanced materials.
Each report includes:
- Synthesis methods
- Process parameters (experiments)
- Research team attribution
- Cross-team comparisons
- Data gap analysis
- Full references
""")
if __name__ == "__main__":
main()
"""
Material Process Parameters - Report Viewer
Read-only viewer for pre-generated synthesis parameter reports.
Deployed on Hugging Face Spaces: Bingdo/process_parameter
"""
import streamlit as st
import json
import re
from pathlib import Path
from datetime import datetime
from typing import Optional, Dict, Any
from urllib.parse import urlparse
# --- Configuration ---
OUTPUT_DIR = "reports"
# --- Page Configuration ---
st.set_page_config(
page_title="Material Process Parameters",
page_icon="π¬",
layout="wide",
initial_sidebar_state="expanded"
)
# --- Custom CSS ---
st.markdown("""
<style>
.main-header {
font-size: 2.5rem;
font-weight: 700;
color: #1f77b4;
margin-bottom: 0.5rem;
}
.sub-header {
font-size: 1.2rem;
color: #666;
margin-bottom: 2rem;
}
.metric-card {
background-color: #ffffff;
border-radius: 10px;
padding: 1rem;
box-shadow: 0 2px 4px rgba(0,0,0,0.1);
text-align: center;
}
.stTabs [data-baseweb="tab-list"] {
gap: 8px;
}
.stTabs [data-baseweb="tab"] {
padding: 10px 20px;
}
</style>
""", unsafe_allow_html=True)
# --- Report Loading Functions ---
def scan_existing_reports(output_dir: str) -> list:
"""Scan output directory for existing report folders."""
output_path = Path(output_dir)
if not output_path.exists():
return []
reports = []
for folder in sorted(output_path.iterdir(), reverse=True):
if folder.is_dir() and not folder.name.startswith('.'):
final_output = folder / "07_final_output.json"
if final_output.exists():
folder_name = folder.name
# Detect backend type from folder name
is_adk = folder_name.endswith('_adk')
backend_label = "Gemini" if is_adk else "OpenAI"
backend_icon = "β¨" if is_adk else "π€"
# Strip _adk suffix for parsing
parse_name = folder_name[:-4] if is_adk else folder_name
# Extract material name and timestamp from folder name
parts = parse_name.rsplit('_', 2)
if len(parts) >= 3:
material_name = parts[0].replace('_', ' ').title()
date_str = parts[1]
time_str = parts[2]
try:
timestamp = datetime.strptime(f"{date_str}_{time_str}", "%Y%m%d_%H%M%S")
display_time = timestamp.strftime("%Y-%m-%d %H:%M")
except ValueError:
display_time = folder_name
else:
material_name = folder_name
display_time = ""
reports.append({
'folder': str(folder),
'folder_name': folder_name,
'material': material_name,
'timestamp': display_time,
'backend': 'gemini_adk' if is_adk else 'openai',
'backend_label': backend_label,