Datasets:

GiliGold commited on
Commit
b419176
·
verified ·
1 Parent(s): b8f009e

Upload knessetCorpus.py

Browse files
Files changed (1) hide show
  1. knessetCorpus.py +35 -124
knessetCorpus.py CHANGED
@@ -1,14 +1,9 @@
1
-
2
- import datasets
3
  import json
4
- import zipfile
5
- import bz2
6
  import os
7
- import urllib.request
8
- from io import BytesIO
9
 
10
-
11
- from typing import List, Dict, Any, Generator
12
 
13
 
14
  _KnessetCorpus_CITATION = "@misc{goldin2024knesset, title={The Knesset Corpus: An Annotated Corpus of Hebrew Parliamentary Proceedings}, author={Gili Goldin and Nick Howell and Noam Ordan and Ella Rabinovich and Shuly Wintner}, year={2024}, eprint={2405.18115}, archivePrefix={arXiv}, primaryClass={cs.CL} }"
@@ -359,124 +354,40 @@ class KnessetCorpus(datasets.GeneratorBasedBuilder):
359
  elif self.config.name == "knessetMembers":
360
  id_field_name = "person_id"
361
 
362
- for filepath in data_files:
363
- if '::' in filepath: # Handle URLs with protocol prefixes
364
- _, url = filepath.split('::', 1)
365
- try:
366
- response = urllib.request.urlopen(url)
367
- content = response.read()
368
- if filepath.endswith('.zip'):
369
- yield from self._process_zip_content(content, id_field_name, url)
370
- elif filepath.endswith('.bz2'):
371
- yield from self._process_bz2_content(content, id_field_name, url)
372
- except Exception as e:
373
- print(f"Error downloading {url}: {e}")
374
- else: # Handle local files
375
- if filepath.endswith('.zip'):
376
- yield from self._process_zip_file(filepath, id_field_name)
377
- elif filepath.endswith('.bz2'):
378
- yield from self._process_bz2_file(filepath, id_field_name)
379
- else:
380
- print(f"Unsupported file format: {filepath}")
381
-
382
- def _process_zip_content(self, content: bytes, id_field_name: str, url: str) -> Generator[tuple, None, None]:
383
- try:
384
- with zipfile.ZipFile(BytesIO(content)) as zip_ref:
385
- for file_info in zip_ref.filelist:
386
- if not file_info.filename.endswith('.json'):
387
- continue
388
-
389
- with zip_ref.open(file_info) as f:
390
- content = f.read().decode('utf-8')
391
- for line in content.splitlines():
392
- if not line.strip():
393
- continue
394
-
395
  try:
396
- row = json.loads(line)
397
- except json.JSONDecodeError as e:
398
- print(f"JSON decode error in zip file from {url}, file {file_info.filename}: {e}")
399
- continue
400
-
401
- yield from self._process_row(row, id_field_name)
402
-
403
- except Exception as e:
404
- print(f"Error processing zip content from {url}: {e}")
405
-
406
- def _process_bz2_content(self, content: bytes, id_field_name: str, url: str) -> Generator[tuple, None, None]:
407
- try:
408
- decompressed = bz2.decompress(content).decode('utf-8')
409
- for line in decompressed.splitlines():
410
- if not line.strip():
411
- continue
412
-
413
- try:
414
- row = json.loads(line)
415
- except json.JSONDecodeError as e:
416
- print(f"JSON decode error in bz2 content from {url}: {e}")
417
- continue
418
-
419
- yield from self._process_row(row, id_field_name)
420
-
421
- except Exception as e:
422
- print(f"Error processing bz2 content from {url}: {e}")
423
-
424
- def _process_zip_file(self, filepath: str, id_field_name: str) -> Generator[tuple, None, None]:
425
- try:
426
- with zipfile.ZipFile(filepath, 'r') as zip_ref:
427
- for file_info in zip_ref.filelist:
428
- if not file_info.filename.endswith('.json'):
429
- continue
430
-
431
- with zip_ref.open(file_info) as f:
432
- content = f.read().decode('utf-8')
433
- for line in content.splitlines():
434
- if not line.strip():
435
- continue
436
 
