Datasets:

Modalities:
Image
Text
Formats:
arrow
Libraries:
Datasets
License:
kb-books / ocr_metadata /scripts /page_mix.py
balsab's picture
External reference-based Ocr quality check (#19)
c8f0f88
Raw History Blame Contribute Delete
6.28 kB
import warnings
import numpy as np
def estimate_groups_sd(data:list[int]) -> list[list[int],list[str]]:
""" Estimates a multiple poisson model mixture by finding large changes in conjugate priors updates. """
if 0 in data:
warnings.warn("WARNING : 0s. Make sure missing (0) observations are in the assumptions")
else:
pass
#we have a range of n_toks
n_toks = sorted(data)
#take cumulative sum
cs_toks = np.cumsum(n_toks)
#calculate conjugate prior updates
# alpha_i+1 = alpha_i + k
# beta_i+1 = beta_i + 1
mean_list = [(cs_toks[idx_i])/(idx_i + 1) for idx_i, i in enumerate(n_toks)]
#############################################
#differences
diff_diff = np.diff(mean_list, n=2)
# find borders, to big changes
# find outliers, assume gaussian?
m =np.mean(diff_diff)
s = np.std(diff_diff)
out_limit = m+3*s
#find the id of the borders
border_idx = np.where(diff_diff > out_limit)[0]
if len(border_idx) == 0:
out_limit = m+2*s
border_idx = np.where(diff_diff > out_limit)[0]
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")
if len(border_idx) == 0:
out_limit = m+1*s
border_idx = np.where(diff_diff > out_limit)[0]
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")
if len(border_idx) == 0:
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")
# + 2 cause the differentiation lessens the length and we want
# the border idx to be the first value of the group on the discrete data
borders = [n_toks[i+2] for i in border_idx]
#############################################
#make bins on the original data
indices = np.digitize(data, borders, right=False)
return (data,indices,borders)
def category_overview_sd(data_list):
#separate to category
_, og_groups, borders = estimate_groups_sd(data_list)
#
group_ids, group_count =np.unique(og_groups,return_counts=True)
group_count = group_count / len(data_list)
borders = [0] + borders
overview_dict = np.array([group_ids,group_count,borders])
return overview_dict
def beta_median(alpha:int,beta:int):
""" Approximates beta median based on :
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
"""
b_med = (alpha-(1/3))/(alpha+beta-(2/3))
return b_med
def estimate_beta_median(n_toks:int,n_correct:int):
if n_toks == n_correct:
warnings.warn("WARNING: all tokens are identified, n_correct will be decreased by one")
n_correct = n_correct - 1
assert n_toks > 1, f"ERROR: few tokens on page: {n_toks}, n_toks should be > 1"
assert n_correct >1,f"ERROR: Too few identified tokens on page: {n_correct}, n_correct should be > 1"
n_incorrect = n_toks - n_correct
return beta_median(n_correct,n_incorrect)
def estimate_median_diff(medians_1:list[float], medians_2:list[float]):
""" Estimate the probability of the second set of medians being higher than the first. Median ids should align"""
assert len(medians_1) == len(medians_1), f"ERROR: mismatch in median list sizes: m1: {len(medians_1)}, m2: {len(medians_1)}"
med_diff = np.array(medians_2) - np.array(medians_1)
return np.mean(med_diff > 0)
#################################for filtering huggingface datasets
#custom errors to handle different unexpected values
class EmptyDocumentError(Exception):
def __init__(self, message = "EmptyDocumentError : Pages with tokens too low"):
super().__init__(message)
self.message = message
def __str__(self):
return f"{self.message}"
class NoMixError(Exception):
def __init__(self, message = "NoMixError : No clear boundaries have been found. Leaps in page differences might be strangely linear. "):
super().__init__(message)
self.message = message
def __str__(self):
return f"{self.message}"
class LowProportionError(Exception):
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."):
super().__init__(message)
self.message = message
def __str__(self):
return f"{self.message}"
#filter representative category
def representative_pages(ds,doc_toks,column:str):
#og len
l1 = len(doc_toks)
doc_toks_non_0 = [i for i in doc_toks if i !=0]
if len(doc_toks_non_0) / l1 < 0.2:
raise EmptyDocumentError(f"EmptyDocumentError : Pages with tokens: {len(doc_toks_non_0)}, Total pages: {l1}")
catover = category_overview_sd(doc_toks)
#border value for category with the highest proportion in the data
max_proportion = np.max(catover,axis=1)[1]
max_prop_cat = np.where(catover[1]==max_proportion)[0][0]
cat_lb = catover[2][max_prop_cat]
if len(catover[0]) == 1:
raise NoMixError()
if max_proportion < 0.5:
raise LowProportionError()
#if the highest category is the most likely
#is the most likely only get min,
#otherwise get the border of the next category too
if (np.max(catover,axis=1)[0] == max_prop_cat):
val = (ds[column] >= cat_lb)
else:
next_cat = max_prop_cat+1
cat_ub = catover[2,next_cat]
val = (ds[column] >= cat_lb) & (ds[column] < cat_ub)
return val
def compare_to_ref_line(dataset,ref_val:float,column_to_compare:str):
ratio_of_pass = np.mean(np.array(dataset[column_to_compare]) > ref_val)
return ratio_of_pass