import requests import csv import pandas as pd import matplotlib.pyplot as plt from datetime import datetime from pathlib import Path import os import re # Get the repository root (works both for local and GitHub Actions) if 'GITHUB_WORKSPACE' in os.environ: REPO_ROOT = Path(os.environ['GITHUB_WORKSPACE']) else: # Find git root when running locally current_dir = Path(__file__).resolve().parent while current_dir != current_dir.parent: if (current_dir / '.git').exists(): REPO_ROOT = current_dir break current_dir = current_dir.parent else: raise RuntimeError("Not in a git repository") # Define paths relative to repository root CSV_PATH = REPO_ROOT / 'daily_downloads.csv' IMAGE_PATH = REPO_ROOT / 'download_statistics.png' README_PATH = REPO_ROOT / 'README.md' API_URL = "https://huggingface.co/api/datasets/danielrosehill/ifvi_valuefactors_deriv?expand[]=downloads&expand[]=downloadsAllTime" def update_csv(): response = requests.get(API_URL) data = response.json() downloads = data.get('downloadsAllTime', 0) today = datetime.now().strftime('%Y-%m-%d') try: with open(CSV_PATH, mode='r') as file: reader = csv.reader(file) rows = list(reader) except FileNotFoundError: rows = [["Date", "Total Downloads"]] # Check if today's date is already in the CSV today_exists = False for i, row in enumerate(rows): if len(row) > 0 and row[0] == today: rows[i] = [today, downloads] today_exists = True break # If today's date is not in the CSV, add it if not today_exists: rows.append([today, downloads]) with open(CSV_PATH, mode='w', newline='') as file: writer = csv.writer(file) writer.writerows(rows) print(f"Updated CSV with {downloads} downloads for {today}") def generate_image(): data = pd.read_csv(CSV_PATH) data['Date'] = pd.to_datetime(data['Date']) data = data.sort_values('Date') plt.figure(figsize=(10, 6)) plt.plot(data['Date'], data['Total Downloads'], marker='o', label='Total Downloads') plt.title('Cumulative Downloads Over Time') plt.xlabel('Date') plt.ylabel('Cumulative Downloads') plt.grid(True) plt.legend() plt.xticks(rotation=45) plt.tight_layout() plt.savefig(IMAGE_PATH) plt.close() print(f"Generated download statistics image at {IMAGE_PATH}") def update_readme(): # The badge in the README is already dynamic and will update automatically # This function ensures the download_statistics.png image is properly referenced with open(README_PATH, 'r') as file: content = file.read() # Check if we need to add a download statistics section with the image if "## Cumulative Download Statistics" not in content and "![Cumulative Download Statistics]" not in content: # Find a good place to insert the download statistics section - after the badges and before navigation index badge_line = "![Dataset Downloads Hugging Face](https://img.shields.io/badge/dynamic/json?color=brightgreen&label=Cumulative%20Dataset%20Downloads&query=$.downloadsAllTime&url=https://huggingface.co/api/datasets/danielrosehill/ifvi_valuefactors_deriv)" navigation_index = "## 📑 Navigation Index" if badge_line in content and navigation_index in content: # Insert after the badges and before navigation index parts = content.split(badge_line) badge_part = parts[0] + badge_line rest_parts = parts[1].split(navigation_index) content = badge_part + "\n\n## Cumulative Download Statistics\n\n![Cumulative Download Statistics](download_statistics.png)\n\n" + navigation_index + rest_parts[1] else: # Fallback: Insert at the beginning of the file content = content.split("---\n", 2) if len(content) >= 3: content = "---\n" + content[1] + "---\n" + "## Cumulative Download Statistics\n\n![Cumulative Download Statistics](download_statistics.png)\n\n" + content[2] else: content = "## Cumulative Download Statistics\n\n![Cumulative Download Statistics](download_statistics.png)\n\n" + content[0] # Update existing section if it exists but is in the wrong place elif "## Cumulative Download Statistics" in content: # First remove the existing section section_start = content.find("## Cumulative Download Statistics") section_end = content.find("\n\n", section_start + 30) # Look for the end of the section if section_end == -1: # If not found, try to find the next heading section_end = content.find("\n##", section_start + 30) if section_end == -1: # If still not found, just use the rest of the content section_end = len(content) else: section_end += 2 # Include the newlines section_content = content[section_start:section_end] content = content.replace(section_content, "") # Then add it in the right place badge_line = "![Dataset Downloads Hugging Face](https://img.shields.io/badge/dynamic/json?color=brightgreen&label=Cumulative%20Dataset%20Downloads&query=$.downloadsAllTime&url=https://huggingface.co/api/datasets/danielrosehill/ifvi_valuefactors_deriv)" navigation_index = "## 📑 Navigation Index" if badge_line in content and navigation_index in content: parts = content.split(badge_line) badge_part = parts[0] + badge_line rest_parts = parts[1].split(navigation_index) content = badge_part + "\n\n## Cumulative Download Statistics\n\n![Cumulative Download Statistics](download_statistics.png)\n\n" + navigation_index + rest_parts[1] with open(README_PATH, 'w') as file: file.write(content) print(f"Updated README with cumulative download statistics section") if __name__ == "__main__": update_csv() generate_image() update_readme()