#!/usr/bin/env python3
"""
Generate enhanced HTML website from README.md table
"""
import pandas as pd
import re
import os
def to_link_if_markdown(cell_text: str) -> str:
"""Convert markdown links [text](url) to HTML tags"""
if not isinstance(cell_text, str):
return str(cell_text)
cell_text = re.sub(r'\[(.*?)\]\((.*?)\)', r'\1', cell_text)
return cell_text.strip()
def extract_table_from_readme(readme_path: str) -> pd.DataFrame:
"""Extract the main projects table from README.md"""
with open(readme_path, "r", encoding='utf-8') as f:
text = f.readlines()
table = []
in_projects_section = False
for line in text:
# Check if we're in the Projects section
if line.strip() == "### Projects":
in_projects_section = True
continue
# Stop if we hit another section
if in_projects_section and line.startswith("### ") and "Projects" not in line:
break
# Extract table rows (has 8 | characters for 7 columns)
if in_projects_section and len(re.findall(r"\|", line)) == 8:
row = [cell.strip() for cell in line.split("|")[1:-1]]
table.append(row)
if len(table) < 2:
raise ValueError("Could not find valid table in README.md")
# First row is header, second row is separator, rest is data
header = table[0]
data = table[2:] if len(table) > 2 else []
df = pd.DataFrame(data, columns=header)
# Apply markdown to HTML conversion
df = df.applymap(to_link_if_markdown)
return df
def get_enhanced_html_template() -> str:
"""Return the enhanced HTML template"""
return '''
Awesome Computational Primatology
🐒 Awesome Computational Primatology
A curated list of machine learning research for non-human primatology
{total_papers}Papers
{years_span}Years
{with_code}With Code
{with_data}With Data
🏷️ Topic Legend
PDPrimate Detection
BPEBody Pose Estimation
FDFace Detection
FLEFacial Landmark Estimation
FRFace Recognition
FACFacial Action Coding
BRBehavior Recognition
AMAvatar/Mesh
SISpecies Identification
RLReinforcement Learning
{table_html}
'''
def calculate_stats(df: pd.DataFrame) -> dict:
"""Calculate statistics from the dataframe"""
total_papers = len(df)
# Count years
years = set()
for year in df.iloc[:, 0]: # First column is year
if str(year).isdigit():
years.add(int(year))
years_span = len(years)
# Count papers with code (Model column)
with_code = 0
model_col = df.iloc[:, 4] if len(df.columns) > 4 else pd.Series() # Model column
for value in model_col:
if isinstance(value, str) and ('Yes' in value or 'Code only' in value):
with_code += 1
# Count papers with data (Data column)
with_data = 0
data_col = df.iloc[:, 5] if len(df.columns) > 5 else pd.Series() # Data column
for value in data_col:
if isinstance(value, str) and 'Yes' in value:
with_data += 1
return {
'total_papers': total_papers,
'years_span': years_span,
'with_code': with_code,
'with_data': with_data
}
def main():
"""Main function to generate the website"""
# Determine if running in GitHub Actions or locally
if os.path.exists("/home/runner/work"):
# GitHub Actions
base_path = "/home/runner/work/awesome-computational-primatology/awesome-computational-primatology"
else:
# Local development - go up 2 levels from .github/workflows/
script_dir = os.path.dirname(os.path.abspath(__file__)) # .github/workflows/
base_path = os.path.dirname(os.path.dirname(script_dir)) # repository root
readme_path = os.path.join(base_path, "README.md")
output_path = os.path.join(base_path, "index.html")
print(f"Script location: {os.path.abspath(__file__)}")
print(f"Base path: {base_path}")
print(f"README path: {readme_path}")
print(f"Output path: {output_path}")
try:
# Extract table from README
df = extract_table_from_readme(readme_path)
print(f"Extracted table with {len(df)} rows and {len(df.columns)} columns")
# Calculate statistics
stats = calculate_stats(df)
print(f"Statistics: {stats}")
# Generate table HTML
table_html = df.to_html(
table_id="table",
escape=False,
index=False,
classes="display"
)
# Get template and format with data
template = get_enhanced_html_template()
html_content = template.replace('{table_html}', table_html)
html_content = html_content.replace('{total_papers}', str(stats['total_papers']))
html_content = html_content.replace('{years_span}', str(stats['years_span']))
html_content = html_content.replace('{with_code}', str(stats['with_code']))
html_content = html_content.replace('{with_data}', str(stats['with_data']))
# Write output
with open(output_path, "w", encoding='utf-8') as f:
f.write(html_content)
print(f"✅ Generated enhanced website: {output_path}")
except Exception as e:
print(f"❌ Error generating website: {e}")
raise
if __name__ == "__main__":
main()