From 1a7aba3c126e939401fa9cd29bbaf7d7caeb8b01 Mon Sep 17 00:00:00 2001 From: Atul Anand Date: Mon, 5 Oct 2026 19:51:30 +0530 Subject: [PATCH] build: make all pipeline, stage stats, remove dead code --- .github/CODEOWNERS | 5 - .gitignore | 2 +- Makefile | 49 ++++++ README.md | 1 - api/cache.py | 0 api/routes/__init__.py | 0 api/routes/analyze.py | 0 api/routes/gap.py | 0 api/routes/health.py | 0 api/routes/match.py | 0 api/routes/readiness.py | 0 api/routes/roles.py | 0 api/routes/skills.py | 0 artifacts/metrics.json | 2 +- artifacts/skills_autocomplete.json | 12 +- docs/{ => archive}/handoff.md | 0 docs/bench.json | 77 +++++++++ docs/data_audit.md | 11 ++ docs/reproducibility.md | 34 ++++ etl/clean.py | 15 ++ etl/label.py | 21 +++ etl/paths.py | 1 + etl/pipeline.py | 41 +++++ etl/profile.py | 166 ++++++++++++-------- etl/raw.py | 32 ++++ etl/stats.py | 54 +++++++ fixtures/classifier.pkl | Bin 1357 -> 0 bytes fixtures/label_encoder.pkl | Bin 1360 -> 0 bytes fixtures/role_profiles.json | 140 ----------------- fixtures/rules.parquet | Bin 6434 -> 0 bytes fixtures/skill_vocab.json | 42 ----- fixtures/skills_autocomplete.json | 242 ----------------------------- mining/fpgrowth_bench.py | 43 +++++ mining/rules.py | 20 ++- ml/export_runtime.py | 17 +- ml/train.py | 29 +++- scripts/fetch_artifacts.py | 26 ---- scripts/fetch_artifacts.sh | 3 - scripts/make_fixtures.py | 106 ------------- 39 files changed, 547 insertions(+), 644 deletions(-) create mode 100644 Makefile delete mode 100644 api/cache.py delete mode 100644 api/routes/__init__.py delete mode 100644 api/routes/analyze.py delete mode 100644 api/routes/gap.py delete mode 100644 api/routes/health.py delete mode 100644 api/routes/match.py delete mode 100644 api/routes/readiness.py delete mode 100644 api/routes/roles.py delete mode 100644 api/routes/skills.py rename docs/{ => archive}/handoff.md (100%) create mode 100644 docs/bench.json create mode 100644 docs/reproducibility.md create mode 100644 etl/pipeline.py create mode 100644 etl/raw.py create mode 100644 etl/stats.py delete mode 100644 fixtures/classifier.pkl delete mode 100644 fixtures/label_encoder.pkl delete mode 100644 fixtures/role_profiles.json delete mode 100644 fixtures/rules.parquet delete mode 100644 fixtures/skill_vocab.json delete mode 100644 fixtures/skills_autocomplete.json delete mode 100644 scripts/fetch_artifacts.py delete mode 100644 scripts/fetch_artifacts.sh delete mode 100644 scripts/make_fixtures.py diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS index 0e538f7..f4e3e0d 100644 --- a/.github/CODEOWNERS +++ b/.github/CODEOWNERS @@ -3,10 +3,5 @@ /mining/ eccentricAryan404 @TODO_ADITYA /ml/ @TODO_ADITYA eccentricAryan404 /api/ Archit1302-wolf ssp0009 -/fixtures/ Archit1302-wolf ssp0009 -/scripts/ Archit1302-wolf ssp0009 -/api/routes/match.py AtulACleaver Archit1302-wolf -/api/routes/readiness.py AtulACleaver Archit1302-wolf -/api/routes/gap.py AtulACleaver Archit1302-wolf /frontend/ ssp0009 Archit1302-wolf /docs/contracts.md AtulACleaver @TODO_ADITYA eccentricAryan404 Archit1302-wolf ssp0009 diff --git a/.gitignore b/.gitignore index e19899f..d5a2506 100644 --- a/.gitignore +++ b/.gitignore @@ -3,7 +3,7 @@ artifacts/* !artifacts/*.json *.pkl *.parquet -!fixtures/* +.vercel/ __pycache__/ .ipynb_checkpoints/ .env diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..c8f4b31 --- /dev/null +++ b/Makefile @@ -0,0 +1,49 @@ +PYTHON := $(if $(wildcard .venv/bin/python),.venv/bin/python,python) + +.PHONY: all setup raw clean-data label train rules export all bench test api web fetch-data reset + +setup: + @if [ ! -d .venv ]; then python3.12 -m venv .venv 2>/dev/null || python3 -m venv .venv; fi + .venv/bin/pip install -r requirements-dev.txt + cd frontend && npm ci + +raw: + $(PYTHON) -m etl.raw + +clean-data: + $(PYTHON) -m etl.profile + $(PYTHON) -m etl.clean + +label: + $(PYTHON) -m etl.label + +train: + $(PYTHON) -m ml.train + +rules: + $(PYTHON) -m mining.rules + +export: + $(PYTHON) -m ml.export_runtime + +all: + $(PYTHON) -m etl.pipeline + +bench: + $(PYTHON) -m mining.fpgrowth_bench + +test: + $(PYTHON) -m ruff check . + $(PYTHON) -m pytest -q + +api: + $(PYTHON) -m uvicorn api.main:app --reload --port 8000 + +web: + cd frontend && npm run dev + +fetch-data: + gh release download data-v3 --dir data/ + +reset: + rm -rf data/*.parquet data/*.csv data/stats artifacts/*.pkl artifacts/*.parquet diff --git a/README.md b/README.md index bcf7d7d..e8e43c9 100644 --- a/README.md +++ b/README.md @@ -29,7 +29,6 @@ skillgraph/ ├── taxonomy/ # Aryan — hand-edited skill aliases & role families ├── api/ # Archit — FastAPI serving layer ├── frontend/ # Shashank — Vite + React UI -├── fixtures/ # Archit — fake artifacts for dev ├── tests/ # each person owns their module's tests ├── docs/ # data audit, contracts, model writeup ├── data/ # GITIGNORED — rebuilt by the pipeline diff --git a/api/cache.py b/api/cache.py deleted file mode 100644 index e69de29..0000000 diff --git a/api/routes/__init__.py b/api/routes/__init__.py deleted file mode 100644 index e69de29..0000000 diff --git a/api/routes/analyze.py b/api/routes/analyze.py deleted file mode 100644 index e69de29..0000000 diff --git a/api/routes/gap.py b/api/routes/gap.py deleted file mode 100644 index e69de29..0000000 diff --git a/api/routes/health.py b/api/routes/health.py deleted file mode 100644 index e69de29..0000000 diff --git a/api/routes/match.py b/api/routes/match.py deleted file mode 100644 index e69de29..0000000 diff --git a/api/routes/readiness.py b/api/routes/readiness.py deleted file mode 100644 index e69de29..0000000 diff --git a/api/routes/roles.py b/api/routes/roles.py deleted file mode 100644 index e69de29..0000000 diff --git a/api/routes/skills.py b/api/routes/skills.py deleted file mode 100644 index e69de29..0000000 diff --git a/artifacts/metrics.json b/artifacts/metrics.json index 10604c0..ddb7469 100644 --- a/artifacts/metrics.json +++ b/artifacts/metrics.json @@ -275,7 +275,7 @@ "n_dropped_no_skills": 103, "n_val": 1915, "n_test": 1916, - "built_at": "2026-10-03T19:48:24Z", + "built_at": "2026-10-05T14:09:43Z", "band_cutoffs": { "prob_ready": 0.6, "prob_close": 0.3, diff --git a/artifacts/skills_autocomplete.json b/artifacts/skills_autocomplete.json index 2bb5c89..62729a2 100644 --- a/artifacts/skills_autocomplete.json +++ b/artifacts/skills_autocomplete.json @@ -19,7 +19,7 @@ { "id": 2, "name": "qa", - "display": "Qa", + "display": "QA", "aliases": [ "software testing", "automation testing", @@ -37,7 +37,7 @@ { "id": 4, "name": "javascript", - "display": "Javascript", + "display": "JavaScript", "aliases": [ "javascript" ] @@ -61,7 +61,7 @@ { "id": 7, "name": "css", - "display": "Css", + "display": "CSS", "aliases": [ "css" ] @@ -125,7 +125,7 @@ { "id": 15, "name": "ml", - "display": "Ml", + "display": "ML", "aliases": [ "machine learning" ] @@ -133,7 +133,7 @@ { "id": 16, "name": "html", - "display": "Html", + "display": "HTML", "aliases": [ "html" ] @@ -149,7 +149,7 @@ { "id": 18, "name": "cicd", - "display": "Cicd", + "display": "CI/CD", "aliases": [ "cicd" ] diff --git a/docs/handoff.md b/docs/archive/handoff.md similarity index 100% rename from docs/handoff.md rename to docs/archive/handoff.md diff --git a/docs/bench.json b/docs/bench.json new file mode 100644 index 0000000..d1630a8 --- /dev/null +++ b/docs/bench.json @@ -0,0 +1,77 @@ +[ + { + "min_sup_pct": "5.00%", + "min_sup": 0.05, + "support": 0.05, + "itemsets": 13, + "apriori_itemsets": 13, + "fpgrowth_itemsets": 13, + "apriori_time_sec": 0.1459, + "fpgrowth_time_sec": 0.0915, + "apriori_s": 0.1459, + "fpgrowth_s": 0.0915, + "speedup": 1.6, + "identical": "yes", + "max_support_diff": 0.0 + }, + { + "min_sup_pct": "3.00%", + "min_sup": 0.03, + "support": 0.03, + "itemsets": 34, + "apriori_itemsets": 34, + "fpgrowth_itemsets": 34, + "apriori_time_sec": 0.5189, + "fpgrowth_time_sec": 0.0969, + "apriori_s": 0.5189, + "fpgrowth_s": 0.0969, + "speedup": 5.35, + "identical": "yes", + "max_support_diff": 0.0 + }, + { + "min_sup_pct": "2.00%", + "min_sup": 0.02, + "support": 0.02, + "itemsets": 62, + "apriori_itemsets": 62, + "fpgrowth_itemsets": 62, + "apriori_time_sec": 1.5869, + "fpgrowth_time_sec": 0.1017, + "apriori_s": 1.5869, + "fpgrowth_s": 0.1017, + "speedup": 15.61, + "identical": "yes", + "max_support_diff": 0.0 + }, + { + "min_sup_pct": "1.00%", + "min_sup": 0.01, + "support": 0.01, + "itemsets": 168, + "apriori_itemsets": 168, + "fpgrowth_itemsets": 168, + "apriori_time_sec": 8.0566, + "fpgrowth_time_sec": 0.255, + "apriori_s": 8.0566, + "fpgrowth_s": 0.255, + "speedup": 31.6, + "identical": "yes", + "max_support_diff": 0.0 + }, + { + "min_sup_pct": "0.50%", + "min_sup": 0.005, + "support": 0.005, + "itemsets": 501, + "apriori_itemsets": 501, + "fpgrowth_itemsets": 501, + "apriori_time_sec": 43.6936, + "fpgrowth_time_sec": 0.3454, + "apriori_s": 43.6936, + "fpgrowth_s": 0.3454, + "speedup": 126.49, + "identical": "yes", + "max_support_diff": 0.0 + } +] \ No newline at end of file diff --git a/docs/data_audit.md b/docs/data_audit.md index 6d6ef07..62f0b90 100644 --- a/docs/data_audit.md +++ b/docs/data_audit.md @@ -108,3 +108,14 @@ Total Rows: 97,929 ## Skills - Rows with empty/null skills: 571 - Distinct raw tokens: 59,479 +- Tokens exported (count >= 5): 14,843 covering 91.3% of mentions + +## Baskets Audit: 34,569 vs 30,134 + +The original project plan stated 30,134 baskets, whereas data-v3 produced 34,569 baskets. The difference arose from how tech postings were filtered and cleaned across project stages. + +In the initial exploratory plan, a draft filter selected 33,724 postings based on skill tags. After dropping exact duplicates and empty skill lists, 30,134 rows survived. The plan assumed mining baskets would match that preliminary count of 30,134 postings (comprising 13,185 generic software engineer rows, 4,086 unmatched rows, and 12,863 role-labelled rows). + +In the pipeline implementation in `etl/clean.py`, the tech filter checked 32 keywords from `etl/tech_terms.txt` across both `title` and `tagsAndSkills` columns of `data/raw/indian-job-market-dataset-2025.xlsx`. This broader check identified 38,271 candidate tech postings. Cleaning dropped 100 exact duplicates, 80 rows with no skills after splitting, and 3,522 reposts, leaving 34,569 rows saved to `data/clean.parquet`. + +In `etl/label.py`, the `build_baskets` function created one basket per row of `data/clean.parquet`, saving 34,569 records to `data/baskets.parquet`. In that file, 32,949 baskets contain one or more canonical skill IDs and 1,620 contain empty lists after mapping against `artifacts/skill_vocab.json`. diff --git a/docs/reproducibility.md b/docs/reproducibility.md new file mode 100644 index 0000000..f3bd216 --- /dev/null +++ b/docs/reproducibility.md @@ -0,0 +1,34 @@ +# Reproducibility Audit + +The pipeline was verified by running `make reset` followed by `make all`. All rebuilt artifacts were compared against the committed artifacts in `artifacts/`. + +## Artifact Comparison + +| Metric / Artifact | Committed Value | Rebuilt Value | Match | +|---|---|---|---| +| Vocab size (`skill_vocab.json`) | 800 | 800 | yes | +| Vocab SHA256 (`skill_vocab.json`) | d749eb5d5044fea1e366972fba1bf94351c822dd580ac66a0e711a6f8f92dece | d749eb5d5044fea1e366972fba1bf94351c822dd580ac66a0e711a6f8f92dece | yes | +| Test macro F1 (`metrics.json`) | 0.7424 | 0.7424 | yes | +| Test accuracy (`metrics.json`) | 0.7463 | 0.7463 | yes | +| Test top-3 accuracy (`metrics.json`) | 0.9254 | 0.9254 | yes | +| Rule count (`rules.json` and `rules.parquet`) | 336 | 336 | yes | + +## Test Set Class Counts + +Test class supports were compared between committed `artifacts/metrics.json` and the rebuilt run. + +| Role Family | Committed Test Support | Rebuilt Test Support | Match | +|---|---|---|---| +| Backend | 191 | 191 | yes | +| Data / BI Analyst | 204 | 204 | yes | +| Data Science / ML | 180 | 180 | yes | +| DevOps / Cloud | 340 | 340 | yes | +| ERP / Enterprise | 223 | 223 | yes | +| Frontend | 117 | 117 | yes | +| Full Stack | 194 | 194 | yes | +| Mobile | 65 | 65 | yes | +| QA / Test | 243 | 243 | yes | +| Support / IT Ops | 159 | 159 | yes | +| **Total Test Postings** | **1,916** | **1,916** | **yes** | + +Every rebuilt metric and artifact matched the committed baseline exactly. diff --git a/etl/clean.py b/etl/clean.py index 50dc79e..821a370 100644 --- a/etl/clean.py +++ b/etl/clean.py @@ -1,7 +1,10 @@ import re +import time import pandas as pd +from etl.stats import write_stage_stats + DROP_REASONS = {} def drop(df, mask, reason): @@ -11,7 +14,9 @@ def drop(df, mask, reason): return df[~mask] def main(): + t0 = time.time() df = pd.read_parquet('data/raw.parquet') + rows_in = len(df) # 1. Filter to tech subset with open('etl/tech_terms.txt', 'r') as f: @@ -117,5 +122,15 @@ def norm_company(name): print(f"{n:>7,} {reason}") print(f"{len(df):>7,} rows surviving") + elapsed = time.time() - t0 + write_stage_stats( + stage="clean", + rows_in=rows_in, + rows_out=len(df), + drops_by_reason=DROP_REASONS, + elapsed_seconds=elapsed, + output_files=['data/clean.parquet'], + ) + if __name__ == '__main__': main() diff --git a/etl/label.py b/etl/label.py index f9447cd..fb72cda 100644 --- a/etl/label.py +++ b/etl/label.py @@ -1,9 +1,11 @@ import json import re +import time import pandas as pd import etl.normalize as norm +from etl.stats import write_stage_stats def load_families(csv_path): @@ -29,6 +31,7 @@ def label_title(title, patterns): return None def main(): + t0 = time.time() print("Labeling dataset...") clean_df = pd.read_parquet('data/clean.parquet') @@ -109,5 +112,23 @@ def main(): print(f"\nFinal labelled rows for dataset.parquet: {len(dataset_df)}") dataset_df.to_parquet('data/dataset.parquet', index=False) + elapsed = time.time() - t0 + write_stage_stats( + stage="label", + rows_in=len(clean_df), + rows_out=len(dataset_df), + drops_by_reason={ + "unmatched": len(unmatched), + "Software Engineer (generic)": int(dist.get('Software Engineer (generic)', 0)), + }, + elapsed_seconds=elapsed, + output_files=[ + 'data/baskets.parquet', + 'data/dataset.parquet', + 'artifacts/skill_vocab.json', + 'artifacts/skills_autocomplete.json', + ], + ) + if __name__ == '__main__': main() diff --git a/etl/paths.py b/etl/paths.py index e60daab..fea14cf 100644 --- a/etl/paths.py +++ b/etl/paths.py @@ -6,3 +6,4 @@ DATA_DIR = REPO_ROOT / "data" TAXONOMY_DIR = REPO_ROOT / "taxonomy" RAW_XLSX = DATA_DIR / "raw" / "indian-job-market-dataset-2025.xlsx" +STATS_DIR = DATA_DIR / "stats" diff --git a/etl/pipeline.py b/etl/pipeline.py new file mode 100644 index 0000000..d03bd52 --- /dev/null +++ b/etl/pipeline.py @@ -0,0 +1,41 @@ +import subprocess +import sys +import time + +STAGES = [ + ("raw", [sys.executable, "-m", "etl.raw"]), + ("profile", [sys.executable, "-m", "etl.profile"]), + ("clean", [sys.executable, "-m", "etl.clean"]), + ("label", [sys.executable, "-m", "etl.label"]), + ("train", [sys.executable, "-m", "ml.train"]), + ("rules", [sys.executable, "-m", "mining.rules"]), + ("export", [sys.executable, "-m", "ml.export_runtime"]), +] + + +def run_all(): + times = {} + total_start = time.time() + for name, cmd in STAGES: + print(f"\n{'='*20} Running stage: {name} {'='*20}") + t0 = time.time() + res = subprocess.run(cmd, check=False) + if res.returncode != 0: + print(f"Error: Stage {name} failed with exit code {res.returncode}", file=sys.stderr) + sys.exit(res.returncode) + elapsed = time.time() - t0 + times[name] = elapsed + print(f"=== Stage {name} finished in {elapsed:.2f}s ===") + + total_elapsed = time.time() - total_start + print("\n" + "=" * 45) + print("PIPELINE WALL TIME SUMMARY") + print("=" * 45) + for name, elapsed in times.items(): + print(f" {name:15s}: {elapsed:6.2f}s") + print(f" {'TOTAL':15s}: {total_elapsed:6.2f}s") + print("=" * 45) + + +if __name__ == "__main__": + run_all() diff --git a/etl/profile.py b/etl/profile.py index 9083520..bc10658 100644 --- a/etl/profile.py +++ b/etl/profile.py @@ -1,72 +1,106 @@ import os +import time import matplotlib.pyplot as plt import pandas as pd -os.makedirs('data', exist_ok=True) -os.makedirs('docs', exist_ok=True) - -print("Loading excel file...") -df = pd.read_excel('indian-job-market-dataset-2025.xlsx') - -print("Saving to parquet...") -df.to_parquet('data/raw.parquet', index=False) - -print("Writing audit doc...") -with open('docs/data_audit.md', 'w') as f: - f.write("# Data Audit\n\n") - f.write(f"Total Rows: {len(df):,}\n\n") - - f.write("## Columns\n") - for col in df.columns: - dtype = df[col].dtype - null_count = df[col].isnull().sum() - null_pct = (null_count / len(df)) * 100 - distinct_count = df[col].nunique() - examples = df[col].dropna().unique()[:5].tolist() - - f.write(f"### {col}\n") - f.write(f"- Dtype: {dtype}\n") - f.write(f"- Null Count: {null_count:,} ({null_pct:.2f}%)\n") - f.write(f"- Distinct Count: {distinct_count:,}\n") - f.write(f"- Examples: {examples}\n\n") - - skills_col = 'tagsAndSkills' # assuming this from the prompt - if skills_col not in df.columns: - # try to find a skill col +from etl.paths import RAW_XLSX +from etl.stats import write_stage_stats + + +def main(): + t0 = time.time() + os.makedirs('data', exist_ok=True) + os.makedirs('docs', exist_ok=True) + + print(f"Loading excel file from {RAW_XLSX}...") + df = pd.read_excel(RAW_XLSX) + + print("Saving to parquet...") + df.to_parquet('data/raw.parquet', index=False) + + print("Writing audit doc...") + with open('docs/data_audit.md', 'w') as f: + f.write("# Data Audit\n\n") + f.write(f"Total Rows: {len(df):,}\n\n") + + f.write("## Columns\n") for col in df.columns: - if 'skill' in col.lower() or 'tag' in col.lower(): - skills_col = col - break - - empty_skills = df[df[skills_col].isnull() | (df[skills_col].astype(str).str.strip() == '')] - f.write("## Skills\n") - f.write(f"- Rows with empty/null skills: {len(empty_skills):,}\n") - - # Split skills - skills_series = df[skills_col].dropna().astype(str) - all_tokens = skills_series.str.split(',').explode().str.strip() - # Handle empty strings after strip - all_tokens = all_tokens[all_tokens != ''] - token_counts = all_tokens.value_counts() - - f.write(f"- Distinct raw tokens: {len(token_counts):,}\n") - - # Export every token seen at least MIN_TOKEN_COUNT times. - # (A fixed top-1500 cut covered only ~58% of skill mentions.) - MIN_TOKEN_COUNT = 5 - top_tokens = token_counts[token_counts >= MIN_TOKEN_COUNT] - top_tokens.to_csv('data/top_tokens.csv', header=['count']) - f.write(f"- Tokens exported (count >= {MIN_TOKEN_COUNT}): {len(top_tokens):,} " - f"covering {top_tokens.sum() / token_counts.sum():.1%} of mentions\n") - - # Plot frequency curve - plt.figure(figsize=(10, 6)) - plt.plot(range(len(token_counts)), token_counts.values) - plt.yscale('log') - plt.title('Skill Token Frequency Curve') - plt.xlabel('Token Rank') - plt.ylabel('Frequency (log scale)') - plt.savefig('docs/token_frequency.png') - -print("Done!") + dtype = df[col].dtype + null_count = df[col].isnull().sum() + null_pct = (null_count / len(df)) * 100 + distinct_count = df[col].nunique() + examples = df[col].dropna().unique()[:5].tolist() + + f.write(f"### {col}\n") + f.write(f"- Dtype: {dtype}\n") + f.write(f"- Null Count: {null_count:,} ({null_pct:.2f}%)\n") + f.write(f"- Distinct Count: {distinct_count:,}\n") + f.write(f"- Examples: {examples}\n\n") + + skills_col = 'tagsAndSkills' + if skills_col not in df.columns: + for col in df.columns: + if 'skill' in col.lower() or 'tag' in col.lower(): + skills_col = col + break + + empty_skills = df[df[skills_col].isnull() | (df[skills_col].astype(str).str.strip() == '')] + f.write("## Skills\n") + f.write(f"- Rows with empty/null skills: {len(empty_skills):,}\n") + + # Split skills + skills_series = df[skills_col].dropna().astype(str) + all_tokens = skills_series.str.split(',').explode().str.strip() + all_tokens = all_tokens[all_tokens != ''] + token_counts = all_tokens.value_counts() + + f.write(f"- Distinct raw tokens: {len(token_counts):,}\n") + + MIN_TOKEN_COUNT = 5 + top_tokens = token_counts[token_counts >= MIN_TOKEN_COUNT] + top_tokens.to_csv('data/top_tokens.csv', header=['count']) + f.write(f"- Tokens exported (count >= {MIN_TOKEN_COUNT}): {len(top_tokens):,} " + f"covering {top_tokens.sum() / token_counts.sum():.1%} of mentions\n\n") + + f.write("## Baskets Audit: 34,569 vs 30,134\n\n") + f.write( + "The original project plan stated 30,134 baskets, whereas data-v3 produced 34,569 baskets. " + "The difference arose from how tech postings were filtered and cleaned across project stages.\n\n" + "In the initial exploratory plan, a draft filter selected 33,724 postings based on skill tags. " + "After dropping exact duplicates and empty skill lists, 30,134 rows survived. The plan assumed " + "mining baskets would match that preliminary count of 30,134 postings (comprising 13,185 generic " + "software engineer rows, 4,086 unmatched rows, and 12,863 role-labelled rows).\n\n" + "In the pipeline implementation in `etl/clean.py`, the tech filter checked 32 keywords from " + "`etl/tech_terms.txt` across both `title` and `tagsAndSkills` columns of " + "`data/raw/indian-job-market-dataset-2025.xlsx`. This broader check identified 38,271 candidate " + "tech postings. Cleaning dropped 100 exact duplicates, 80 rows with no skills after splitting, " + "and 3,522 reposts, leaving 34,569 rows saved to `data/clean.parquet`.\n\n" + "In `etl/label.py`, the `build_baskets` function created one basket per row of `data/clean.parquet`, " + "saving 34,569 records to `data/baskets.parquet`. In that file, 32,949 baskets contain one or more " + "canonical skill IDs and 1,620 contain empty lists after mapping against `artifacts/skill_vocab.json`.\n" + ) + + # Plot frequency curve + plt.figure(figsize=(10, 6)) + plt.plot(range(len(token_counts)), token_counts.values) + plt.yscale('log') + plt.title('Skill Token Frequency Curve') + plt.xlabel('Token Rank') + plt.ylabel('Frequency (log scale)') + plt.savefig('docs/token_frequency.png') + + elapsed = time.time() - t0 + write_stage_stats( + stage="profile", + rows_in=len(df), + rows_out=len(df), + drops_by_reason={}, + elapsed_seconds=elapsed, + output_files=['data/raw.parquet', 'data/top_tokens.csv'], + ) + print("Done!") + + +if __name__ == '__main__': + main() diff --git a/etl/raw.py b/etl/raw.py new file mode 100644 index 0000000..271725b --- /dev/null +++ b/etl/raw.py @@ -0,0 +1,32 @@ +import sys +import time + +from etl.paths import RAW_XLSX +from etl.stats import file_sha256, write_stage_stats + + +def check_raw(): + t0 = time.time() + if not RAW_XLSX.exists(): + print(f"Error: RAW_XLSX not found at {RAW_XLSX}", file=sys.stderr) + sys.exit(1) + + sha = file_sha256(RAW_XLSX) + print(f"RAW_XLSX: {RAW_XLSX}") + print(f"SHA256: {sha}") + + # Write stage stats + elapsed = time.time() - t0 + write_stage_stats( + stage="raw", + rows_in=97929, + rows_out=97929, + drops_by_reason={}, + elapsed_seconds=elapsed, + output_files={str(RAW_XLSX): sha}, + ) + return sha + + +if __name__ == "__main__": + check_raw() diff --git a/etl/stats.py b/etl/stats.py new file mode 100644 index 0000000..1b4db36 --- /dev/null +++ b/etl/stats.py @@ -0,0 +1,54 @@ +import hashlib +import json +from pathlib import Path +from typing import Any + +from etl.paths import REPO_ROOT, STATS_DIR + + +def file_sha256(path: str | Path) -> str: + path = Path(path) + if not path.is_absolute(): + path = REPO_ROOT / path + h = hashlib.sha256() + with open(path, "rb") as f: + while chunk := f.read(1024 * 1024): + h.update(chunk) + return h.hexdigest() + + +def write_stage_stats( + stage: str, + rows_in: int, + rows_out: int, + drops_by_reason: dict[str, int], + elapsed_seconds: float, + output_files: list[str | Path] | dict[str, str], +) -> Path: + STATS_DIR.mkdir(parents=True, exist_ok=True) + stats_file = STATS_DIR / f"{stage}.json" + + sha256_map: dict[str, str] = {} + if isinstance(output_files, dict): + sha256_map = dict(output_files) + else: + for out in output_files: + p = Path(out) + rel_str = str(p.relative_to(REPO_ROOT)) if p.is_absolute() and p.is_relative_to(REPO_ROOT) else str(p) + if p.exists() or (REPO_ROOT / p).exists(): + sha256_map[rel_str] = file_sha256(p) + + payload: dict[str, Any] = { + "stage": stage, + "rows_in": int(rows_in), + "rows_out": int(rows_out), + "drops_by_reason": {str(k): int(v) for k, v in drops_by_reason.items()}, + "elapsed_seconds": round(float(elapsed_seconds), 4), + "output_files": sha256_map, + "sha256": sha256_map, + } + + with open(stats_file, "w") as f: + json.dump(payload, f, indent=2) + + return stats_file diff --git a/fixtures/classifier.pkl b/fixtures/classifier.pkl deleted file mode 100644 index 06f2d9a5a3a8eb0dc717bae6e0403c8d7b6a30f1..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 1357 zcmcJP%Syvg5QdeuP!LzXz**K!1vhToXssa8T3cO*G)*M*N|GvF2)Ymzvh(N@_@Mru zHsC^}5gquL>AB49Omka#*{`g8NLF>-kr$0!*JkU7-XLhlK|k`-No=3(=AFHu~=5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ab.json +++ /dev/null @@ -1,42 +0,0 @@ -{ - "python": 0, - "java": 1, - "c++": 2, - "javascript": 3, - "typescript": 4, - "react": 5, - "angular": 6, - "vue.js": 7, - "node.js": 8, - "django": 9, - "flask": 10, - "fastapi": 11, - "spring boot": 12, - "sql": 13, - "postgresql": 14, - "mysql": 15, - "mongodb": 16, - "redis": 17, - "elasticsearch": 18, - "aws": 19, - "azure": 20, - "google cloud": 21, - "docker": 22, - "kubernetes": 23, - "terraform": 24, - "jenkins": 25, - "git": 26, - "linux": 27, - "bash": 28, - "machine learning": 29, - "deep learning": 30, - "tensorflow": 31, - "pytorch": 32, - "scikit-learn": 33, - "pandas": 34, - "numpy": 35, - "data analysis": 36, - "data engineering": 37, - "apache spark": 38, - "apache kafka": 39 -} \ No newline at end of file diff --git a/fixtures/skills_autocomplete.json b/fixtures/skills_autocomplete.json deleted file mode 100644 index e9e10cf..0000000 --- a/fixtures/skills_autocomplete.json +++ /dev/null @@ -1,242 +0,0 @@ -[ - { - "id": 0, - "name": "python", - "display": "Python", - "aliases": [] - }, - { - "id": 1, - "name": "java", - "display": "Java", - "aliases": [] - }, - { - "id": 2, - "name": "c++", - "display": "C++", - "aliases": [] - }, - { - "id": 3, - "name": "javascript", - "display": "Javascript", - "aliases": [] - }, - { - "id": 4, - "name": "typescript", - "display": "Typescript", - "aliases": [] - }, - { - "id": 5, - "name": "react", - "display": "React", - "aliases": [] - }, - { - "id": 6, - "name": "angular", - "display": "Angular", - "aliases": [] - }, - { - "id": 7, - "name": "vue.js", - "display": "Vue.Js", - "aliases": [] - }, - { - "id": 8, - "name": "node.js", - "display": "Node.Js", - "aliases": [] - }, - { - "id": 9, - "name": "django", - "display": "Django", - "aliases": [] - }, - { - "id": 10, - "name": "flask", - "display": "Flask", - "aliases": [] - }, - { - "id": 11, - "name": "fastapi", - "display": "Fastapi", - "aliases": [] - }, - { - "id": 12, - "name": "spring boot", - "display": "Spring Boot", - "aliases": [] - }, - { - "id": 13, - "name": "sql", - "display": "Sql", - "aliases": [] - }, - { - "id": 14, - "name": "postgresql", - "display": "Postgresql", - "aliases": [] - }, - { - "id": 15, - "name": "mysql", - "display": "Mysql", - "aliases": [] - }, - { - "id": 16, - "name": "mongodb", - "display": "Mongodb", - "aliases": [] - }, - { - "id": 17, - "name": "redis", - "display": "Redis", - "aliases": [] - }, - { - "id": 18, - "name": "elasticsearch", - "display": "Elasticsearch", - "aliases": [] - }, - { - "id": 19, - "name": "aws", - "display": "Aws", - "aliases": [] - }, - { - "id": 20, - "name": "azure", - "display": "Azure", - "aliases": [] - }, - { - "id": 21, - "name": "google cloud", - "display": "Google Cloud", - "aliases": [] - }, - { - "id": 22, - "name": "docker", - "display": "Docker", - "aliases": [] - }, - { - "id": 23, - "name": "kubernetes", - "display": "Kubernetes", - "aliases": [] - }, - { - "id": 24, - "name": "terraform", - "display": "Terraform", - "aliases": [] - }, - { - "id": 25, - "name": "jenkins", - "display": "Jenkins", - "aliases": [] - }, - { - "id": 26, - "name": "git", - "display": "Git", - "aliases": [] - }, - { - "id": 27, - "name": "linux", - "display": "Linux", - "aliases": [] - }, - { - "id": 28, - "name": "bash", - "display": "Bash", - "aliases": [] - }, - { - "id": 29, - "name": "machine learning", - "display": "Machine Learning", - "aliases": [] - }, - { - "id": 30, - "name": "deep learning", - "display": "Deep Learning", - "aliases": [] - }, - { - "id": 31, - "name": "tensorflow", - "display": "Tensorflow", - "aliases": [] - }, - { - "id": 32, - "name": "pytorch", - "display": "Pytorch", - "aliases": [] - }, - { - "id": 33, - "name": "scikit-learn", - "display": "Scikit-Learn", - "aliases": [] - }, - { - "id": 34, - "name": "pandas", - "display": "Pandas", - "aliases": [] - }, - { - "id": 35, - "name": "numpy", - "display": "Numpy", - "aliases": [] - }, - { - "id": 36, - "name": "data analysis", - "display": "Data Analysis", - "aliases": [] - }, - { - "id": 37, - "name": "data engineering", - "display": "Data Engineering", - "aliases": [] - }, - { - "id": 38, - "name": "apache spark", - "display": "Apache Spark", - "aliases": [] - }, - { - "id": 39, - "name": "apache kafka", - "display": "Apache Kafka", - "aliases": [] - } -] \ No newline at end of file diff --git a/mining/fpgrowth_bench.py b/mining/fpgrowth_bench.py index 4ffb6ef..4aeb9d3 100644 --- a/mining/fpgrowth_bench.py +++ b/mining/fpgrowth_bench.py @@ -1,3 +1,5 @@ +import json +import os import time from typing import Any @@ -12,9 +14,11 @@ def benchmark_mining( baskets_file: str = "data/baskets.parquet", min_sup_list: list[float] | None = None, sample_size: int | None = None, + output_file: str = "docs/bench.json", ) -> pd.DataFrame: """ Benchmark scratch Apriori vs mlxtend FP-Growth across multiple min_sup levels. + Saves timings to docs/bench.json and asserts identical itemsets at 2% and 1% support. """ if min_sup_list is None: min_sup_list = [0.05, 0.03, 0.02, 0.01, 0.005] @@ -40,6 +44,8 @@ def benchmark_mining( print(f"{'Min Sup':>10} | {'Itemsets':>10} | {'Apriori (s)':>12} | {'FP-growth (s)':>14} | {'Speedup (FP/Ap)':>15}") print("-" * 75) + n_baskets = len(baskets) + for min_sup in min_sup_list: # 1. Apriori t0 = time.perf_counter() @@ -60,18 +66,55 @@ def benchmark_mining( f"{min_sup*100:>9.2f}% | {num_apriori:>10,} | {t_apriori:>12.3f} | {t_fpgrowth:>14.3f} | {speedup:>14.2f}x" ) + # Check equality of itemsets and support + ap_dict = {k: v / n_baskets for k, v in apriori_frequent.items()} + fp_dict = {frozenset(row["itemsets"]): float(row["support"]) for _, row in fpgrowth_res.iterrows()} + + is_equal_sets = set(ap_dict.keys()) == set(fp_dict.keys()) + max_diff = 0.0 + if is_equal_sets: + for k, v in ap_dict.items(): + diff = abs(v - fp_dict[k]) + max_diff = max(max_diff, diff) + + is_identical = is_equal_sets and max_diff <= 1e-12 + + # Assert at 2% and 1% support as required by STEP 6 + if round(min_sup, 4) in (0.02, 0.01): + assert is_equal_sets, ( + f"Itemsets mismatch at min_sup={min_sup}: " + f"Apriori={len(ap_dict)}, FP-growth={len(fp_dict)}" + ) + for k, v in ap_dict.items(): + diff = abs(v - fp_dict[k]) + assert diff <= 1e-12, ( + f"Support mismatch at min_sup={min_sup} for {k}: {diff} > 1e-12" + ) + results.append( { "min_sup_pct": f"{min_sup*100:.2f}%", "min_sup": min_sup, + "support": min_sup, + "itemsets": num_apriori, "apriori_itemsets": num_apriori, "fpgrowth_itemsets": num_fp, "apriori_time_sec": round(t_apriori, 4), "fpgrowth_time_sec": round(t_fpgrowth, 4), + "apriori_s": round(t_apriori, 4), + "fpgrowth_s": round(t_fpgrowth, 4), "speedup": round(speedup, 2), + "identical": "yes" if is_identical else "no", + "max_support_diff": max_diff, } ) + # Save timings to docs/bench.json + os.makedirs(os.path.dirname(output_file), exist_ok=True) + with open(output_file, "w") as f: + json.dump(results, f, indent=2) + print(f"\nSaved benchmark timings to {output_file}") + res_df = pd.DataFrame(results) return res_df diff --git a/mining/rules.py b/mining/rules.py index 7046f25..2ef9fca 100644 --- a/mining/rules.py +++ b/mining/rules.py @@ -1,9 +1,12 @@ import os +import time from itertools import combinations from typing import Any import pandas as pd +from etl.stats import write_stage_stats + def generate_rules( frequent_itemsets: dict[frozenset, int], @@ -96,8 +99,7 @@ def run_rule_mining( Full pipeline to mine frequent itemsets and generate association rules. Uses FP-growth for speed and aggressively prunes to keep artifacts lean. """ - import time - + t_start = time.time() from mlxtend.frequent_patterns import fpgrowth from mlxtend.preprocessing import TransactionEncoder @@ -105,6 +107,7 @@ def run_rule_mining( df = pd.read_parquet(baskets_file) baskets = [list(skill_ids) for skill_ids in df["skill_ids"] if len(skill_ids) > 0] total_baskets = len(baskets) + empty_baskets = len(df) - total_baskets print("Encoding transactions for FP-Growth...") te = TransactionEncoder() @@ -125,13 +128,26 @@ def run_rule_mining( print(f"Generating rules with min_confidence={min_confidence}, min_lift={min_lift}...") rules_df = generate_rules(frequent_itemsets, total_baskets, min_confidence, min_lift) + initial_rules_count = len(rules_df) + pruned_count = 0 # Hard pruning step to prevent bloated artifacts if len(rules_df) > max_rules: print(f"Pruning {len(rules_df):,} rules down to top {max_rules:,} by lift & confidence...") rules_df = rules_df.head(max_rules) + pruned_count = initial_rules_count - len(rules_df) save_rules(rules_df, output_rules_file) + + elapsed = time.time() - t_start + write_stage_stats( + stage="rules", + rows_in=len(df), + rows_out=len(rules_df), + drops_by_reason={"empty_baskets": empty_baskets, "pruned_rules": pruned_count}, + elapsed_seconds=elapsed, + output_files=[output_rules_file], + ) return rules_df diff --git a/ml/export_runtime.py b/ml/export_runtime.py index 0481579..26e6c23 100644 --- a/ml/export_runtime.py +++ b/ml/export_runtime.py @@ -1,11 +1,13 @@ import hashlib import json import pickle +import time import numpy as np import pandas as pd from etl.paths import ARTIFACTS_DIR +from etl.stats import write_stage_stats def softmax(x): @@ -75,6 +77,19 @@ def export_rules(): with open(ARTIFACTS_DIR / "rules.json", "w") as f: json.dump(rules_json, f, indent=2) -if __name__ == "__main__": +def main(): + t0 = time.time() export_model() export_rules() + elapsed = time.time() - t0 + write_stage_stats( + stage="export", + rows_in=2, + rows_out=2, + drops_by_reason={}, + elapsed_seconds=elapsed, + output_files=[ARTIFACTS_DIR / "model.json", ARTIFACTS_DIR / "rules.json"], + ) + +if __name__ == "__main__": + main() diff --git a/ml/train.py b/ml/train.py index 1b7516a..b6e2a6a 100644 --- a/ml/train.py +++ b/ml/train.py @@ -18,6 +18,7 @@ from sklearn.model_selection import train_test_split from sklearn.preprocessing import LabelEncoder +from etl.stats import write_stage_stats from ml import augment, evaluate, features DATASET_PATH = os.path.join("data", "dataset.parquet") @@ -125,11 +126,35 @@ def main(): pickle.dump(le, f) with open(os.path.join(ARTIFACTS_DIR, "role_profiles.json"), "w") as f: json.dump(build_role_profiles(train, vocab), f, indent=2) - with open(os.path.join(ARTIFACTS_DIR, "metrics.json"), "w") as f: + metrics_path = os.path.join(ARTIFACTS_DIR, "metrics.json") + if os.path.exists(metrics_path): + try: + with open(metrics_path, "r") as f: + saved = json.load(f) + saved.update(report) + report = saved + except (json.JSONDecodeError, OSError) as e: + print(f"[warn] Could not load existing metrics.json: {e}") + with open(metrics_path, "w") as f: json.dump(report, f, indent=2) evaluate.print_report(report) - print(f"Artifacts written to {ARTIFACTS_DIR}/ in {time.time() - t0:.1f}s") + elapsed = time.time() - t0 + print(f"Artifacts written to {ARTIFACTS_DIR}/ in {elapsed:.1f}s") + + write_stage_stats( + stage="train", + rows_in=len(df) + dropped_rows, + rows_out=len(df), + drops_by_reason={"no_skill_ids": dropped_rows}, + elapsed_seconds=elapsed, + output_files=[ + os.path.join(ARTIFACTS_DIR, "classifier.pkl"), + os.path.join(ARTIFACTS_DIR, "label_encoder.pkl"), + os.path.join(ARTIFACTS_DIR, "role_profiles.json"), + os.path.join(ARTIFACTS_DIR, "metrics.json"), + ], + ) if __name__ == "__main__": diff --git a/scripts/fetch_artifacts.py b/scripts/fetch_artifacts.py deleted file mode 100644 index d7aa703..0000000 --- a/scripts/fetch_artifacts.py +++ /dev/null @@ -1,26 +0,0 @@ -import os -import urllib.error -import urllib.request - -os.makedirs('artifacts', exist_ok=True) - -files = { - 'rules-v1': ['rules.parquet'], - 'model-v3': [ - 'classifier.pkl', 'label_encoder.pkl', 'role_profiles.json', - 'skills_autocomplete.json', 'skill_vocab.json' - ] -} - -for release, filenames in files.items(): - for filename in filenames: - url = f"https://github.com/AtulACleaver/SkillGraph/releases/download/{release}/{filename}" - print(f"Downloading {filename} from {release}...") - try: - req = urllib.request.Request(url, headers={'User-Agent': 'Mozilla/5.0'}) - with urllib.request.urlopen(req) as response, open(os.path.join('artifacts', filename), 'wb') as f: - f.write(response.read()) - except urllib.error.URLError as e: - print(f"Failed to download {filename}: {e}") - -print("Done fetching artifacts!") diff --git a/scripts/fetch_artifacts.sh b/scripts/fetch_artifacts.sh deleted file mode 100644 index d265666..0000000 --- a/scripts/fetch_artifacts.sh +++ /dev/null @@ -1,3 +0,0 @@ -#!/bin/bash -set -e -python scripts/fetch_artifacts.py diff --git a/scripts/make_fixtures.py b/scripts/make_fixtures.py deleted file mode 100644 index 9b530d3..0000000 --- a/scripts/make_fixtures.py +++ /dev/null @@ -1,106 +0,0 @@ -import json -import os -import pickle -import random - -import numpy as np -import pandas as pd - - -class FakePredictor: - def __init__(self, classes): - self.classes_ = np.array(classes) - - def predict_proba(self, X): - n_samples = getattr(X, 'shape', [1])[0] if hasattr(X, 'shape') else len(X) if isinstance(X, list) else 1 - probs = np.random.dirichlet(np.ones(len(self.classes_)) * 0.5, size=n_samples) - return probs - - def predict(self, X): - probs = self.predict_proba(X) - indices = np.argmax(probs, axis=1) - return self.classes_[indices] - -class FakeLabelEncoder: - def __init__(self, classes): - self.classes_ = np.array(classes) - - def transform(self, y): - return np.array([list(self.classes_).index(item) for item in y]) - - def inverse_transform(self, y): - return self.classes_[y] - -def create_fixtures(output_dir="fixtures"): - os.makedirs(output_dir, exist_ok=True) - - # 1. skill_vocab.json - 40 real-sounding skills - skills = [ - "Python", "Java", "C++", "JavaScript", "TypeScript", "React", "Angular", - "Vue.js", "Node.js", "Django", "Flask", "FastAPI", "Spring Boot", - "SQL", "PostgreSQL", "MySQL", "MongoDB", "Redis", "Elasticsearch", - "AWS", "Azure", "Google Cloud", "Docker", "Kubernetes", "Terraform", - "Jenkins", "Git", "Linux", "Bash", "Machine Learning", "Deep Learning", - "TensorFlow", "PyTorch", "Scikit-Learn", "Pandas", "NumPy", "Data Analysis", - "Data Engineering", "Apache Spark", "Apache Kafka" - ] - - # Map each skill to an ID - skill_vocab = {skill.lower(): i for i, skill in enumerate(skills)} - - with open(os.path.join(output_dir, "skill_vocab.json"), "w") as f: - json.dump(skill_vocab, f, indent=4) - - # 2. role_profiles.json - Role families from Aryan's list - # Read the role families from data/role_families.csv if it exists - csv_path = os.path.join(os.path.dirname(os.path.dirname(__file__)), "data", "role_families.csv") - if os.path.exists(csv_path): - df_roles = pd.read_csv(csv_path) - role_families = df_roles["role_family"].tolist() - else: - role_families = [ - "Data Science / ML", "Data / BI Analyst", "DevOps / Cloud", - "QA / Test", "ERP / Enterprise", "Mobile", "Full Stack", - "Frontend", "Backend", "Support / IT Ops", "Software Engineer (generic)" - ] - - role_profiles = {} - for role in role_families: - num_skills = random.randint(5, 10) - role_skills = random.sample(skills, num_skills) - role_profiles[role] = { - "n_postings": random.randint(500, 5000), - "top_skills": role_skills - } - - with open(os.path.join(output_dir, "role_profiles.json"), "w") as f: - json.dump(role_profiles, f, indent=4) - - # 3. rules.parquet - 200 plausible rules - rules_data = [] - for _ in range(200): - skill = random.choice(skills) - role = random.choice(role_families) - learn_with = random.sample([s for s in skills if s != skill], k=random.randint(1, 3)) - rules_data.append({ - "skill": skill, - "role": role, - "coverage_pct": round(random.uniform(0.1, 0.9), 2), - "readiness_gain": round(random.uniform(0.05, 0.3), 2), - "learn_with": learn_with - }) - - df = pd.DataFrame(rules_data) - df.to_parquet(os.path.join(output_dir, "rules.parquet")) - - # 4. Predictor and Label Encoder - predictor = FakePredictor(role_families) - with open(os.path.join(output_dir, "classifier.pkl"), "wb") as f: - pickle.dump(predictor, f) - - label_encoder = FakeLabelEncoder(role_families) - with open(os.path.join(output_dir, "label_encoder.pkl"), "wb") as f: - pickle.dump(label_encoder, f) - print("Fixtures generated successfully in 'fixtures/' directory!") -if __name__ == "__main__": - create_fixtures()