| import json |
| import sys |
| import pickle |
| import logging |
|
|
| log = logging.getLogger(__name__) |
| log.addHandler(logging.FileHandler('collect.log')) |
| log.setLevel(logging.DEBUG) |
|
|
| user_agent = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/123.0.0.0 Safari/537.36' |
|
|
| def get_concepts_id(list_of_eurovoc_terms, eurovoc_dict): |
| """Get concept IDs from the preloaded eurovoc dictionary""" |
| for e in list_of_eurovoc_terms: |
| try: |
| yield eurovoc_dict[e.strip().lower()] |
| except KeyError: |
| log.warning(f"⚠️ Could not find {e} in Eurovoc") |
|
|
| def add_eurovoc_ids_to_jsonl(input_file, output_file, eurovoc_dict): |
| """Read JSONL, add eurovoc_concepts_ids, write to new file""" |
| with open(input_file, 'r') as infile, open(output_file, 'w') as outfile: |
| for line_num, line in enumerate(infile, 1): |
| line = line.strip() |
| if not line or line == 'null': |
| log.warning(f"⚠️ Skipping empty/null line {line_num}") |
| continue |
| try: |
| doc = json.loads(line) |
| if 'eurovoc_concepts' in doc: |
| |
| concept_ids = list(get_concepts_id(doc['eurovoc_concepts'], eurovoc_dict)) |
| |
| |
| if 'eurovoc_concepts' in doc: |
| doc['eurovoc_concepts_ids'] = concept_ids |
| outfile.write(json.dumps(doc) + '\n') |
| except json.JSONDecodeError as e: |
| log.error(f"⚠️ Invalid JSON at line {line_num}: {e}") |
| continue |
|
|
|
|
| if __name__ == '__main__': |
| |
| |
| with open("eurovoc_dict.pkl", "rb") as f: |
| eurovoc_dict = pickle.load(f) |
|
|
| input_file = sys.argv[1] |
| output_file = sys.argv[2] if len(sys.argv) > 2 else 'output.jsonl' |
| add_eurovoc_ids_to_jsonl(input_file, output_file, eurovoc_dict) |
| print(f"Done! Saved to {output_file}", file=sys.stderr) |