Datasets:

Modalities:
Image
Text
Formats:
arrow
Libraries:
Datasets
License:
balsab commited on
Commit
0645cae
·
verified ·
1 Parent(s): fb848ae

External reference-based Ocr quality check

Browse files

A rough quality overview for the documents in the corpus. Uses an external dictionary to count danish tokens in each page, and compares the results to other external sources of alleged "good" quality. Has problems, but is relatively quick and does not require too much resources. Included is a markdown with a more detailed rundown of the process.

.gitattributes CHANGED
@@ -57,3 +57,5 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
57
  # Video files - compressed
58
  *.mp4 filter=lfs diff=lfs merge=lfs -text
59
  *.webm filter=lfs diff=lfs merge=lfs -text
 
 
 
57
  # Video files - compressed
58
  *.mp4 filter=lfs diff=lfs merge=lfs -text
59
  *.webm filter=lfs diff=lfs merge=lfs -text
60
+ ocr_metadata/token_count/meta_data.json filter=lfs diff=lfs merge=lfs -text
61
+ ocr_metadata/token_count/ods_fullforms_2020-08-26.csv filter=lfs diff=lfs merge=lfs -text
ocr_metadata/ocr_metadata.json ADDED
The diff for this file is too large to render. See raw diff
 
ocr_metadata/ocr_metadata.md ADDED
@@ -0,0 +1,235 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # OCR Meta Data
2
+
3
+ OCR quality the legibility of scans might not always easy to analyze in a corpus of this magnitude. Especially knowing there are historic texts and at least two different font types present in the original scans.
4
+
5
+ For assessing the current state of the text data in the corpus and identifying documents which require to be re-processed from the scan a relatively quick, low-resource, rough estimation was used by comparing text meta data to the meta data of external references.
6
+
7
+ The before comparing to the reference, the pages, that are likely to be noise and/or non-representative to the overall quality of the document, were filtered out.
8
+
9
+ The meta data of the OCR (and thus text quality) the scripts related to their attainment are available [here](./ocr_metadata.json)
10
+
11
+
12
+ The meta data of the texts and the scripts related to their attainment are detailed [here](./token_count/meta_data.json)
13
+
14
+
15
+ ## Data Fields
16
+
17
+ An entry in the ocr_meta_data.json consists of the following fields:
18
+
19
+ - `filename` (`str`): A unique identifier for each document.
20
+ - `above_ref_line` (`float`): Bounded at [0,1], a numerical representation of quality. The bigger the number, the higher the ratio of pages surpassing the reference line derived from external texts.
21
+ - `processed` (`bool`): Whether the meta data was successfully compared to the reference line.
22
+ - `problem` (`str`): Flagged errors during the comparison process:
23
+ - `no` : The document was processed, the comparison process ran as expected
24
+ - `small_doc` : The document was processed, but the document has less than 10 pages. Low page numbers can influence the outcome of the de-noising.
25
+ - `no_mix` : The document was processed, but no pages were identified as noisy or non-representative of the whole document. As books usually have at least some empty- or title pages, this level of homogeneity is unexpected.
26
+ - `low_prop` : The document was processed, but after filtering, the remaining pages were less than half the size of the original document. As books usually have a main type of page, which dominates its majority, (e.g.: pages of full text) this level of variety is unexpected.
27
+ - `empty` : The document was not processed, the ocr is missing.
28
+
29
+ ## Results and Recommendations
30
+ **Banded quality values by year**
31
+ <p align="center">
32
+ <img src="./plots/ocr_meta_years.png" width="600" style="margin-right: 10px;" />
33
+ </p>
34
+
35
+ *Ratio and number of documents for each year, if quality is banded into 0.2 chunks based on the `above_ref_line` variable. The dotted line marks 1848*
36
+
37
+ The plots show a gradual increase in quality of the texts throughout the 19th century. This change in ocr quality likely corresponds to the shift from fraktur to antiqua fonts in book printing. OCR technology available at the time of scanning probably had issues with fraktur based texts. The sudden drop in the number of high-quality OCRs in the early 20th century are simply due to the [public domain filtering](syartide) which removed a lot of documents of ambiguous status before assembling and publishing the corpus itself.
38
+
39
+ Since the method for determining quality is not without faults (the plots indicate some high-quality OCRs even in the 1750's, which are almost all guaranteed to be in fraktur) the year 1848 seems to be an adequate dividing line.
40
+
41
+ Documents published from this year onward with a high `above_ref_line` value should be of acceptable quality, while the rest might require either some text restoration or more OCR methods. But as the examples show, all documents should be approached cautiously.
42
+
43
+ Pre 1848 excerpts with `above_ref_line` of 1:
44
+ <details>
45
+ <summary>Disse Rigers Fortrin i Lyksali... (1752)</summary>
46
+ 1te Crearur, fi>m hav formeeret Naturens Rige med et L iv , har Ud­
47
+ rettet meere end de, som ikke ere S tore uden ved Adeleggelse.
48
+ Forend Throner og M e re bleve besmittede med B lo d ; forend
49
+ Hyklerie og Overtros bragte den Lårdom ind, at M agten ikke var
50
+ bundet ril Viisdom s Lov, da i den lyksalige Alder saae man de adel-
51
+ modige Helte at bane sig Vey til et ubodeligt N avn ved at vare det
52
+ menneskelige Kions Lovgivere, Velgiorere og Beskyttere: A t giore
53
+ Jorden frugtbar, sormeere Landet med S tader og Indbyggere, be­
54
+ fordre mange Familiers Velstand ved Handel og Konster, og giore
55
+ deres Lyksalighed sikker og bestandig ved Love var den eeneste V ey til
56
+ DLre og Udsdelighed: D e forte ikke S v a rd e t, uden for at hanthave de
57
+ viise Love, som de selv havde givet, og fo ra t stadfaste Folket i en ro­
58
+ lig Besiddelse a f den Lyksalighed, hvortil de selv vare forste Aarsag og
59
+ S tifte re .
60
+ </details>
61
+ <details>
62
+ <summary>Et ringe Bryllups-Digt, da Bru... (1753)</summary>
63
+ O ! et lyksaligt P a r, hvor Venskab saa kand fryde,
64
+ Hvor ZEgte-Folk ey Tab paa noget godt stal nyde,
65
+ Hvor parret P ar sin Fryd ey finder uden der,
66
+ Hvor deres Hjemme - Sted i TEgte-Pagten er.
67
+ Men er det saa, saa er'vel den, der ugift bliver,
68
+ Ey saa lyksalig, som ben Mand, der sig hengiver
69
+ T>'l stig en Engle- V en, og faaer den Mage, der
70
+ Fornoyer, elsker og ham årer med l?lsiler.
71
+ V or B r u d g o m har ved sit eomxali ven Havn tiltragtet
72
+ Han fem Aars S oe-fart mod sligt Haab har lidet ag tet/
73
+ Som Soe-Mand bcrr han P riis, nu Reysen vel er endt,
74
+ V or erdle Brudgom ^ oredi Sorg til Trsst blev sendt.
75
+ </details>
76
+ <details>
77
+ <summary>Kort Samtale imellem en Landma...(1760)</summary>
78
+ Deres Hoygrevelige Excellencer,
79
+ Hr. Johan Ludvig von HMlil,
80
+ Greve til Detln-aborg, Ridder a f Dlepkanten, Geheime Raad t
81
+ det Geheime < I!onleil, Cammerherre, Ober-8eeret3ir i det Danffe
82
+ (dancellie, krLlidi Udi d!o!legio de Ourlu D vangelu promovendo,
83
+ (Jeneral-KirkednlpeLkori, og krXddi i det Kongelige Viden­
84
+ skabernes 8oeietXt udi Kiobenhavn rc.
85
+ </details>
86
+
87
+ ___
88
+
89
+ Excerpts from 1848 with `above_ref_line` of 1:
90
+ <details>
91
+ <summary>Kongens Svar og dets Følger</summary>
92
+ ^ndskjondt vi ikke tröste os til ved Ordet at gribe ind i Be­
93
+ givenhedernes Gang, saa ville vi dog ikke svigte det Hverv at
94
+ oplyse Veien for Villien, der aldrig behover mere Lys end naar
95
+ Folelsen stcerkt opliver den.
96
+ Kongen har talt; og hver dansk Mand slutter sig nu til
97
+ ham. Kongens Svar til det tydffe Parties Assendinge er i Alles
98
+ Mund, — og, hvilke Anskuelser man end iovrigt hvlder, saa
99
+ vil Enhver tilstaae, at der er Forstand med Kraft i den Tale.
100
+ </details>
101
+ <details>
102
+ <summary>Pastor Hieronimus Laubs Efterm...</summary>
103
+ 3S
104
+ aaudrig, talentfuld og begavet Religionslærer; en tw
105
+ Hyrde for den ham anbetroede Hjord, der ikke plejede
106
+ denne med menneskelig Viisdoms svulstige Ord, men
107
+ prcedikede som' en sand Herrens Apostel Guds Ord reent
108
+ og pnurt, og agtede hverken sig selv eller Menigheden
109
+ at vide Andet til Salighed end Jesum Christum, og
110
+ ham korsfæstet; hvorfor han og kunde sige sig selv med
111
+ Apostelen: „Det er min Roes, min Samvittigheds
112
+ Vidnesbyrd, at jeg har vandret for Gud i Oprigtighed
113
+ og Hjertets Retsindighed".
114
+ </details>
115
+ <details>
116
+ <summary>Sørgetale ved Kong Christian d...</summary>
117
+ Kongernes Konge, Du Herrernes Herre!
118
+ Dybt boie vi os for Dig, som holder Almagtens
119
+ Scepter i DinHaand; men i det vi boie os for
120
+ Dig med dybeste LErefrygt, hceve vi ogsaa Blikket
121
+ til Dig med den barnligste Tillid, fordi vi vide,
122
+ at Du, paa hvis Vink Troner henveires og
123
+ Herskerspire knuses, er Algodhedens Gud, som
124
+ Du er Alvceldens. Men derfor tor vi ogsaa for
125
+ Dig, barmhjertige Fader, udtale vore Klager,
126
+ </details>
127
+
128
+ ___
129
+
130
+ # Methods
131
+ The processes for estimating quality are detailed below
132
+
133
+ ## Reference Data and Comparison
134
+ For reference, 10k documents were sampled from the [Enevaldens nyheder](https://huggingface.co/datasets/danish-foundation-models/danish-dynaword/tree/main/data/enevaeldens_nyheder) dataset from the [Danish Dynaword](https://huggingface.co/datasets/danish-foundation-models/danish-dynaword). That dataset is assumed to have similar linguistic and stylistic contents, as it is also a collection historic Danish writings, dating back multiple centuries.
135
+
136
+ The Danish Dynaword in addition, has an automatic labeling process, which can assess text quality.
137
+
138
+ Only documents with the "good" label were chosen, to try and assemble a reference dataset.
139
+
140
+
141
+ The 10k documents were processed in the same way as the meta data of this corpus. The texts were tokenized, and tokens were matched to entries in the [reference dictionary](szartide).
142
+ The `text_rel_a_words` (float) variables were extracted, which are all These are all bounded \[0,1\]. These values formed a reference distribution, with each value in it representing the ratio of identifiable danish words and all words in a single text from an allegedly good quality historic Danish dataset. The median of this distribution was chosen as the **reference line**.
143
+
144
+ To determine the ocr quality of the documents of this corpus, the `text_rel_a_words` values for each document were also extracted from the metadata and compared to the **reference line**.
145
+
146
+ The comparison resulted in the `above_ref_line`(float) variable bounded \[0,1\], which represents the proportion of pages in the document, that were above the reference line. A value of 1 would therefore mean a document in which all pages had a greater proportion of \( tokens found within the dictionary / all alphabetical tokens \) than the reference line. This would probably indicate a document with a high high-quality OCR.
147
+ Values around 0.5 would indicate ambiguous, but possibly similar quality to the historic texts, and values of 0 would indicate worse quality.
148
+
149
+ Relevant scripts for producing the reference values are available [here](./scripts/get_ref_median.py).
150
+ Relevant scripts for comparison to the reference values are available [here](./scripts/doc_quality.py).
151
+
152
+ ## Removing Noise
153
+
154
+ The exact contents of the documents are also quite important and can influence the results. The reference distribution contains values derived from only text, while a page in this scanned corpus might be empty, might have pictures or only a small amount of tokens. For example, because of this, a picture book with perfectly legible, high-quality OCR scan danish text, which is above the reference line but only on every odd page, because even pages have pictures and therefore 0 alphabetical tokens, would have a final value of 0.5. This could prove problematic and lead to false estimations in the OCR quality of some documents. Also, if one thinks of books, they usually have empty pages in the front, back and between chapters, or might have title pages with only named entities, etc. These would all lower the estimated quality, therefore there needs to be a way to separate the relevant pages of every document. The pages which hold the majority of text contents and therefore would be the best indication of quality.
155
+
156
+ ### Conjugate prior based poisson mixture estimation
157
+
158
+ A non parametric conjugate-prior based mixture estimation was used to determine which pages are representative for each document.
159
+
160
+ If a book is a collection of different page types, e.g. pages with only text, pages with half text, title and empty pages, it could modelled as a mixture of discrete distributions, where each discrete value corresponds to the number of tokens on a page. These distributions are supposed to be clearly separable when ordered, and there should be minimal overlap between the drawn values.
161
+
162
+ Therefore a poisson mixture model could probably clearly separate the underlying page types for each document, but to avoid the use of more complex modeling techniques, the pages were simply ordered and treated as individual draws from poisson distributions, while a gamma distribution, which is the conjugate prior for the poisson, was calculated after every observation. This way, the gamma distribution gives the expected values for the lambda value of the poisson. In case the new value will be much higher than expected, the expectations of the gamma distribution will greatly update, and this signals that these are now drawn from a new poisson distribution.
163
+ It is important for this to work, that the pages are ordered by the number of words on them in an increasing fashion.
164
+
165
+ The method is crude and might not be as precise as a mixture model estimation, but at least, it is fast and the only essential external library for running it is [numpy](https://numpy.org/).
166
+
167
+ Then after mixture boundaries were identified, the number of pages belonging to each category were counted, and the one with the most pages in it was deemed the representative distribution for that document. Other noisy or non-related pages were filter out before comparing the documents to the **reference line**.
168
+
169
+ Relevant scripts for filtering the pages is available [here](./scripts/find_rep_pages.py).
170
+ Error logs during filtering are available [here](./scripts/repr_meta.log)
171
+
172
+
173
+ ### Mixture Separation Example
174
+ There is a 100 page document which is a mixture of draws from 3 [poisson](https://en.wikipedia.org/wiki/Poisson_distribution) distributions.
175
+
176
+ |Distributions | ||# draws |
177
+ |------------|---------|---|--|
178
+ | **$\lambda_{noise}$** | 10| |5|
179
+ | **$\lambda_{picture}$** | 80| |15|
180
+ | **$\lambda_{text}$** | 200| |80|
181
+
182
+ If the pages are ordered, the first 5 will be from a poisson with $\lambda_{noise}$. Let these values be \[ 8, 8, 12, 13, 15 \].
183
+
184
+ The [gamma](https://en.wikipedia.org/wiki/Gamma_distribution) distribution is the conjugate prior of the [poisson](https://en.wikipedia.org/wiki/Poisson_distribution), meaning, after each $n^{th}$ draw of $x$ from a poisson, the expected possible **$\lambda_{n+1}$** values can be modelled as:
185
+ $$
186
+ \alpha_{n+1} = \sum_{i=1}^{n} x_i \qquad \beta_{n+1} = n \qquad \lambda_{n+1} \sim Gamma(\alpha_{n+1},\beta_{n+1})
187
+ $$
188
+
189
+ So after page 1 \(page 1 here refers not to original page 1, but the one with the least words on it after ordering\)
190
+ $$
191
+ \lambda_{2} \sim Gamma(8,1)
192
+ $$
193
+ After page 2:
194
+ $$
195
+ \lambda_{3} \sim Gamma(8+8,2)
196
+ $$
197
+ And so on...
198
+ $$
199
+ \lambda_{4} \sim Gamma(28,3) \\
200
+ \lambda_{5} \sim Gamma(41,4) \\
201
+ \lambda_{6} \sim Gamma(56,5) \\
202
+ $$
203
+
204
+ But after page 5, there is a big change, because the currently expected gamma has a mean of $56/5 = 11.2$ but we know in this case the next 15 pages are drawn from $\lambda_{picture}$, which is $80$.
205
+
206
+ While the conjugate prior gamma for $\lambda$ was slowly homing on the value 10, now it will have a large update.
207
+
208
+ Let's say that $x_6 = 63$
209
+ $$
210
+ \lambda_{7} \sim Gamma(119,6)
211
+ $$
212
+
213
+
214
+ This is an observable difference. The mean of this distribution is $19.83$. Then the conjugate prior estimated lambda values for the second distribution will "clump" together again, until $x_{21}$ is reached, where there will be another big leap in the expected possible values for $\lambda_{22}$.
215
+
216
+ To automatically identify the leaps, the second derivative of the means of the gamma distributions were taken.
217
+ This way, large changes will emerge as outlier positive numbers. For example:
218
+
219
+ $$
220
+ \{x_i \mid 1 \leq i \leq ...\} = \{8,8,12,13,15,63,65, ...\} \\[10pt]
221
+ \mu_{gammas} = \{8,8,9.33, 10.25, 11.2,19.83, 26.28,...\}\\[10pt]
222
+ \Delta^2 \mu_{gammas} = \{ 1.33, -0.41, 0.03, 7.68, -2.46,...\}
223
+ $$
224
+
225
+ To make this a non parametric estimation, outliers in this list are treated as borders between different distributions. Preferably, values above the mean by 3 standard deviation were treated as outliers.
226
+
227
+ <p align="center">
228
+ <img src="./plots/example_denoiseing.png" width="600" style="margin-right: 10px;" />
229
+ </p>
230
+
231
+ In the case of this simulated example, it successfully identified the 3 different distributions, but with smaller difference between the lambdas, or too small overall document size,this method might struggle.
232
+
233
+
234
+
235
+
ocr_metadata/plots/example_denoiseing.png ADDED

Git LFS Details

  • SHA256: 549b7cb87b072c872eaec533fc4dac38a5cf656c4b52b1c4f06b03f3aa845682
  • Pointer size: 131 Bytes
  • Size of remote file: 145 kB
ocr_metadata/plots/ocr_meta_years.png ADDED

Git LFS Details

  • SHA256: 3514ef010d8779060cf65c683cb9dd18ee999da3eba1752df6fedb9a3de02afa
  • Pointer size: 131 Bytes
  • Size of remote file: 187 kB
ocr_metadata/scripts/doc_quality.py ADDED
@@ -0,0 +1,110 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from datasets import Dataset, load_dataset, disable_progress_bars, concatenate_datasets
2
+
3
+ from tqdm import tqdm
4
+
5
+ from page_mix import *
6
+
7
+ import re
8
+ disable_progress_bars()
9
+
10
+ def update_processed_docs(ds,document,msg):
11
+ #save current problem, if
12
+ if ds["problem"] == "no":
13
+ old_p = ""
14
+ else:
15
+ old_p = ds["problem"]
16
+
17
+ if ds["filename"] == document:
18
+ ds.update({"problem":old_p + msg})
19
+ else:
20
+ pass
21
+ return ds
22
+
23
+ def empty_docs(documents):
24
+ ds=[]
25
+ for i in documents:
26
+ ds.append({"filename":i,"above_ref_line":0.0,"processed":False,"problem":"empty"})
27
+ ds = Dataset.from_list(ds)
28
+
29
+ return ds
30
+
31
+
32
+ def main():
33
+ quality_list = []
34
+
35
+ #assemble dataset from representative pages
36
+ meta_data = load_dataset("./repr_meta",split="train")
37
+ #get reference line to from "good quality" documents
38
+ #by taking the median of its alphabetic character ratio dist
39
+ ref_docs = Dataset.from_parquet("good_qual_10k_counts.parquet")
40
+ reference_line = np.median(ref_docs["text_rel_a_words"])
41
+
42
+
43
+ #separate years
44
+ year_list = sorted(list(set(meta_data["published"])))
45
+
46
+ for year in tqdm(year_list,desc="YEARS "):
47
+
48
+ #filter each year
49
+ year_meta_data = meta_data.filter(lambda ds,year:ds["published"] == year, num_proc= 10, fn_kwargs={"year":year})
50
+
51
+ document_list = sorted(list(set(year_meta_data["file_name"])))
52
+
53
+ for document in tqdm(document_list,
54
+ leave=False,
55
+ desc="DOCS "):
56
+
57
+ #compare page alphabethic ratios to ref line
58
+ doc_meta_data = year_meta_data.filter(lambda ds,document:ds["file_name"] == document, fn_kwargs={"document":document})
59
+
60
+ rp = compare_to_ref_line(doc_meta_data,
61
+ ref_val=reference_line,
62
+ column_to_compare="page_text_rel_a_words")
63
+ #assigning for inspection
64
+ quality_list.append({"filename":document,"above_ref_line":rp,"processed":True,"problem":"no"})
65
+
66
+ #create dataset
67
+ quality_ds = Dataset.from_list(quality_list)
68
+
69
+ ######
70
+ #Error docs
71
+ with open("./repr_meta.log") as f:
72
+ lines = f.readlines()
73
+
74
+ re_pat= r"ERROR:.*pdf"
75
+
76
+ epe = [i for i in lines if "EmptyDocumentError" in i]
77
+ nme = [i for i in lines if "NoMixError" in i]
78
+ lpe = [i for i in lines if "LowProportionError" in i]
79
+ small_doc = [i for i in lines if "small_doc:True" in i]
80
+
81
+ #pair the errors with filenames
82
+ nme_fns = [re.findall(re_pat,i)[0].replace("ERROR: ", "") for i in nme]
83
+
84
+ epe_fns = [re.findall(re_pat,i)[0].replace("ERROR: ", "") for i in epe]
85
+
86
+ lpe_fns = [re.findall(re_pat,i)[0].replace("ERROR: ", "") for i in lpe]
87
+
88
+ small_doc_fns = [re.findall(re_pat,i)[0].replace("ERROR: ", "") for i in small_doc]
89
+
90
+ #append vals from logs
91
+ for i in tqdm(small_doc_fns,leave=False,desc="small_docs"):
92
+ quality_ds = quality_ds.map(update_processed_docs,fn_kwargs={"document":i,"msg":"small_doc;"})
93
+
94
+ for i in tqdm(nme_fns,leave=False,desc="no_mix"):
95
+ quality_ds = quality_ds.map(update_processed_docs,fn_kwargs={"document":i,"msg":"no_mix;"})
96
+
97
+ for i in tqdm(lpe_fns,leave=False,desc="low_prop"):
98
+ quality_ds = quality_ds.map(update_processed_docs,fn_kwargs={"document":i,"msg":"low_prop;"})
99
+
100
+ empty_document = empty_docs(epe_fns)
101
+
102
+ quality_ds = concatenate_datasets([quality_ds,empty_document])
103
+ #print(epe_fns)
104
+
105
+ #save results
106
+ quality_ds.to_json("../ocr_metadata.json")
107
+
108
+
109
+ if __name__ == "__main__":
110
+ main()
ocr_metadata/scripts/find_rep_pages.py ADDED
@@ -0,0 +1,79 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import logging
3
+
4
+ from datasets import Dataset , concatenate_datasets, disable_progress_bars
5
+ from tqdm import tqdm
6
+
7
+ from u_func import *
8
+ from page_mix import *
9
+
10
+
11
+
12
+ logging.basicConfig(filename="repr_meta.log",
13
+ format='%(asctime)s %(levelname)s: %(message)s',
14
+ filemode='a')
15
+
16
+ logger = logging.getLogger()
17
+ logger.setLevel(logging.INFO)
18
+
19
+ def main():
20
+ logger.info("START...")
21
+ disable_progress_bars()
22
+
23
+ #metadata
24
+ meta_data = Dataset.from_json("../token_count/meta_data.json")
25
+ #separate years
26
+ year_list = sorted(list(set(meta_data["published"])))
27
+
28
+ for year in tqdm(year_list,desc="YEARS "):
29
+ logger.info(f"{year} : ")
30
+ year_ds_list = []
31
+ #filter each year
32
+ year_meta_data = meta_data.filter(lambda ds,year:ds["published"] == year, num_proc= 10, fn_kwargs={"year":year})
33
+
34
+ #separate documents
35
+ document_list = sorted(list(set(year_meta_data["file_name"])))
36
+
37
+ for document in tqdm(document_list,
38
+ leave=False,
39
+ desc="DOCS "):
40
+
41
+
42
+ doc_meta_data = year_meta_data.filter(lambda ds,document:ds["file_name"] == document, fn_kwargs={"document":document})
43
+
44
+ if len(doc_meta_data)<10:
45
+ small_doc = True
46
+ else:
47
+ small_doc = False
48
+
49
+ #remove first page (it is a cover by the library, and not part of the ocr)
50
+ doc_meta_data = doc_meta_data.filter(lambda ds: ds["page_id"][-3:] != "_p1")
51
+ #find the pages which are more representative of the whole ocr
52
+ #meaning they have no outlier amount of tokens
53
+ doc_toks = list(doc_meta_data["page_text_n_tokens"])
54
+
55
+ try:
56
+ doc_meta_data = doc_meta_data.filter(representative_pages,
57
+ fn_kwargs={"doc_toks":doc_toks,
58
+ "column":"page_text_n_tokens"})
59
+ except (EmptyDocumentError,NoMixError,LowProportionError) as e:
60
+ logger.error(f"{document} problem, small_doc:{small_doc} ,{e}")
61
+ if "EmptyDocumentError" in e.message:
62
+ continue
63
+ else:
64
+ #if no denoizing could be done, mark all pages as representative, the problem is logged
65
+ pass
66
+
67
+ #temporary ds added to to large ds
68
+ year_ds_list.append(doc_meta_data)
69
+
70
+ #save by year
71
+ year_ds = concatenate_datasets(year_ds_list)
72
+ fp = os.path.join(".","repr_meta",f"{year}_pages.json")
73
+ year_ds.to_json(fp)
74
+
75
+ if __name__ == "__main__":
76
+ main()
77
+
78
+
79
+
ocr_metadata/scripts/get_ref_median.py ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from datasets import load_dataset, Dataset
2
+
3
+ import pandas as pd
4
+ from u_func import *
5
+ from page_mix import *
6
+
7
+
8
+ def main():
9
+ #get reference data of acceptable quality
10
+ #load dynaword metadata and filter good quality texts
11
+ meta = load_dataset("danish-foundation-models/danish-dynaword", "meta", split="train").filter(
12
+ lambda row: (row["dataset"] == "enevaeldens_nyheder") & (row["content_quality"] == "good"), num_proc = 10,
13
+ )
14
+ #select 10k docs
15
+ good_quality_ids = [i for i in meta["id"][:10000]]
16
+ #load dynaword texts and filter good quality texts
17
+ a = load_dataset("danish-foundation-models/danish-dynaword", "enevaeldens_nyheder", split = "train").filter(
18
+ lambda ds, good_quality_ids: ds["id"] in good_quality_ids,
19
+ fn_kwargs={"good_quality_ids":good_quality_ids},
20
+ num_proc=10)
21
+
22
+ #load in wordset to check against
23
+ danish_words=list(pd.read_csv("../token_count/ods_fullforms_2020-08-26.csv", sep = "\t")["A"])
24
+ danish_words = [i.lower() for i in danish_words]
25
+ danish_words = list(set(danish_words))
26
+
27
+ b = a.map(
28
+ count_tokens_and_words,
29
+ fn_kwargs = {"colname":"text",
30
+ "wordlist":danish_words},
31
+ num_proc = 10)
32
+
33
+ b.to_parquet("good_qual_10k_counts.parquet")
34
+
35
+ if __name__ == "__main__":
36
+ main()
ocr_metadata/scripts/good_qual_10k_counts.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:e7d96ba69bf229a15a0039a5fc7a985b72ee743801255fda844e12cbe24b4409
3
+ size 6404335
ocr_metadata/scripts/page_mix.py ADDED
@@ -0,0 +1,160 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import warnings
2
+
3
+ import numpy as np
4
+
5
+
6
+ def estimate_groups_sd(data:list[int]) -> list[list[int],list[str]]:
7
+ """ Estimates a multiple poisson model mixture by finding large changes in conjugate priors updates. """
8
+
9
+ if 0 in data:
10
+ warnings.warn("WARNING : 0s. Make sure missing (0) observations are in the assumptions")
11
+ else:
12
+ pass
13
+
14
+ #we have a range of n_toks
15
+ n_toks = sorted(data)
16
+ #take cumulative sum
17
+ cs_toks = np.cumsum(n_toks)
18
+
19
+ #calculate conjugate prior updates
20
+ # alpha_i+1 = alpha_i + k
21
+ # beta_i+1 = beta_i + 1
22
+
23
+ mean_list = [(cs_toks[idx_i])/(idx_i + 1) for idx_i, i in enumerate(n_toks)]
24
+ #############################################
25
+ #differences
26
+ diff_diff = np.diff(mean_list, n=2)
27
+ # find borders, to big changes
28
+ # find outliers, assume gaussian?
29
+ m =np.mean(diff_diff)
30
+ s = np.std(diff_diff)
31
+ out_limit = m+3*s
32
+
33
+ #find the id of the borders
34
+ border_idx = np.where(diff_diff > out_limit)[0]
35
+ if len(border_idx) == 0:
36
+ out_limit = m+2*s
37
+ border_idx = np.where(diff_diff > out_limit)[0]
38
+ warnings.warn("StdLoweredWarning: Outlier detection was lowered to 2 standard deviations range. Data might have too few observations, or the difference in the counts could have an unexpected linear increase")
39
+ if len(border_idx) == 0:
40
+ out_limit = m+1*s
41
+ border_idx = np.where(diff_diff > out_limit)[0]
42
+ warnings.warn("StdLoweredWarning: Outlier detection was lowered to 1 standard deviations range. Data might have too few observations, or the difference in the counts could have an unexpected linear increase")
43
+ if len(border_idx) == 0:
44
+ warnings.warn("NoMixWarning: No clear borders found. Data might have too few observations, or the difference in the counts could have an unexpected linear increase")
45
+ # + 2 cause the differentiation lessens the length and we want
46
+ # the border idx to be the first value of the group on the discrete data
47
+ borders = [n_toks[i+2] for i in border_idx]
48
+ #############################################
49
+ #make bins on the original data
50
+ indices = np.digitize(data, borders, right=False)
51
+
52
+ return (data,indices,borders)
53
+
54
+ def category_overview_sd(data_list):
55
+ #separate to category
56
+ _, og_groups, borders = estimate_groups_sd(data_list)
57
+ #
58
+ group_ids, group_count =np.unique(og_groups,return_counts=True)
59
+ group_count = group_count / len(data_list)
60
+
61
+ borders = [0] + borders
62
+
63
+ overview_dict = np.array([group_ids,group_count,borders])
64
+ return overview_dict
65
+
66
+
67
+
68
+ def beta_median(alpha:int,beta:int):
69
+ """ Approximates beta median based on :
70
+
71
+ Kerman, J. (2011). A closed-form approximation for the median of the beta distribution (arXiv:1111.0433). arXiv. https://doi.org/10.48550/arXiv.1111.0433
72
+ """
73
+ b_med = (alpha-(1/3))/(alpha+beta-(2/3))
74
+ return b_med
75
+
76
+ def estimate_beta_median(n_toks:int,n_correct:int):
77
+ if n_toks == n_correct:
78
+ warnings.warn("WARNING: all tokens are identified, n_correct will be decreased by one")
79
+ n_correct = n_correct - 1
80
+
81
+ assert n_toks > 1, f"ERROR: few tokens on page: {n_toks}, n_toks should be > 1"
82
+ assert n_correct >1,f"ERROR: Too few identified tokens on page: {n_correct}, n_correct should be > 1"
83
+
84
+ n_incorrect = n_toks - n_correct
85
+ return beta_median(n_correct,n_incorrect)
86
+
87
+ def estimate_median_diff(medians_1:list[float], medians_2:list[float]):
88
+ """ Estimate the probability of the second set of medians being higher than the first. Median ids should align"""
89
+
90
+ assert len(medians_1) == len(medians_1), f"ERROR: mismatch in median list sizes: m1: {len(medians_1)}, m2: {len(medians_1)}"
91
+
92
+ med_diff = np.array(medians_2) - np.array(medians_1)
93
+
94
+ return np.mean(med_diff > 0)
95
+
96
+ #################################for filtering huggingface datasets
97
+
98
+ #custom errors to handle different unexpected values
99
+ class EmptyDocumentError(Exception):
100
+ def __init__(self, message = "EmptyDocumentError : Pages with tokens too low"):
101
+ super().__init__(message)
102
+ self.message = message
103
+
104
+ def __str__(self):
105
+ return f"{self.message}"
106
+
107
+ class NoMixError(Exception):
108
+ def __init__(self, message = "NoMixError : No clear boundaries have been found. Leaps in page differences might be strangely linear. "):
109
+ super().__init__(message)
110
+ self.message = message
111
+
112
+ def __str__(self):
113
+ return f"{self.message}"
114
+
115
+ class LowProportionError(Exception):
116
+ def __init__(self, message = "LowProportionError : The highest proportion for representative pages is less than 0.5. There might be too few pages or leaps in page differences might be strangely linear."):
117
+ super().__init__(message)
118
+ self.message = message
119
+
120
+ def __str__(self):
121
+ return f"{self.message}"
122
+
123
+ #filter representative category
124
+ def representative_pages(ds,doc_toks,column:str):
125
+ #og len
126
+ l1 = len(doc_toks)
127
+ doc_toks_non_0 = [i for i in doc_toks if i !=0]
128
+
129
+ if len(doc_toks_non_0) / l1 < 0.2:
130
+ raise EmptyDocumentError(f"EmptyDocumentError : Pages with tokens: {len(doc_toks_non_0)}, Total pages: {l1}")
131
+
132
+ catover = category_overview_sd(doc_toks)
133
+
134
+ #border value for category with the highest proportion in the data
135
+ max_proportion = np.max(catover,axis=1)[1]
136
+ max_prop_cat = np.where(catover[1]==max_proportion)[0][0]
137
+ cat_lb = catover[2][max_prop_cat]
138
+
139
+ if len(catover[0]) == 1:
140
+ raise NoMixError()
141
+ if max_proportion < 0.5:
142
+ raise LowProportionError()
143
+
144
+
145
+ #if the highest category is the most likely
146
+ #is the most likely only get min,
147
+ #otherwise get the border of the next category too
148
+ if (np.max(catover,axis=1)[0] == max_prop_cat):
149
+ val = (ds[column] >= cat_lb)
150
+
151
+ else:
152
+ next_cat = max_prop_cat+1
153
+ cat_ub = catover[2,next_cat]
154
+ val = (ds[column] >= cat_lb) & (ds[column] < cat_ub)
155
+
156
+ return val
157
+
158
+ def compare_to_ref_line(dataset,ref_val:float,column_to_compare:str):
159
+ ratio_of_pass = np.mean(np.array(dataset[column_to_compare]) > ref_val)
160
+ return ratio_of_pass
ocr_metadata/scripts/page_mix_plots.py ADDED
@@ -0,0 +1,105 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import warnings
2
+
3
+ import numpy as np
4
+ import pandas as pd
5
+
6
+ #import pymc as pm
7
+ from plotnine import *
8
+
9
+
10
+ def estimate_groups_plot(data:list[int],std:int=3) -> list[list[int],list[str]]:
11
+ """ Estimates a multiple poisson model mixture by finding large changes in conjugate priors updates. """
12
+
13
+ if 0 in data:
14
+ warnings.warn("WARNING : 0s detected in input data, this could result in more groups being estimated than expected. Make sure missing (0) observations are in the assumptions")
15
+ else:
16
+ pass
17
+
18
+ r_gen = np.random.default_rng()
19
+
20
+ #we have a range of n_toks
21
+ n_toks = sorted(data)
22
+ #take cumulative sum
23
+ cs_toks = np.cumsum(n_toks)
24
+
25
+ d_list = []
26
+ mean_list= []
27
+
28
+ for idx_i, i in enumerate(n_toks):
29
+
30
+ #alpha and beta values for the gamma dist
31
+ alpha=cs_toks[idx_i]
32
+ beta=idx_i + 1
33
+ mean_list.append(alpha/beta)
34
+
35
+ draws = r_gen.gamma(shape=alpha, scale = 1/beta,size=100)
36
+ #draws = pm.draw(pm.Gamma.dist(alpha=alpha,
37
+ # beta=beta),100)
38
+
39
+ for d in draws:
40
+ d_list.append({"n_toks":i,"gamma_a":alpha,"gamma_b":beta,"val":d, "m":mean_list[idx_i]})
41
+
42
+ df = pd.DataFrame(d_list)
43
+
44
+ #############################################
45
+ #differences
46
+ diff_diff = np.diff(mean_list, n=2)
47
+ # find borders, to big changes
48
+ # find outliers, assume gaussian?
49
+ m = np.mean(diff_diff)
50
+ s = np.std(diff_diff)
51
+
52
+ out_limit = m+std*s
53
+ outliers = [i for i in diff_diff if i>out_limit]
54
+
55
+ #if no outliers, start inflating with zeros
56
+
57
+
58
+ #find the id of the borders
59
+ border_idx = np.where(diff_diff > out_limit)[0]
60
+
61
+ # + 2 cause the differentiation lessens the length and we want
62
+ # the border idx to be the first value of the group on the discrete data
63
+ borders = [n_toks[i+2] for i in border_idx]
64
+
65
+ #find the id of those outliers to visualize the prior updates
66
+ prior_borders = [mean_list[i+2] for i in border_idx]
67
+ #############################################
68
+ #visualize original dists
69
+
70
+ #value category labels, as many as identified borders
71
+ labels = np.array([f"group_{i}" for i in range(len(borders)+1)])
72
+
73
+ #make bins
74
+ indices = np.digitize(n_toks, borders, right=False)
75
+ cats = labels[indices]
76
+
77
+ recat = [{"n_toks": i, "cat":cats[idx_i]} for idx_i, i in enumerate(n_toks)]
78
+
79
+
80
+ #plot differences?
81
+ vis_diff = pd.DataFrame(diff_diff,columns=["val"])
82
+
83
+
84
+ recat_df = pd.DataFrame(recat)
85
+
86
+ plot = (
87
+ ggplot(df,aes("val",group="n_toks"))
88
+ + geom_vline(xintercept=prior_borders, linetype="dashed")
89
+ + xlab("expected lambda values after each page")
90
+ + geom_density()
91
+ + theme_classic()
92
+ ) / (
93
+ ggplot(vis_diff,aes("val"))
94
+ + geom_density()
95
+ + geom_vline(xintercept=outliers,linetype="dashed")
96
+ + xlab("outliers in the gamma means (second derivatives)")
97
+ + theme_classic()
98
+ ) / (
99
+ ggplot(recat_df,aes("n_toks",fill="cat"))
100
+ + geom_vline(xintercept=borders, linetype="dashed")
101
+ + xlab("separated distributions")
102
+ + geom_density()
103
+ + theme_classic()
104
+ )
105
+ return plot
ocr_metadata/scripts/repr_meta.log ADDED
The diff for this file is too large to render. See raw diff
 
ocr_metadata/scripts/repr_meta/.gitkeep ADDED
File without changes
ocr_metadata/scripts/u_func.py ADDED
@@ -0,0 +1,185 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import itertools
2
+ from collections import Counter
3
+ from datasets import Dataset
4
+
5
+ from tqdm import tqdm
6
+
7
+ def only_nan(input:list) -> bool:
8
+ #remove nans and whitespaces
9
+ c_input = [e for e in input if e==e and e!=" "]
10
+ if len(c_input) > 0:
11
+ return False
12
+ else:
13
+ return True
14
+
15
+ def shard_ds(ds:Dataset, size=1000) -> list[Dataset]:
16
+ if len(ds) < 1000:
17
+ ds_list = [ds]
18
+ else:
19
+ ds_list = []
20
+ n_s = round(len(ds)/size)
21
+ indices = [i for i in range(n_s)]
22
+ for i in indices:
23
+ data_shard = ds.shard(num_shards=n_s, index = i)
24
+ ds_list.append(data_shard)
25
+
26
+ return ds_list
27
+
28
+
29
+ def word_tokenize(text: str) -> list[str]:
30
+ """
31
+ Tokenizes a string into words, splitting on whitespace and punctuation.
32
+ Example:
33
+ >>> word_tokenize("Hello, world!")
34
+ ['Hello', ',', 'world', '!']
35
+ >>> word_tokenize("This is a test.")
36
+ ['This', 'is', 'a', 'test', '.']
37
+ >>> word_tokenize("Many spaces between words.")
38
+ ['Many', 'spaces', 'between', 'words', '.']
39
+ """
40
+
41
+ punkt = [",", ".", "!", "?", ":", ";", "(", ")", "[", "]", "{", "}", '"', "'"]
42
+ for p in punkt:
43
+ text = text.replace(p, f" {p} ")
44
+ t = text.split()
45
+ return t
46
+
47
+ def remove_punkt_and_numbers(tokens:list[str]) -> list[str]:
48
+ punkt = [",", ".", "!", "?", ":", ";", "(", ")", "[", "]", "{", "}", '"', "'"]
49
+ tokens = [i.lower() for i in tokens if i not in punkt and i.isalpha()]
50
+ return tokens
51
+
52
+
53
+ def count_tokens_and_words(page:Dataset,colname:str,wordlist:list[str])-> Dataset:
54
+ """returns all token count including numbers and punctuation,
55
+ as well as relation of dictionary items to all tokens (measures general quality),
56
+ and relation of dictionary items to only alphabetic words (measures difference between ocr methods)
57
+ """
58
+
59
+ toks = word_tokenize(page[colname])
60
+ a_toks = remove_punkt_and_numbers(toks)
61
+ t_length = len(toks)
62
+
63
+ punkt = [",", ".", "!", "?", ":", ";", "(", ")", "[", "]", "{", "}", '"', "'"]
64
+ t_punkt = [i for i in toks if i in punkt]
65
+ n_punkt = len(t_punkt)
66
+
67
+ word_c = [i for i in a_toks if i in wordlist]
68
+ if len(a_toks) == 0:
69
+ wc_rel = 0.0
70
+ wc_a_rel = 0.0
71
+ else:
72
+ wc_rel = round(len(word_c)/len(toks),4)
73
+ wc_a_rel = round(len(word_c)/len(a_toks),4)
74
+
75
+ t_name = colname + "_n_tokens"
76
+ wc_name = colname + "_rel_words"
77
+ wc_a_name = colname + "_rel_a_words"
78
+ p_t_name = colname + "_punkt_tokens"
79
+ a_t_name = colname + "_a_tokens"
80
+
81
+ page.update({t_name:t_length,
82
+ wc_name:wc_rel,
83
+ wc_a_name:wc_a_rel,
84
+ p_t_name:n_punkt,
85
+ a_t_name:len(a_toks)})
86
+
87
+ return page
88
+
89
+ def all_possible_words(word:str,ed:dict[str:list[str]]):
90
+ """returns a list of all possible words based on the most common misidentification errors for characters"""
91
+
92
+ pc_at_idx = []
93
+ #for each character
94
+ for char in word:
95
+ if char in ed.keys():
96
+ #check if that character has possible errors
97
+ possible_chars=ed.get(char)
98
+ pc_at_idx.append(possible_chars)
99
+
100
+ else:
101
+ pc_at_idx.append([char])
102
+ #get all combinations of possible error characters without dups
103
+ a = list(set(itertools.product(*pc_at_idx)))
104
+ alternate_word_list = ["".join(list(i)) for i in a]
105
+ return alternate_word_list
106
+
107
+ def error_checker(a_toks:list[str],wordlist:list[str],errors:dict[str,list[str]]):
108
+ """If token is not in the wordlist, tries the possible misidentified characters to lessen the errors"""
109
+ word_c = []
110
+ for alpha_token in tqdm(a_toks):
111
+ #only check against specific starting chars???
112
+
113
+
114
+ ##
115
+ if alpha_token in wordlist:
116
+ word_c.append(alpha_token)
117
+ #limit lenght otherwise time explodes
118
+ elif len(alpha_token)<7:
119
+ a_p_w = sorted(all_possible_words(alpha_token,errors))
120
+ # limit what to check against based on first char
121
+ # slice x subsets from wordlsit based on only the first character
122
+ c_keys= Counter(a_p_w).keys()
123
+ abc_wl = [[i for i in wordlist if i[0] == j] for j in c_keys]
124
+
125
+ for alternate_w in a_p_w:
126
+ #determine which abc_wl to check against
127
+ abc_idx = list(c_keys).index(alternate_w[0])
128
+
129
+ if alternate_w in abc_wl[abc_idx]:
130
+ word_c.append(alternate_w)
131
+ break
132
+ else:
133
+ pass
134
+ else:
135
+ pass
136
+ return word_c
137
+
138
+
139
+
140
+ def count_tokens_and_words_2(page:Dataset,
141
+ colname:str,
142
+ wordlist:list[str],
143
+ err_dict:dict[str,list[str]])-> Dataset:
144
+ """returns all token count including numbers and punctuation,
145
+ as well as relation of dictionary items to all tokens (measures general quality),
146
+ and relation of dictionary items to only alphabetic words (measures difference between ocr methods)
147
+ """
148
+ toks = word_tokenize(page[colname])
149
+ a_toks = remove_punkt_and_numbers(toks)
150
+ t_length = len(toks)
151
+
152
+ punkt = [",", ".", "!", "?", ":", ";", "(", ")", "[", "]", "{", "}", '"', "'"]
153
+ t_punkt = [i for i in toks if i in punkt]
154
+ n_punkt = len(t_punkt)
155
+ #now here someting that checks all possible errors
156
+ word_c = error_checker(a_toks,wordlist,err_dict)
157
+
158
+
159
+ if len(a_toks) == 0:
160
+ wc_rel = 0.0
161
+ wc_a_rel = 0.0
162
+ else:
163
+ wc_rel = round(len(word_c)/len(toks),4)
164
+ wc_a_rel = round(len(word_c)/len(a_toks),4)
165
+
166
+ t_name = colname + "_n_tokens"
167
+ wc_name = colname + "_rel_words"
168
+ wc_a_name = colname + "_rel_a_words"
169
+ p_t_name = colname + "_punkt_tokens"
170
+ a_t_name = colname + "_a_tokens"
171
+
172
+ page.update({t_name:t_length,
173
+ wc_name:wc_rel,
174
+ wc_a_name:wc_a_rel,
175
+ p_t_name:n_punkt,
176
+ a_t_name:len(a_toks)})
177
+
178
+ return page
179
+
180
+
181
+ def make_year_list(start_year: int, stop_year: int) -> list[str]:
182
+ """make a list of file names based on years"""
183
+ year_list = list(range(start_year, stop_year + 1))
184
+ year_list = [str(i) for i in year_list]
185
+ return year_list
ocr_metadata/token_count/make_count.py ADDED
@@ -0,0 +1,109 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # /// script
2
+ # requires-python = "==3.12"
3
+ # dependencies = [
4
+ # "huggingface-hub>= 0.34.4"
5
+ # "datasets>=3.5.0",
6
+ # ]
7
+ # ///
8
+
9
+ import regex as re
10
+
11
+ import pandas as pd
12
+
13
+ from datasets import load_dataset, concatenate_datasets
14
+ from huggingface_hub import HfFileSystem
15
+
16
+
17
+ from u_func import *
18
+
19
+ #consider appendix
20
+ appendix = False
21
+ #which
22
+ a="_4"
23
+ #set years
24
+ start_year = 1930
25
+ #last year to process
26
+ stop_year = 1930
27
+ year_list = sorted(make_year_list(start_year,stop_year))
28
+ if appendix:
29
+ year_list = [i+a for i in year_list]
30
+
31
+ def get_files_year(year:str)->list[str]:
32
+ #get filenames in a year
33
+ fs = HfFileSystem()
34
+ # List files
35
+ try:
36
+ f_dict = fs.ls(f"datasets/chcaa/kb-books/data/{year}")
37
+ f_names = [i.get("name") for i in f_dict]
38
+ f_names = [re.sub("datasets/chcaa/kb-books/","",i) for i in f_names]
39
+ except FileNotFoundError:
40
+ f_names = "Not Found"
41
+ return f_names
42
+
43
+
44
+ def main():
45
+ #load in wordset to check against
46
+ danish_words=list(pd.read_csv("./ods_fullforms_2020-08-26.csv", sep = "\t")["A"])
47
+ danish_words = [i.lower() for i in danish_words]
48
+ danish_words = list(set(danish_words))
49
+
50
+
51
+
52
+ for year in year_list:
53
+ print(f"STARTING YEAR {year}...")
54
+ #load in data
55
+ #year_path = os.path.join("..","data",year)
56
+ #year_data = load_from_disk(year_path)
57
+ year_files = get_files_year(year)
58
+
59
+ if year_files == "Not Found":
60
+ print(f"{year} does not exist")
61
+ continue
62
+
63
+ year_data = load_dataset("chcaa/kb-books", split="train",
64
+ data_files=year_files)
65
+
66
+ #count tokens
67
+ #drop image
68
+ year_data = year_data.remove_columns("page_image")
69
+
70
+ #shuffling and sharding is to try and increase efficiency of the processes
71
+ #if a single process gets stuck with an unlucky draw of pages the available cpu
72
+ #power is not fully utilized
73
+
74
+ #shuffle dataset
75
+ year_data = year_data.shuffle(seed=1956)
76
+ #flatten indices
77
+ year_data = year_data.flatten_indices()
78
+ #shard the year
79
+ year_data = shard_ds(year_data)
80
+ #print(year_data)
81
+ yd_list = []
82
+ for i in year_data:
83
+ i = i.map(
84
+ count_tokens_and_words,
85
+ fn_kwargs = {"colname":"page_text",
86
+ "wordlist":danish_words},
87
+ num_proc = 16)
88
+ yd_list.append(i)
89
+ #print(yd_list)
90
+ #reassemble
91
+ year_data = concatenate_datasets(yd_list)
92
+
93
+ cols = year_data.column_names
94
+ wanted_cols = ["page_id","title","published",
95
+ "page_text_n_tokens",
96
+ "page_text_rel_a_words",
97
+ "page_text_rel_words",
98
+ "page_text_punkt_tokens",
99
+ "page_text_a_tokens",
100
+ "file_name"]
101
+ unwanted_cols = [i for i in cols if i not in wanted_cols]
102
+ #remove unnecessary columns
103
+ year_data = year_data.remove_columns(column_names=unwanted_cols)
104
+ #save by year
105
+ year_data.to_parquet(f"./metadata/{year}.parquet")
106
+
107
+
108
+ if __name__ == "__main__":
109
+ main()
ocr_metadata/token_count/meta_data.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:965cf20aa56f800f398ddfc293542fc6f7b1b0bbb2fd82317d72bbcb38a68009
3
+ size 1158858773
ocr_metadata/token_count/meta_data/.gitkeep ADDED
File without changes
ocr_metadata/token_count/ods_fullforms_2020-08-26.csv ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:2c9260a90e5d314c3cfdbbebc68b5e545808b4899895275f7ccbe2ac9fc09d46
3
+ size 49015402
ocr_metadata/token_count/reorganize_metadata.py ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # /// script
2
+ # requires-python = "==3.12"
3
+ # dependencies = [
4
+ # "datasets>=3.5.0"
5
+ # ]
6
+ # ///
7
+ import os
8
+ from datasets import Dataset, concatenate_datasets
9
+
10
+
11
+ def main():
12
+ #load files
13
+ ds_list = []
14
+ files = os.listdir("./metadata")
15
+ for i in sorted(files):
16
+ fp = f"./metadata/{i}"
17
+ ds = Dataset.from_parquet(fp)
18
+ ds_list.append(ds)
19
+ ds_big = concatenate_datasets(ds_list)
20
+ #save as one file
21
+ ds_big.to_json(f"meta_data.json")
22
+
23
+ if __name__ == "__main__":
24
+ main()