Spaces:
Running
Running
Commit ·
5be9274
1
Parent(s): ca526b9
Revert "Refresh graph directly from Hub API"
Browse filesThis reverts commit cfe24a8555f547fd805afa88ed651ba284979b52.
Files changed (2)
1234511 unmodified lines1718192021222327 unmodified lines515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551567 unmodified lines1641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092106 unmodified lines2172182192202212222232242252262272284 unmodified lines23323423523623723823924024124224324424562 unmodified lines308309310311312313314315316317318319320321322323324143 unmodified lines4684694704714724734744754764774784794804815 unmodified lines48748848949049149249349449549649730 unmodified lines5285295305315325335349 unmodified lines54454554654754854955055155255355412 unmodified lines56756856957057157257357457557657757857958058158258358458558658758858959059112 unmodified lines604605606607608609610#!/usr/bin/env python3"""Build and publish a Neo4j dump from the public Hugging Face Hub API."""from __future__ import annotations11 unmodified linesSOURCE_REPO = "cfahlgren1/hub-stats"HUB_API_SOURCE = "huggingface.co/api"DEFAULT_DUMP_REPO = "cnil/genmod-dump-neo4j"PARQUET_REVISION = "refs/convert/parquet"27 unmodified linesreturn models, datasetsdef isoformat(value: object) -> str | None:return value.isoformat() if hasattr(value, "isoformat") else Nonedef write_jsonl_snapshot(path: Path, rows: object, kind: str) -> int:count = 0with path.open("w", encoding="utf-8") as output:for info in rows:tags = list(info.tags or [])if kind == "model":safetensors = getattr(info, "safetensors", None)card_data = getattr(info, "card_data", None)base_models = getattr(info, "base_models", None) or {}record = {"_id": getattr(info, "_id", None),"id": info.id,"author": info.author,"lastModified": isoformat(info.last_modified),"downloadsAllTime": info.downloads_all_time or info.downloads,"pipeline_tag": info.pipeline_tag,"createdAt": isoformat(info.created_at),"parameters_total": getattr(safetensors, "total", None),"likes": info.likes,"license": (card_data.get("license")if isinstance(card_data, dict)else None),"tags": tags,"base_model_relation": base_models.get("relation"),"base_model_ids": [model.get("id")for model in base_models.get("models", [])if model.get("id")],}else:record = {"_id": getattr(info, "_id", None),"id": info.id,"author": info.author,"lastModified": isoformat(info.last_modified),"downloadsAllTime": info.downloads_all_time or info.downloads,"createdAt": isoformat(info.created_at),"tags": tags,}output.write(json.dumps(record, ensure_ascii=False) + "\n")count += 1if count % 50000 == 0:log(f"Collected {count:,} {kind} records")log(f"Collected {count:,} {kind} records in total")return countdef download_sources_from_api(work_dir: Path,api: HfApi,max_models: int | None,max_datasets: int | None,) -> tuple[Path, Path]:"""Create deterministic local snapshots without relying on a third-party dataset."""model_fields = ["author","baseModels","cardData","createdAt","downloads","downloadsAllTime","lastModified","likes","pipeline_tag","safetensors","tags",]dataset_fields = ["author","createdAt","downloads","downloadsAllTime","lastModified","likes","tags",]models = work_dir / "models.jsonl"datasets = work_dir / "datasets.jsonl"log("Collecting the model snapshot from the public Hugging Face Hub API")write_jsonl_snapshot(models,api.list_models(expand=model_fields, limit=max_models),"model",)log("Collecting the dataset snapshot from the public Hugging Face Hub API")write_jsonl_snapshot(datasets,api.list_datasets(expand=dataset_fields, limit=max_datasets),"dataset",)return models, datasetsdef sql_path(path: Path) -> str:return str(path).replace("'", "''")7 unmodified lines) -> None:model_limit = f" LIMIT {max_models}" if max_models else ""dataset_limit = f" LIMIT {max_datasets}" if max_datasets else ""if models_path.suffix == ".jsonl":model_source = f"read_json_auto('{sql_path(models_path)}', format='newline_delimited')"dataset_source = f"read_json_auto('{sql_path(datasets_path)}', format='newline_delimited')"model_columns = """TRY_CAST(_id AS VARCHAR) AS _id, id, author, lastModified,TRY_CAST(downloadsAllTime AS BIGINT) AS downloadsAllTime,pipeline_tag, createdAt,TRY_CAST(parameters_total AS BIGINT) AS parameters_total,TRY_CAST(likes AS BIGINT) AS likes,TRY_CAST(license AS VARCHAR) AS license, tags,TRY_CAST(base_model_relation AS VARCHAR) AS base_model_relation,TRY_CAST(base_model_ids AS VARCHAR[]) AS base_model_ids"""dataset_columns = """TRY_CAST(_id AS VARCHAR) AS _id, id, author, lastModified,TRY_CAST(downloadsAllTime AS BIGINT) AS downloadsAllTime,createdAt, tags"""else:model_source = f"read_parquet('{sql_path(models_path)}')"dataset_source = f"read_parquet('{sql_path(datasets_path)}')"model_columns = """_id, id, author, lastModified, downloadsAllTime, pipeline_tag,createdAt, safetensors.total AS parameters_total, likes,json_extract_string(cardData, '$.license') AS license, tags,baseModels.relation AS base_model_relation,list_transform(baseModels.models, model -> model.id) AS base_model_ids"""dataset_columns = "_id, id, author, lastModified, downloadsAllTime, createdAt, tags"connection.execute(f"""CREATE VIEW source_models ASSELECT * EXCLUDE (_dedupe_rank)FROM (SELECT{model_columns},row_number() OVER (PARTITION BY idORDER BY lastModified DESC NULLS LAST, _id DESC NULLS LAST) AS _dedupe_rankFROM {model_source}WHERE id IS NOT NULL AND trim(id) <> '')WHERE _dedupe_rank = 16 unmodified linesSELECT * EXCLUDE (_dedupe_rank)FROM (SELECT{dataset_columns},row_number() OVER (PARTITION BY idORDER BY lastModified DESC NULLS LAST, _id DESC NULLS LAST) AS _dedupe_rankFROM {dataset_source}WHERE id IS NOT NULL AND trim(id) <> '')WHERE _dedupe_rank = 14 unmodified lines"""CREATE VIEW base_model_edges ASSELECT DISTINCTbase_id AS parent_id,child.id AS child_id,COALESCE(child.base_model_relation, 'derived') AS relation_nameFROM source_models AS child,UNNEST(child.base_model_ids) AS nested(base_id)WHERE base_id IS NOT NULLAND trim(base_id) <> ''AND child.id IS NOT NULL""")62 unmodified linespipeline_tag AS task,CAST(createdAt AS VARCHAR) AS created_at,CASEWHEN parameters_total >= 1000000000THEN printf('%.1fB', parameters_total / 1000000000.0)WHEN parameters_total >= 1000000THEN printf('%.1fM', parameters_total / 1000000.0)WHEN parameters_total >= 1000THEN printf('%.1fK', parameters_total / 1000.0)WHEN parameters_total IS NOT NULLTHEN CAST(parameters_total AS VARCHAR)END AS parameters,likes,licenseFROM source_modelsWHERE id IS NOT NULL AND trim(id) <> ''),143 unmodified linesdef write_metadata(output_dir: Path,source_repo: str,source_revision: str,model_count: int,dataset_count: int,) -> Path:metadata = {"built_at": datetime.now(timezone.utc).isoformat(),"source_repo": source_repo,"source_revision": source_revision,"model_count": model_count,"dataset_count": dataset_count,5 unmodified linesdef parquet_unique_id_count(path: Path) -> int:connection = duckdb.connect()reader = "read_json_auto" if path.suffix == ".jsonl" else "read_parquet"count = connection.execute(f"""SELECT count(DISTINCT id)FROM {reader}('{sql_path(path)}')WHERE id IS NOT NULL AND trim(id) <> ''""").fetchone()[0]30 unmodified linespath_or_fileobj=str(metadata_path),),],commit_message="Refresh Neo4j graph from the Hugging Face Hub API",)9 unmodified linesparser.add_argument("--dump-repo", default=os.getenv("NEO4J_DUMP_REPO", DEFAULT_DUMP_REPO))parser.add_argument("--dump-revision", default=os.getenv("NEO4J_DUMP_REVISION", "main"))parser.add_argument("--neo4j-admin", default=os.getenv("NEO4J_ADMIN", "neo4j-admin"))parser.add_argument("--source",choices=("hub-api", "hub-stats"),default=os.getenv("GENMOD_REFRESH_SOURCE", "hub-api"),)parser.add_argument("--models-parquet", type=Path)parser.add_argument("--datasets-parquet", type=Path)parser.add_argument("--max-models", type=int)12 unmodified linesargs.work_dir.mkdir(parents=True, exist_ok=True)api = HfApi()if bool(args.models_parquet) != bool(args.datasets_parquet):raise SystemExit("Provide both --models-parquet and --datasets-parquet.")if args.models_parquet:models_path, datasets_path = args.models_parquet, args.datasets_parquetsource_repo = "local-files"source_revision = "provided"elif args.source == "hub-stats":source_repo = SOURCE_REPOsource_revision = api.dataset_info(SOURCE_REPO).shamodels_path, datasets_path = download_sources(args.work_dir)else:source_repo = HUB_API_SOURCEsource_revision = datetime.now(timezone.utc).isoformat()models_path, datasets_path = download_sources_from_api(args.work_dir,api,args.max_models,args.max_datasets,)csv_dir = args.work_dir / "csv"files = prepare_csv_files(12 unmodified linesdataset_count = args.max_datasets or parquet_unique_id_count(datasets_path)metadata_path = write_metadata(args.work_dir,source_repo,source_revision,model_count,dataset_count,1234511 unmodified lines17181920212227 unmodified lines5051525354557 unmodified lines6364656667686970717273747576777879806 unmodified lines8788899091929394959697984 unmodified lines10310410510610710810911011111211311411511662 unmodified lines179180181182183184185186187188189190191192193194195143 unmodified lines3393403413423433443453463473483493503515 unmodified lines35735835936036136236336436536630 unmodified lines3973983994004014024039 unmodified lines41341441541641741812 unmodified lines43143243343443543643743843944044144244312 unmodified lines456457458459460461#!/usr/bin/env python3"""Build and publish a Neo4j dump from the public cfahlgren1/hub-stats dataset."""from __future__ import annotations11 unmodified linesSOURCE_REPO = "cfahlgren1/hub-stats"DEFAULT_DUMP_REPO = "cnil/genmod-dump-neo4j"PARQUET_REVISION = "refs/convert/parquet"27 unmodified linesreturn models, datasetsdef sql_path(path: Path) -> str:return str(path).replace("'", "''")7 unmodified lines) -> None:model_limit = f" LIMIT {max_models}" if max_models else ""dataset_limit = f" LIMIT {max_datasets}" if max_datasets else ""connection.execute(f"""CREATE VIEW source_models ASSELECT * EXCLUDE (_dedupe_rank)FROM (SELECT*,row_number() OVER (PARTITION BY idORDER BY lastModified DESC NULLS LAST, _id DESC NULLS LAST) AS _dedupe_rankFROM read_parquet('{sql_path(models_path)}')WHERE id IS NOT NULL AND trim(id) <> '')WHERE _dedupe_rank = 16 unmodified linesSELECT * EXCLUDE (_dedupe_rank)FROM (SELECT*,row_number() OVER (PARTITION BY idORDER BY lastModified DESC NULLS LAST, _id DESC NULLS LAST) AS _dedupe_rankFROM read_parquet('{sql_path(datasets_path)}')WHERE id IS NOT NULL AND trim(id) <> '')WHERE _dedupe_rank = 14 unmodified lines"""CREATE VIEW base_model_edges ASSELECT DISTINCTbase.id AS parent_id,child.id AS child_id,COALESCE(child.baseModels.relation, 'derived') AS relation_nameFROM source_models AS child,UNNEST(child.baseModels.models) AS nested(base)WHERE child.baseModels IS NOT NULLAND base.id IS NOT NULLAND trim(base.id) <> ''AND child.id IS NOT NULL""")62 unmodified linespipeline_tag AS task,CAST(createdAt AS VARCHAR) AS created_at,CASEWHEN safetensors.total >= 1000000000THEN printf('%.1fB', safetensors.total / 1000000000.0)WHEN safetensors.total >= 1000000THEN printf('%.1fM', safetensors.total / 1000000.0)WHEN safetensors.total >= 1000THEN printf('%.1fK', safetensors.total / 1000.0)WHEN safetensors.total IS NOT NULLTHEN CAST(safetensors.total AS VARCHAR)END AS parameters,likes,json_extract_string(cardData, '$.license') AS licenseFROM source_modelsWHERE id IS NOT NULL AND trim(id) <> ''),143 unmodified linesdef write_metadata(output_dir: Path,source_revision: str,model_count: int,dataset_count: int,) -> Path:metadata = {"built_at": datetime.now(timezone.utc).isoformat(),"source_repo": SOURCE_REPO,"source_revision": source_revision,"model_count": model_count,"dataset_count": dataset_count,5 unmodified linesdef parquet_unique_id_count(path: Path) -> int:connection = duckdb.connect()count = connection.execute(f"""SELECT count(DISTINCT id)FROM read_parquet('{sql_path(path)}')WHERE id IS NOT NULL AND trim(id) <> ''""").fetchone()[0]30 unmodified linespath_or_fileobj=str(metadata_path),),],commit_message="Refresh Neo4j graph from cfahlgren1/hub-stats",)9 unmodified linesparser.add_argument("--dump-repo", default=os.getenv("NEO4J_DUMP_REPO", DEFAULT_DUMP_REPO))parser.add_argument("--dump-revision", default=os.getenv("NEO4J_DUMP_REVISION", "main"))parser.add_argument("--neo4j-admin", default=os.getenv("NEO4J_ADMIN", "neo4j-admin"))parser.add_argument("--models-parquet", type=Path)parser.add_argument("--datasets-parquet", type=Path)parser.add_argument("--max-models", type=int)12 unmodified linesargs.work_dir.mkdir(parents=True, exist_ok=True)api = HfApi()source_revision = api.dataset_info(SOURCE_REPO).shaif bool(args.models_parquet) != bool(args.datasets_parquet):raise SystemExit("Provide both --models-parquet and --datasets-parquet.")if args.models_parquet:models_path, datasets_path = args.models_parquet, args.datasets_parquetelse:models_path, datasets_path = download_sources(args.work_dir)csv_dir = args.work_dir / "csv"files = prepare_csv_files(12 unmodified linesdataset_count = args.max_datasets or parquet_unique_id_count(datasets_path)metadata_path = write_metadata(args.work_dir,source_revision,model_count,dataset_count,
123456#!/bin/bashset -eapt-get updateapt-get install -y python3-pippip3 install duckdb==1.3.2 huggingface-hub==1.25.1exec python3 /workspace/database_refresh/refresh_database.py --source hub-api1234567#!/bin/bashset -eapt-get updateapt-get install -y python3-pip wgetpip3 install duckdb==1.3.2 huggingface-hub==0.31.4wget -qO /tmp/r.py https://huggingface.co/spaces/cnil/genmod/resolve/refresh-hub-database/database_refresh/refresh_database.pyexec python3 /tmp/r.py
database_refresh/refresh_database.py+25-174
database_refresh/run_weekly_refresh.sh+4-3