LocationBasedServices/smartguide/pipeline/pr-dev There was a failure building this commit
144 lines
4.7 KiB
Python
144 lines
4.7 KiB
Python
#!/usr/bin/env python3
|
|
"""
|
|
build_patents_openalex_keywords.py — Build IPC/CPC → OpenAlex topic/keyword matches.
|
|
|
|
Fetches IPC/CPC metadata from the `ipc` index, matches labels against OpenAlex topics
|
|
(from topic_hierarchy_cache.json) and keywords (from openalex-topics) using
|
|
SentenceTransformer embeddings, then writes results to the patents_openalex_keywords
|
|
Elasticsearch index and a local JSON backup.
|
|
|
|
Usage:
|
|
python scripts/build_patents_openalex_keywords.py
|
|
python scripts/build_patents_openalex_keywords.py --top-k 3 --min-score 0.55
|
|
python scripts/build_patents_openalex_keywords.py --levels section class subclass
|
|
python scripts/build_patents_openalex_keywords.py --skip-keywords
|
|
|
|
Requires src/main/inse/.env with PATENT_ELASTICSEARCH credentials (INSE) and, unless
|
|
--skip-keywords is set, NES Elasticsearch credentials for openalex-topics.
|
|
"""
|
|
from __future__ import annotations
|
|
|
|
import argparse
|
|
import asyncio
|
|
import json
|
|
import logging
|
|
import sys
|
|
from pathlib import Path
|
|
|
|
current_dir = Path(__file__).resolve().parent
|
|
sys.path.insert(0, str(current_dir.parent / "src" / "main"))
|
|
|
|
from inse.patents.patents_openalex_keywords.client import PatentsOpenAlexKeywordsClient
|
|
from inse.patents.patents_openalex_keywords.ipc_entries import (
|
|
DEFAULT_BUILD_LEVELS,
|
|
fetch_unique_ipc_entries,
|
|
)
|
|
from inse.patents.patents_openalex_keywords.matching import (
|
|
TopicVectorsMatcher,
|
|
build_documents_from_topicvectors,
|
|
documents_to_json_mapping,
|
|
)
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
|
|
async def run(args: argparse.Namespace) -> None:
|
|
levels = tuple(args.levels)
|
|
|
|
ipc_entries = await fetch_unique_ipc_entries(levels=levels)
|
|
counts = {level: len(ipc_entries.get(level, {})) for level in levels}
|
|
logger.info("Fetched unique IPC/CPC symbols: %s", counts)
|
|
|
|
if args.skip_keywords:
|
|
logger.info("--skip-keywords is ignored in topicvectors mode")
|
|
if args.topic_cache:
|
|
logger.info("--topic-cache is ignored in topicvectors mode")
|
|
if args.batch_size != 64:
|
|
logger.info("--batch-size is ignored in topicvectors mode")
|
|
|
|
matcher = TopicVectorsMatcher(min_score=args.min_score)
|
|
logger.info("Matching IPC/CPC labels against topicvectors index...")
|
|
documents = await build_documents_from_topicvectors(
|
|
ipc_entries, matcher, levels=levels, top_k=args.top_k
|
|
)
|
|
logger.info("Built %d IPC/CPC mapping documents", len(documents))
|
|
|
|
if args.output:
|
|
output_path = Path(args.output)
|
|
output_path.parent.mkdir(parents=True, exist_ok=True)
|
|
mapping = documents_to_json_mapping(documents)
|
|
output_path.write_text(
|
|
json.dumps(mapping, indent=2, ensure_ascii=True),
|
|
encoding="utf-8",
|
|
)
|
|
logger.info("Wrote local JSON backup to %s", output_path)
|
|
|
|
if not args.dry_run:
|
|
client = PatentsOpenAlexKeywordsClient(timeout=60.0)
|
|
await client.ensure_index()
|
|
await client.bulk_index(documents)
|
|
logger.info("Indexed %d documents into patents_openalex_keywords", len(documents))
|
|
else:
|
|
logger.info("Dry run — skipped Elasticsearch indexing")
|
|
|
|
|
|
def main() -> None:
|
|
parser = argparse.ArgumentParser(
|
|
description="Build IPC/CPC → OpenAlex topic/keyword matches with SentenceTransformer.",
|
|
)
|
|
parser.add_argument(
|
|
"--output",
|
|
default=str(
|
|
current_dir.parent / "src" / "data" / "patents_openalex_keywords_mapping.json"
|
|
),
|
|
help="Local JSON backup path",
|
|
)
|
|
parser.add_argument(
|
|
"--topic-cache",
|
|
default=None,
|
|
help="Deprecated in topicvectors mode (kept for CLI compatibility)",
|
|
)
|
|
parser.add_argument(
|
|
"--levels",
|
|
nargs="+",
|
|
default=list(DEFAULT_BUILD_LEVELS),
|
|
choices=list(DEFAULT_BUILD_LEVELS),
|
|
help="IPC/CPC hierarchy levels to map",
|
|
)
|
|
parser.add_argument(
|
|
"--top-k",
|
|
type=int,
|
|
default=3,
|
|
help="Number of top topic/keyword matches per IPC/CPC code",
|
|
)
|
|
parser.add_argument(
|
|
"--min-score",
|
|
type=float,
|
|
default=0.5,
|
|
help="Minimum cosine similarity for a match",
|
|
)
|
|
parser.add_argument(
|
|
"--batch-size",
|
|
type=int,
|
|
default=64,
|
|
help="Deprecated in topicvectors mode (kept for CLI compatibility)",
|
|
)
|
|
parser.add_argument(
|
|
"--skip-keywords",
|
|
action="store_true",
|
|
help="Deprecated in topicvectors mode (kept for CLI compatibility)",
|
|
)
|
|
parser.add_argument(
|
|
"--dry-run",
|
|
action="store_true",
|
|
help="Build matches locally without indexing into Elasticsearch",
|
|
)
|
|
args = parser.parse_args()
|
|
|
|
logging.basicConfig(level=logging.INFO, format="%(levelname)s %(message)s")
|
|
asyncio.run(run(args))
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|