437
- try:
438
- row = json.loads(line)
439
- except json.JSONDecodeError as e:
440
- print(f"JSON decode error in zip file {filepath}, file {file_info.filename}: {e}")
441
- continue
442
-
443
- yield from self._process_row(row, id_field_name)
444
-
445
- except Exception as e:
446
- print(f"Error opening zip file {filepath}: {e}")
447
-
448
- def _process_bz2_file(self, filepath: str, id_field_name: str) -> Generator[tuple, None, None]:
449
- try:
450
- with bz2.open(filepath, 'rt', encoding='utf-8') as f:
451
- for line in f:
452
- if not line.strip():
453
- continue
454
-
455
- try:
456
- row = json.loads(line)
457
- except json.JSONDecodeError as e:
458
- print(f"JSON decode error in bz2 file {filepath}: {e}")
459
- continue
460
-
461
- yield from self._process_row(row, id_field_name)
462
-
463
- except Exception as e:
464
- print(f"Error opening bz2 file {filepath}: {e}")
465
-
466
- def _process_row(self, row: Dict[str, Any], id_field_name: str) -> Generator[tuple, None, None]:
467
- id_ = row.get(id_field_name)
468
- if id_ is None:
469
- print(f"Key '{id_field_name}' not found in row. Skipping this row. row is: {row}")
470
- return
471
-
472
- if "protocol_sentences" in row:
473
- for sentence in row.get("protocol_sentences", []):
474
- sentence_id = sentence.get("sentence_id")
475
- if sentence_id:
476
- yield sentence_id, sentence
477
- else:
478
- sample = {feature: row[feature] for feature in self._info().features if feature in row}
479
- yield id_, sample
480
 
481
 
482
 
 
 
 
1
  import json
 
 
2
  import os
3
+ from typing import List
4
+ from huggingface_hub import hf_hub_url
5
 
6
+ import datasets
 
7
 
8
 
9
  _KnessetCorpus_CITATION = "@misc{goldin2024knesset, title={The Knesset Corpus: An Annotated Corpus of Hebrew Parliamentary Proceedings}, author={Gili Goldin and Nick Howell and Noam Ordan and Ella Rabinovich and Shuly Wintner}, year={2024}, eprint={2405.18115}, archivePrefix={arXiv}, primaryClass={cs.CL} }"
 
354
  elif self.config.name == "knessetMembers":
355
  id_field_name = "person_id"
356
 
357
+ for i, filepath in enumerate(data_files):
358
+ try:
359
+ with open(filepath, encoding="utf-8") as f:
360
+ for line in f:
361
+ sample = {}
362
+ try:
363
+ row = json.loads(line)
364
+ except Exception as e:
365
+ print(f'couldnt load sample. error was: {e}. Continuing to next sample')
366
+ continue
367
+ id_ = row.get(id_field_name, None)
368
+ if id_ is None:
369
+ print(f"Key '{id_field_name}' not found in row. Skipping this row. row is: {row}")
370
+ continue
371
+ for feature in self._info().features:
372
+ sample[feature] = row[feature]
373
+
374
+ # Handle nested structures (e.g., `protocol_sentences`)
375
+ if "protocol_sentences" in row:
376
+ protocol_sentences = row.get("protocol_sentences", [])
377
+ for sentence in protocol_sentences:
378
+ sentence_id = sentence.get("sentence_id", None)
379
+ if sentence_id:
380
+ yield sentence_id, sentence
381
+ else:
 
 
 
 
 
 
 
 
382
  try:
383
+ yield id_, sample
384
+ except Exception as e:
385
+ print(f'couldnt yield sample. error: {e}. sample is: {sample}.', flush=True)
386
+ except Exception as e:
387
+ print(f"Error opening file '{filepath}': {e}. Skipping.")
388
+
389
+
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
390
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
391
 
392
 
393