LocationBasedServices/smartguide/pipeline/head This commit looks good
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
187 lines
6.6 KiB
Python
187 lines
6.6 KiB
Python
import csv
|
|
import json
|
|
from collections import Counter
|
|
from pathlib import Path
|
|
from typing import Any
|
|
|
|
from openalex_client import get_all_author_works
|
|
|
|
BASE_DIR = Path(__file__).resolve().parent
|
|
INPUT_FILE = BASE_DIR / "research_timeline_sample.csv"
|
|
DETAILS_DIR = BASE_DIR / "per_person_details"
|
|
SUMMARY_FILE = BASE_DIR / "keyword_vs_topic_summary.csv"
|
|
TOP_TERMS_FILE = BASE_DIR / "top_terms_by_person.csv"
|
|
|
|
SELECT_FIELDS = "id,title,publication_year,keywords,topics,primary_topic"
|
|
TOP_N_TERMS = 15
|
|
|
|
|
|
def extract_work_record(work: dict[str, Any]) -> dict[str, Any]:
|
|
"""
|
|
Reduces one OpenAlex work to the fields relevant for comparing keywords
|
|
against topics per publication year.
|
|
"""
|
|
keywords = [kw.get("display_name") for kw in (work.get("keywords") or [])]
|
|
topics = [t.get("display_name") for t in (work.get("topics") or [])]
|
|
primary_topic = (work.get("primary_topic") or {}).get("display_name")
|
|
|
|
return {
|
|
"year": work.get("publication_year"),
|
|
"title": work.get("title"),
|
|
"keywords": keywords,
|
|
"topics": topics,
|
|
"primary_topic": primary_topic,
|
|
}
|
|
|
|
|
|
def group_by_year(records: list[dict[str, Any]]) -> dict[int, list[dict[str, Any]]]:
|
|
by_year: dict[int, list[dict[str, Any]]] = {}
|
|
|
|
for record in records:
|
|
year = record["year"]
|
|
if not isinstance(year, int):
|
|
continue
|
|
by_year.setdefault(year, []).append(record)
|
|
|
|
return dict(sorted(by_year.items()))
|
|
|
|
|
|
def summarize_terms(records: list[dict[str, Any]], field: str) -> dict[str, Any]:
|
|
"""
|
|
Computes basic descriptive stats for a term field (keywords or topics)
|
|
across all works of one person.
|
|
|
|
`distinct_ratio` = distinct terms / total term mentions. A low ratio
|
|
means the same terms keep reappearing across many works; a high ratio
|
|
means most mentions are of a term not seen elsewhere.
|
|
"""
|
|
all_terms: list[str] = []
|
|
per_work_counts: list[int] = []
|
|
|
|
for record in records:
|
|
terms = record[field]
|
|
per_work_counts.append(len(terms))
|
|
all_terms.extend(terms)
|
|
|
|
total_mentions = len(all_terms)
|
|
distinct_terms = len(set(all_terms))
|
|
avg_per_work = total_mentions / len(records) if records else 0.0
|
|
distinct_ratio = distinct_terms / total_mentions if total_mentions else 0.0
|
|
|
|
counter = Counter(all_terms)
|
|
top_terms = counter.most_common(TOP_N_TERMS)
|
|
|
|
return {
|
|
"total_mentions": total_mentions,
|
|
"distinct_terms": distinct_terms,
|
|
"avg_per_work": round(avg_per_work, 2),
|
|
"distinct_ratio": round(distinct_ratio, 3),
|
|
"top_terms": top_terms,
|
|
}
|
|
|
|
|
|
def analyze_sample() -> None:
|
|
if not INPUT_FILE.exists():
|
|
raise FileNotFoundError(f"Input file not found: {INPUT_FILE}")
|
|
|
|
DETAILS_DIR.mkdir(exist_ok=True)
|
|
|
|
summary_rows: list[dict[str, Any]] = []
|
|
top_terms_rows: list[dict[str, Any]] = []
|
|
|
|
with INPUT_FILE.open(mode="r", encoding="utf-8", newline="") as input_file:
|
|
reader = csv.DictReader(input_file)
|
|
|
|
for row in reader:
|
|
name = row.get("name", "").strip()
|
|
openalex_author_id = row.get("openalex_author_id", "").strip()
|
|
|
|
if not openalex_author_id:
|
|
print(f"Skipping {name}: missing OpenAlex author ID")
|
|
continue
|
|
|
|
print(f"Fetching works for {name} ({openalex_author_id})...")
|
|
|
|
try:
|
|
works = get_all_author_works(openalex_author_id, select=SELECT_FIELDS)
|
|
except Exception as error:
|
|
print(f"Error while processing {name}: {error}")
|
|
continue
|
|
|
|
records = [extract_work_record(work) for work in works]
|
|
by_year = group_by_year(records)
|
|
|
|
details_path = DETAILS_DIR / f"{name.replace(' ', '_')}.json"
|
|
with details_path.open(mode="w", encoding="utf-8") as details_file:
|
|
json.dump(by_year, details_file, indent=2, ensure_ascii=False)
|
|
|
|
keyword_stats = summarize_terms(records, "keywords")
|
|
topic_stats = summarize_terms(records, "topics")
|
|
|
|
summary_rows.append(
|
|
{
|
|
"name": name,
|
|
"openalex_author_id": openalex_author_id,
|
|
"work_count": len(records),
|
|
"years_covered": len(by_year),
|
|
"avg_keywords_per_work": keyword_stats["avg_per_work"],
|
|
"distinct_keywords": keyword_stats["distinct_terms"],
|
|
"keyword_distinct_ratio": keyword_stats["distinct_ratio"],
|
|
"avg_topics_per_work": topic_stats["avg_per_work"],
|
|
"distinct_topics": topic_stats["distinct_terms"],
|
|
"topic_distinct_ratio": topic_stats["distinct_ratio"],
|
|
}
|
|
)
|
|
|
|
for rank, (term, count) in enumerate(keyword_stats["top_terms"], start=1):
|
|
top_terms_rows.append(
|
|
{
|
|
"name": name,
|
|
"field": "keyword",
|
|
"rank": rank,
|
|
"term": term,
|
|
"work_count": count,
|
|
}
|
|
)
|
|
for rank, (term, count) in enumerate(topic_stats["top_terms"], start=1):
|
|
top_terms_rows.append(
|
|
{
|
|
"name": name,
|
|
"field": "topic",
|
|
"rank": rank,
|
|
"term": term,
|
|
"work_count": count,
|
|
}
|
|
)
|
|
|
|
with SUMMARY_FILE.open(mode="w", encoding="utf-8", newline="") as summary_file:
|
|
fieldnames = [
|
|
"name",
|
|
"openalex_author_id",
|
|
"work_count",
|
|
"years_covered",
|
|
"avg_keywords_per_work",
|
|
"distinct_keywords",
|
|
"keyword_distinct_ratio",
|
|
"avg_topics_per_work",
|
|
"distinct_topics",
|
|
"topic_distinct_ratio",
|
|
]
|
|
writer = csv.DictWriter(summary_file, fieldnames=fieldnames)
|
|
writer.writeheader()
|
|
writer.writerows(summary_rows)
|
|
|
|
with TOP_TERMS_FILE.open(mode="w", encoding="utf-8", newline="") as top_terms_file:
|
|
fieldnames = ["name", "field", "rank", "term", "work_count"]
|
|
writer = csv.DictWriter(top_terms_file, fieldnames=fieldnames)
|
|
writer.writeheader()
|
|
writer.writerows(top_terms_rows)
|
|
|
|
print(f"Analysis finished. Summary written to {SUMMARY_FILE}")
|
|
print(f"Top terms written to {TOP_TERMS_FILE}")
|
|
print(f"Per-person year/keyword/topic details written to {DETAILS_DIR}/")
|
|
|
|
|
|
if __name__ == "__main__":
|
|
analyze_sample()
|