vldsavelyev commited on
Commit
141b674
·
1 Parent(s): 2d3e792

Split book by chapter. Remove tiny chapters.

Browse files
Files changed (2) hide show
  1. README.md +5 -5
  2. murakami.py +39 -79
README.md CHANGED
@@ -5,13 +5,13 @@ dataset_info:
5
  dtype: string
6
  splits:
7
  - name: train
8
- num_bytes: 18297128
9
- num_examples: 21
10
  - name: test
11
- num_bytes: 48450
12
  num_examples: 1
13
  download_size: 0
14
- dataset_size: 18345578
15
  ---
16
 
17
- Russian translations of Murakami novels, to fine-tune a generative language model. Originally downloaded from the FB2 archive http://flibusta.is/a/8570.
 
5
  dtype: string
6
  splits:
7
  - name: train
8
+ num_bytes: 18352678
9
+ num_examples: 699
10
  - name: test
11
+ num_bytes: 48421
12
  num_examples: 1
13
  download_size: 0
14
+ dataset_size: 18401099
15
  ---
16
 
17
+ Russian translations of Murakami novels, to fine-tune a generative language model. Originally downloaded from the FB2 archive http://flibusta.is/a/8570.
murakami.py CHANGED
@@ -23,6 +23,10 @@ class Builder(datasets.GeneratorBasedBuilder):
23
 
24
  VERSION = datasets.Version("1.1.0")
25
 
 
 
 
 
26
  def _info(self):
27
  return datasets.DatasetInfo(
28
  # This is the description that will appear on the datasets page.
@@ -61,22 +65,19 @@ class Builder(datasets.GeneratorBasedBuilder):
61
 
62
  def _generate_examples(self, filepaths):
63
  for fileidx, filepath in enumerate(filepaths):
64
- print(fileidx, filepath)
65
- title, text = self._extract_text_from_fb2(filepath, fileidx)
66
- yield title, {"text": text}
67
 
68
  @staticmethod
69
- def _extract_text_from_fb2(filepath: Path, fileidx: int) -> tuple[str, str]:
70
  """
71
- Parse FB2 file and return the concatenation of its paragraphs, along with the title.
72
  """
73
  # Load the FB2 format file
74
  with filepath.open("rb") as file:
75
  fb2_data = file.read()
76
 
77
- # Print structure of the FB2 format file
78
- # print(etree.tostring(etree.fromstring(fb2_data), pretty_print=True))
79
-
80
  # Parse the FB2 format file using lxml
81
  root = etree.fromstring(fb2_data)
82
 
@@ -85,79 +86,38 @@ class Builder(datasets.GeneratorBasedBuilder):
85
  "//fb:title-info/fb:book-title",
86
  namespaces={"fb": "http://www.gribuser.ru/xml/fictionbook/2.0"},
87
  )[0].text
88
- print(title)
89
 
90
- # Get all book paragraphs
91
- paragraphs = root.xpath(
92
- "//fb:p",
93
- namespaces={"fb": "http://www.gribuser.ru/xml/fictionbook/2.0"},
94
- )
95
 
96
- # UNCOMMENT THE LINE BELOW TO BUILD `START_PARAGRAPHS`:
97
- # self.helper_to_find_first_paragraphs(paragraphs, title, bi)
 
98
 
99
- found_paragraphs = []
100
- skipping = True
101
- for pi, p in enumerate(paragraphs):
102
- if p.text is None:
103
- continue
104
  if (
105
- fileidx in Builder.START_PARAGRAPHS
106
- and pi >= Builder.START_PARAGRAPHS[fileidx]
107
  ):
