#!/usr/bin/env python # coding: utf-8 # # Corrections of OCRd text in Trove's newspapers # # The full text of newspaper articles in Trove is extracted from page images using Optical Character Recognition (OCR). The accuracy of the OCR process is influenced by a range of factors including the font and the quality of the images. Many errors slip through. Volunteers have done a remarkable job in correcting these errors, but it's a huge task. This notebook explores the scale of OCR correction in Trove. # # There are two ways of getting data about OCR corrections using the Trove API. To get aggregate data you can include `has:corrections` in your query to limit the results to articles that have at least one OCR correction. # # To get information about the number of corrections made to the articles in your results, you can add the `reclevel=full` parameter to include the number of corrections and details of the most recent correction to the article record. For example, note the `correctionCount` and `lastCorrection` values in the record below: # # ``` json # { # "article": { # "id": "41697877", # "url": "/newspaper/41697877", # "heading": "WRAGGE AND WEATHER CYCLES.", # "category": "Article", # "title": { # "id": "101", # "value": "Western Mail (Perth, WA : 1885 - 1954)" # }, # "date": "1922-11-23", # "page": 4, # "pageSequence": 4, # "troveUrl": "https://trove.nla.gov.au/ndp/del/article/41697877", # "illustrated": "N", # "wordCount": 1054, # "correctionCount": 1, # "listCount": 0, # "tagCount": 0, # "commentCount": 0, # "lastCorrection": { # "by": "*anon*", # "lastupdated": "2016-09-12T07:08:57Z" # }, # "identifier": "https://nla.gov.au/nla.news-article41697877", # "trovePageUrl": "https://trove.nla.gov.au/ndp/del/page/3522839", # "pdf": "https://trove.nla.gov.au/ndp/imageservice/nla.news-page3522839/print" # } # } # ``` # ## Setting things up # In[1]: import os from operator import itemgetter # used for sorting import altair as alt import pandas as pd # makes manipulating the data easier import requests from IPython.display import FileLink, clear_output, display from requests.adapters import HTTPAdapter from requests.packages.urllib3.util.retry import Retry from tqdm.auto import tqdm # Make sure data directory exists os.makedirs("data", exist_ok=True) # Create a session that will automatically retry on server errors s = requests.Session() retries = Retry(total=5, backoff_factor=1, status_forcelist=[502, 503, 504]) s.mount("http://", HTTPAdapter(max_retries=retries)) s.mount("https://", HTTPAdapter(max_retries=retries)) # In[2]: get_ipython().run_cell_magic('capture', '', '# Load variables from the .env file if it exists\n# Use %%capture to suppress messages\n%load_ext dotenv\n%dotenv\n') # In[3]: # Insert your Trove API key API_KEY = "YOUR API KEY" # Use api key value from environment variables if it is available if os.getenv("TROVE_API_KEY"): API_KEY = os.getenv("TROVE_API_KEY") # In[4]: # Basic parameters for Trove API params = { "facet": "year", # Get the data aggregated by year. "zone": "newspaper", "key": API_KEY, "encoding": "json", "n": 0, # We don't need any records, just the facets! } # In[5]: def get_results(params): """ Get JSON response data from the Trove API. Parameters: params Returns: JSON formatted response data from Trove API """ response = s.get( "https://api.trove.nla.gov.au/v2/result", params=params, timeout=30 ) response.raise_for_status() # print(response.url) # This shows us the url that's sent to the API data = response.json() return data # ## How many newspaper articles have corrections? # # Let's find out what proportion of newspaper articles have at least one OCR correction. # # First we'll get to the total number of newspaper articles in Trove. # In[6]: # Set the q parameter to a single space to get everything params["q"] = " " # Get the data from the API data = get_results(params) # Extract the total number of results total = int(data["response"]["zone"][0]["records"]["total"]) print("{:,}".format(total)) # Now we'll set the `q` parameter to `has:corrections` to limit the results to newspaper articles that have at least one correction. # In[7]: # Set the q parameter to 'has:corrections' to limit results to articles with corrections params["q"] = "has:corrections" # Get the data from the API data = get_results(params) # Extract the total number of results corrected = int(data["response"]["zone"][0]["records"]["total"]) print("{:,}".format(corrected)) # Calculate the proportion of articles with corrections. # In[8]: print("{:.2%} of articles have at least one correction".format(corrected / total)) # You might be thinking that these figures don't seem to match the number of corrections by individuals displayed on the digitised newspapers home page. Remember that these figures show the **number of articles** that include corrections, while the individual scores show the **number of lines** corrected by each volunteer. # ## Number of corrections by year # In[9]: def get_facets(data): """ Loop through facets in Trove API response, saving terms and counts. Parameters: data - JSON formatted response data from Trove API Returns: A list of dictionaries containing: 'term', 'total_results' """ facets = [] try: # The facets are buried a fair way down in the results # Note that if you ask for more than one facet, you'll have use the facet['name'] param to find the one you want # In this case there's only one facet, so we can just grab the list of terms (which are in fact the results by year) for term in data["response"]["zone"][0]["facets"]["facet"]["term"]: # Get the year and the number of results, and convert them to integers, before adding to our results facets.append({"term": term["search"], "total_results": int(term["count"])}) # Sort facets by year facets.sort(key=itemgetter("term")) except TypeError: pass return facets def get_facet_data(params, start_decade=180, end_decade=201): """ Loop throught the decades from 'start_decade' to 'end_decade', getting the number of search results for each year from the year facet. Combine all the results into a single list. Parameters: params - parameters to send to the API start_decade end_decade Returns: A list of dictionaries containing 'year', 'total_results' for the complete period between the start and end decades. """ # Create a list to hold the facets data facet_data = [] # Loop through the decades for decade in tqdm(range(start_decade, end_decade + 1)): # print(params) # Avoid confusion by copying the params before we change anything. search_params = params.copy() # Add decade value to params search_params["l-decade"] = decade # Get the data from the API data = get_results(search_params) # Get the facets from the data and add to facets_data facet_data += get_facets(data) # Reomve the progress bar (you can also set leave=False in tqdm, but that still leaves white space in Jupyter Lab) clear_output() return facet_data # In[10]: facet_data = get_facet_data(params) # In[11]: # Convert our data to a dataframe called df df = pd.DataFrame(facet_data) # In[12]: df.head() # So which year has the most corrections? # In[13]: df.loc[df["total_results"].idxmax()] # The fact that there's more corrections in newspaper articles from 1915, might make you think that people have been more motivated to correct articles relating to WWI. But if you look at the [total number of articles per year](visualise-total-newspaper-articles-by-state-year.ipynb), you'll see that there's been more articles digitised from 1915! The raw number of corrections is probably not very useful, so let's look instead at the *proportion* of articles each year that have at least one correction. # # To do that we'll re-harvest the facet data, but this time with a blank, or empty search, to get the total number of articles available from each year. # In[14]: # Reset the 'q' parameter # Use a an empty search (a single space) to get ALL THE ARTICLES params["q"] = " " # Get facet data for all articles all_facet_data = get_facet_data(params) # In[15]: # Convert the results to a dataframe df_total = pd.DataFrame(all_facet_data) # No we'll merge the number of articles by year with corrections with the total number of articles. Then we'll calculate the proportion with corrections. # In[16]: def merge_df_with_total(df, df_total, how="left"): """ Merge dataframes containing search results with the total number of articles by year. This is a left join on the year column. The total number of articles will be added as a column to the existing results. Once merged, do some reorganisation and calculate the proportion of search results. Parameters: df - the search results in a dataframe df_total - total number of articles per year in a dataframe Returns: A dataframe with the following columns - 'year', 'total_results', 'total_articles', 'proportion' (plus any other columns that are in the search results dataframe). """ # Merge the two dataframes on year # Note that we're joining the two dataframes on the year column df_merged = pd.merge(df, df_total, how=how, on="term") # Rename the columns for convenience df_merged.rename( {"total_results_y": "total_articles"}, inplace=True, axis="columns" ) df_merged.rename({"total_results_x": "total_results"}, inplace=True, axis="columns") # Set blank values to zero to avoid problems df_merged["total_results"] = df_merged["total_results"].fillna(0).astype(int) # Calculate proportion by dividing the search results by the total articles df_merged["proportion"] = df_merged["total_results"] / df_merged["total_articles"] return df_merged # In[17]: # Merge the search results with the total articles df_merged = merge_df_with_total(df, df_total) df_merged.head() # Let's visualise the results, showing both the number of articles with corrections each year, and the proportion of articles each year with corrections. # In[18]: # Number of articles with corrections chart1 = ( alt.Chart(df_merged) .mark_line(point=True) .encode( x=alt.X("term:Q", axis=alt.Axis(format="c", title="Year")), y=alt.Y( "total_results:Q", axis=alt.Axis(format=",d", title="Number of articles with corrections"), ), tooltip=[ alt.Tooltip("term:Q", title="Year"), alt.Tooltip("total_results:Q", title="Articles", format=","), ], ) .properties(width=700, height=250) ) # Proportion of articles with corrections chart2 = ( alt.Chart(df_merged) .mark_line(point=True, color="red") .encode( x=alt.X("term:Q", axis=alt.Axis(format="c", title="Year")), # This time we're showing the proportion (formatted as a percentage) on the Y axis y=alt.Y( "proportion:Q", axis=alt.Axis(format="%", title="Proportion of articles with corrections"), ), tooltip=[ alt.Tooltip("term:Q", title="Year"), alt.Tooltip("proportion:Q", title="Proportion", format="%"), ], # Make the charts different colors color=alt.value("orange"), ) .properties(width=700, height=250) ) # This is a shorthand way of stacking the charts on top of each other chart1 & chart2 # This is really interesting – it seems there's been a deliberate effort to get the earliest newspapers corrected. # ## Number of corrections by category # # Let's see how the number of corrections varies across categories. This time we'll use the `category` facet instead of `year`. # In[19]: params["q"] = "has:corrections" params["facet"] = "category" # In[20]: data = get_results(params) facets = [] for term in data["response"]["zone"][0]["facets"]["facet"]["term"]: # Get the state and the number of results, and convert it to integers, before adding to our results facets.append({"term": term["search"], "total_results": int(term["count"])}) df_categories = pd.DataFrame(facets) # In[21]: df_categories.head() # Once again, the raw numbers are probably not all that useful, so let's get the total number of articles in each category and calculate the proportion that have at least one correction. # In[22]: # Blank query params["q"] = " " data = get_results(params) facets = [] for term in data["response"]["zone"][0]["facets"]["facet"]["term"]: # Get the state and the number of results, and convert it to integers, before adding to our results facets.append({"term": term["search"], "total_results": int(term["count"])}) df_total_categories = pd.DataFrame(facets) # We'll merge the two corrections by category data with the total articles per category and calculate the proportion. # In[23]: df_categories_merged = merge_df_with_total(df_categories, df_total_categories) df_categories_merged # A lot of the categories have been added recently and don't contain a lot of articles. Some of these have a very high proportion of articles with corrections – 'Obituaries' for example. This suggests users are systematically categorising and correcting certain types of article. # # Let's focus on the main categories by filtering out those with less than 30,000 articles. # In[24]: df_categories_filtered = df_categories_merged.loc[ df_categories_merged["total_articles"] > 30000 ] df_categories_filtered # And now we can visualise the results. # In[25]: cat_chart1 = ( alt.Chart(df_categories_filtered) .mark_bar() .encode( x=alt.X("term:N", title="Category"), y=alt.Y("total_results:Q", title="Articles with corrections"), ) ) cat_chart2 = ( alt.Chart(df_categories_filtered) .mark_bar() .encode( x=alt.X("term:N", title="Category"), y=alt.Y( "proportion:Q", axis=alt.Axis(format="%", title="Proportion of articles with corrections"), ), color=alt.value("orange"), ) ) cat_chart1 | cat_chart2 # As we can see, the rate of corrections is much higher in the 'Family Notices' category than any other. This probably reflects the work of family historians and others searching for, and correcting, articles containing particular names. # ## Number of corrections by newspaper # # How do rates of correction vary across newspapers? We can use the `title` facet to find out. # In[26]: params["q"] = "has:corrections" params["facet"] = "title" # In[27]: data = get_results(params) facets = [] for term in data["response"]["zone"][0]["facets"]["facet"]["term"]: # Get the state and the number of results, and convert it to integers, before adding to our results facets.append({"term": term["search"], "total_results": int(term["count"])}) df_newspapers = pd.DataFrame(facets) # In[28]: df_newspapers.head() # Once again we'll calculate the proportion of articles corrected for each newspaper by getting the total number of articles for each newspaper on Trove. # In[29]: params["q"] = " " # In[30]: data = get_results(params) facets = [] for term in data["response"]["zone"][0]["facets"]["facet"]["term"]: # Get the state and the number of results, and convert it to integers, before adding to our results facets.append({"term": term["search"], "total_results": int(term["count"])}) df_newspapers_total = pd.DataFrame(facets) # In[31]: df_newspapers_merged = merge_df_with_total( df_newspapers, df_newspapers_total, how="right" ) # In[32]: df_newspapers_merged.sort_values(by="proportion", ascending=False, inplace=True) df_newspapers_merged.rename(columns={"term": "id"}, inplace=True) # In[33]: df_newspapers_merged.head() # The `title` facet only gives us the `id` number for each newspaper, not its title. Let's get all the titles and then merge them with the facet data. # In[34]: # Get all the newspaper titles title_params = { "key": API_KEY, "encoding": "json", } title_data = s.get( "https://api.trove.nla.gov.au/v2/newspaper/titles", params=params ).json() # In[35]: titles = [] for newspaper in title_data["response"]["records"]["newspaper"]: titles.append({"title": newspaper["title"], "id": int(newspaper["id"])}) df_titles = pd.DataFrame(titles) # In[36]: df_titles.head() # In[37]: df_titles.shape # One problem with this list is that it also includes the titles of the Government Gazettes (this seems to be a bug in the API). Let's get the gazette titles and then subtract them from the complete list. # In[38]: # Get gazette titles gazette_data = s.get( "https://api.trove.nla.gov.au/v2/gazette/titles", params=params ).json() gazettes = [] for gaz in gazette_data["response"]["records"]["newspaper"]: gazettes.append({"title": gaz["title"], "id": int(gaz["id"])}) df_gazettes = pd.DataFrame(gazettes) # In[39]: df_gazettes.shape # Subtract the gazettes from the list of titles. # In[40]: df_titles_not_gazettes = df_titles[~df_titles["id"].isin(df_gazettes["id"])] # Now we can merge the newspaper titles with the facet data using the `id` to link the two datasets. # In[41]: df_newspapers_with_titles = ( pd.merge(df_titles_not_gazettes, df_newspapers_merged, how="left", on="id") .fillna(0) .sort_values(by="proportion", ascending=False) ) # In[42]: # Convert the totals back to integers df_newspapers_with_titles[ ["total_results", "total_articles"] ] = df_newspapers_with_titles[["total_results", "total_articles"]].astype(int) # Now we can display the newspapers with the highest rates of correction. Remember, that a `proportion` of 1.00 means that every available article has at least one correction. # In[43]: df_newspapers_with_titles[:25] # At the other end, we can see the newspapers with the smallest rates of correction. Note that some newspapers have no corrections at all. # In[44]: df_newspapers_with_titles.sort_values(by="proportion")[:25] # We'll save the full list of newspapers as a CSV file, but first we'll fix up the column headings and add urls for each title. # In[45]: df_newspapers_with_titles_csv = df_newspapers_with_titles.copy() df_newspapers_with_titles_csv.rename( {"total_results": "articles_with_corrections"}, axis=1, inplace=True ) df_newspapers_with_titles_csv["percentage_with_corrections"] = ( df_newspapers_with_titles_csv["proportion"] * 100 ) df_newspapers_with_titles_csv.sort_values( by=["percentage_with_corrections"], inplace=True ) df_newspapers_with_titles_csv[ [ "id", "title", "articles_with_corrections", "total_articles", "percentage_with_corrections", ] ].to_csv("titles_corrected.csv", index=False) df_newspapers_with_titles_csv["title_url"] = df_newspapers_with_titles_csv["id"].apply( lambda x: f"http://nla.gov.au/nla.news-title{x}" ) # Now we'll save the data as a CSV file and display a link. # In[46]: df_newspapers_with_titles_csv.to_csv("titles_corrected.csv", index=False) display(FileLink("titles_corrected.csv")) # ## Neediest newspapers # # Let's see if we can combine some guesses about OCR error rates with the correction data to find the newspapers most in need of help. # # To make a guesstimate of error rates, we'll use the occurance of 'tbe' – ie a common OCR error for 'the'. I don't know how valid this is, but it's a place to start! # In[47]: # Search for 'tbe' to get an indication of errors by newspaper params["q"] = 'text:"tbe"~0' params["facet"] = "title" # In[48]: data = get_results(params) facets = [] for term in data["response"]["zone"][0]["facets"]["facet"]["term"]: # Get the state and the number of results, and convert it to integers, before adding to our results facets.append({"term": term["search"], "total_results": int(term["count"])}) df_errors = pd.DataFrame(facets) # Merge the error data with the total articles per newspaper to calculate the proportion. # In[49]: df_errors_merged = merge_df_with_total(df_errors, df_newspapers_total, how="right") df_errors_merged.sort_values(by="proportion", ascending=False, inplace=True) df_errors_merged.rename(columns={"term": "id"}, inplace=True) # In[50]: df_errors_merged.head() # Add the title names. # In[51]: df_errors_with_titles = ( pd.merge(df_titles_not_gazettes, df_errors_merged, how="left", on="id") .fillna(0) .sort_values(by="proportion", ascending=False) ) # So this is a list of the newspapers with the highest rate of OCR error (by our rather dodgy measure). # In[52]: df_errors_with_titles[:25] # And those with the lowest rate of errors. Note the number of non-English newspapers in this list – of course our measure of accuracy fails completely in newspapers that don't use the word 'the'! # In[53]: df_errors_with_titles[-25:] # Now let's merge the error data with the correction data. # In[54]: corrections_errors_merged_df = pd.merge( df_newspapers_with_titles, df_errors_with_titles, how="left", on="id" ) # In[55]: corrections_errors_merged_df.head() # In[56]: corrections_errors_merged_df["proportion_uncorrected"] = corrections_errors_merged_df[ "proportion_x" ].apply(lambda x: 1 - x) corrections_errors_merged_df.rename( columns={ "title_x": "title", "proportion_x": "proportion_corrected", "proportion_y": "proportion_with_errors", }, inplace=True, ) corrections_errors_merged_df.sort_values( by=["proportion_with_errors", "proportion_uncorrected"], ascending=False, inplace=True, ) # So, for what it's worth, here's a list of the neediest newspapers – those with high error rates and low correction rates! As I've said, this is a pretty dodgy method, but interesting nonetheless. # In[57]: corrections_errors_merged_df[ ["title", "proportion_with_errors", "proportion_uncorrected"] ][:25] # ---- # # Created by [Tim Sherratt](https://timsherratt.org/) for the [GLAM Workbench](https://glam-workbench.github.io/). # Support this project by becoming a [GitHub sponsor](https://github.com/sponsors/wragge?o=esb).