108
- skipping = False
109
- if skipping and p.text.lower() == title.lower():
110
- skipping = False
111
- if not skipping:
112
- found_paragraphs.append(p)
113
- print(f"Found {len(found_paragraphs)} paragraphs")
114
- text = ""
115
- for p in found_paragraphs:
116
- text += p.text.replace(" ", " ") + "\n"
117
- text += "\n"
118
- return title, text
119
-
120
- # Number of initial <p> element to take from each fb2, by number. This allows to skip
121
- # intros and other junk in the beginning of an fb2. This is built semi-manually using
122
- # the `self.helper_to_find_first_paragraphs` function.
123
- START_PARAGRAPHS = {
124
- 3: 5,
125
- 6: 27,
126
- 7: 3,
127
- 9: 4,
128
- 10: 3,
129
- 12: 11,
130
- 18: 5,
131
- 20: 3,
132
- 21: 5,
133
- }
134
-
135
- @staticmethod
136
- def helper_to_find_first_paragraphs(paragraphs, title, book_number, n=30):
137
- """
138
- Helps to eyeball first few paragraphs of a book to skip junk paragraphs
139
- in the beginning and manually construct the `tart_paragraphs` dict.
140
- """
141
- found_paragraphs = []
142
- skipping = True
143
- for i, p in enumerate(list(paragraphs)[:n]):
144
- if p.text is None:
145
- continue
146
- if (
147
- book_number in Builder.START_PARAGRAPHS
148
- and i >= Builder.START_PARAGRAPHS[book_number]
149
- ):
150
- skipping = False
151
- if skipping and p.text.lower() == title.lower():
152
- skipping = False
153
- if not skipping:
154
- found_paragraphs.append(f" {i} {p.text}")
155
-
156
- if found_paragraphs:
157
- print("✅")
158
- print("\n".join(found_paragraphs))
159
-
160
- else:
161
- print("❌")
162
- for i, p in enumerate(list(paragraphs)[:30]):
163
- print(f" {i} {p.text}")
 
23
 
24
  VERSION = datasets.Version("1.1.0")
25
 
26
+ # Small chapters are usually the footnotes and the title of the book, skipping by default as it's
27
+ # not helping to capture the style of the author anyway.
28
+ MIN_CHAPTER_SIZE = 500
29
+
30
  def _info(self):
31
  return datasets.DatasetInfo(
32
  # This is the description that will appear on the datasets page.
 
65
 
66
  def _generate_examples(self, filepaths):
67
  for fileidx, filepath in enumerate(filepaths):
68
+ title, chapters = self._extract_text_from_fb2(filepath, fileidx)
69
+ for i, chapter in enumerate(chapters):
70
+ yield f"{title} {i}", {"text": chapter}
71
 
72
  @staticmethod
73
+ def _extract_text_from_fb2(filepath: Path, fileidx: int) -> tuple[str, list[str]]:
74
  """
75
+ Parse a FB2 file and return book chapters, along with the book title.
76
  """
77
  # Load the FB2 format file
78
  with filepath.open("rb") as file:
79
  fb2_data = file.read()
80
 
 
 
 
81
  # Parse the FB2 format file using lxml
82
  root = etree.fromstring(fb2_data)
83
 
 
86
  "//fb:title-info/fb:book-title",
87
  namespaces={"fb": "http://www.gribuser.ru/xml/fictionbook/2.0"},
88
  )[0].text
 
89
 
90
+ # UNCOMMENT THIS TO BUILD `START_PARAGRAPHS`
91
+ # helper_to_find_first_paragraphs(root, title, bi)
92
+ # continue
 
 
93
 
94
+ # All text is stored in <p> tags. There are also <section> tags, which do not have any content,
95
+ # but serve as chapters separators. So we will merge all <p> tags contents between two <section>.
96
+ chapters: list[str] = []
97
 
98
+ def _add_chapter(text: str):
99
+ if not text:
100
+ return
 
 
101
  if (
102
+ Builder.MIN_CHAPTER_SIZE is not None
103
+ and len(text) < Builder.MIN_CHAPTER_SIZE
104
  ):
105
+ # print(f"Skipping chapter of length {len(text)}")
106
+ pass
107
+ else:
108
+ # print(f"Adding chapter of length {len(text)}")
109
+ chapters.append(text)
110
+
111
+ chapter = ""
112
+ for e in root.iter():
113
+ if e.tag.endswith("}p"):
114
+ chapter += (e.text or "") + (e.tail or "")
115
+ elif e.tag.endswith("}section"):
116
+ _add_chapter(chapter)
117
+ chapter = ""
118
+ _add_chapter(chapter)
119
+
120
+ print(f'{filepath}: "{title}", found {len(chapters)} chapters')
121
+ # print(f"Chapter sizes: {', '.join(str(len(c)) for c in chapters)}")
122
+ # print()
123
+ return title, chapters