Full text
Title: Creation of an open data federated platform Author: Marc Vernet Sancho Advisor: Sergi Nadal Department: ESSI Month and year: June 2022 Degree in Data Science and Engineering Facultat d’Informàtica de Barcelona Facultat de Matemàtiques i Estadística Escola Tècnica Superior d'Enginyeria de Telecomunicació de Barcelona
Acknowledgements First, I would like to thank my supervisor Sergi Nadal, for all the help and guidance during the project development. He not only had the first idea for this project’s topic, but without his guidance the end result would have been very different. I would also like to thank my family for the unconditional support, not only during the development of this thesis but also during these last four years, with its good and bad moments. Specially to my father, for criticizing my work relentlessly, which greatly contributed to making this thesis what I want to believe is (almost) its best version possible. Finally, I would like to end by thanking my job colleagues, who have seen me countless early mornings working on this thesis from the office, and made all those moments more funny and enjoyable.
Abstract The goal of this thesis is to design and build a web platform that integrates access to data from several Open Data portals. This platform will be used as a tool to explore and showcase the results of different techniques of data discovery, with the goal of developing and implementing a method to efficiently detect similarities and datasets that can be joined. This thesis is highly practical, and is focused on explaining the technical decisions and implementation details behind the final tool developed. With the popularization of Open Data platforms the amount of data available on the internet is growing exponentially, and with it the question of how to extract value of such large amounts of data. This project not only looks for a way to unify the data in a single place, but also for ways to be able to explore this data, making special emphasis on ways to detect similarities between datasets. The project initially revolved around the data provided from the municipal open data portals from Barcelona and L’Hospitalet de Llobregat, but the final solution is meant to be scalable and easily adaptable to other data sources. The initial idea for this thesis was to be focused mainly on exploring methods for detecting similarity and joinability between datasets based on profiles, but during development, it became obvious that the infrastructure required to unify all the datasets and provide a tool to explore the data was not simple at all. So in the end, a big part of the thesis consists of the discussion of technical decisions made and details of the tool built for the project.
Resum L’objectiu d’aquesta tesi ´es dissenyar i construir una plataforma web que integri l’acc´es a dades de diferents portals de Dades Obertes. Aquesta plataforma es far`a servir com a eina per explorar i mostrar els resultats de diferents t`ecniques de ”Data Discovery”, amb l’objectiu de desenvolupar i implementar un m`etode per, de forma eficient, detectar similituds i datasets als quals es pot aplicar una operaci´o de ”join”. Aquesta tesi ´es altament pr`actica, i est`a centrada en descriure les decisions t`ecniques i detalls d’implementaci´o al darrere de la versi´o final de l’eina desenvolupada. Amb la popularitzaci´o dels portals de Dades Obertes la quantitat de dades disponibles a internet est`a creixent de forma exponencial, i amb aquest creixement sorgeix la pregunta de com extreure valor d’aquesta quantitat de dades enorme. Aquest projecte no nom´es busca una manera d’unificar les dades en un sol lloc, sin´o tamb´e trobar maneres d’explorar aquestes dades, fent especial `emfasi en m`etodes per detectar similituds entre datasets. El projecte inicialment girava al voltant de les dades proporcionades pels portals de Dades Obertes municipals de Barcelona i l’Hospitalet de Llobregat, per`o la soluci´o final t´e l’objectiu de ser escalable i f`acilment adaptable a altres fonts de dades. La idea inicial per aquesta tesi era centrar-se principalment a explorar m`etodes per detectar similitud i ”joins” entre els datasets basats en perfils, per`o durant el desenvolupament, va esdevenir obvi que la infraestructura requerida per unificar tots els datasets i proporcionar una eina per explorar-los no era una tasca gens senzilla. Com a conseq¨u`encia, finalment una gran part d’aquesta tesi consisteix en la discussi´o de les decisions t`ecniques fetes i dels detalls de l’eina constru¨ıda per al projecte.
Resumen El objetivo de esta tesis es dise˜nar y construir una plataforma web que integre el acceso a datos de diferentes portales de Datos Abiertos. Esta plataforma se utilizar´a como herramienta para explorar y mostrar los resultados de distintas t´ecnicas de ”Data Discovery”, con el objetivo de desarrollar e implementar un m´etodo para, de forma eficiente, detectar similitudes y datasets a los cuales se les pueda aplicar una operaci´on de ”join”. Esta tesis es altamente pr´actica, y est´a centrada en describir las decisiones t´ecnicas y detalles de implementaci´on detr´as de la versi´on final de la herramienta desarrollada. Con la popularizaci´on de los portales de Datos Abiertos la cantidad de datos disponibles en internet est´a creciendo de forma exponencial, i con este crecimiento surge la pregunta de como extraer valor de esta cantidad de datos enorme. Este proyecto no solo busca una forma de unificar los datos en un mismo sitio, sino tambi´en encontrar maneras de explorar estos datos, haciendo especial ´enfasis en m´etodos para detectar similitudes entre datasets. El proyecto inicialmente giraba alrededor de los datos proporcionados por los portales de Datos Abiertos municipales de Barcelona y L’Hospitalet de Llobregat, pero la soluci´on final tiene el objetivo de ser escalable y f´acilmente adaptable a otras fuentes de datos. La idea inicial para esta tesis era centrarse principalmente en explorar m´etodos para detectar similitud y ”joins” entre datasets basados en perfiles, pero durante el desarrollo, result´o obvio que la infraestructura requerida para unificar todos los datasets y proporcionar una herramienta para explorarlos no era una tarea nada sencilla. Como consecuencia, finalmente, una gran parte de esta tesis consiste en la discusi´on de las decisiones t´ecnicas hechas y de los detalles de la herramienta construida para el proyecto.
Contents 1 Introduction and Contextualization 2 1.1 Motivation ................................. 2 1.2 What is an Open Data platform ..................... 4 1.2.1 Data catalog features ....................... 4 1.3 Resources used .............................. 5 1.3.1 Open Data BCN ......................... 6 1.3.2 Dades Obertes L’Hospitalet ................... 7 2 Data Discovery 9 2.1 Defining the problem ........................... 9 2.2 Previous work ............................... 11 2.3 A first solution .............................. 12 2.4 Similarity based on profiles ........................ 16 3 Implementation Scope 20 3.1 General objectives ............................ 20 3.2 Functional requirements ......................... 20 3.3 Non-functional requirements ....................... 21 3.4 Design ................................... 22 3.4.1 Implementation details ...................... 23 4 Back-end Implementation 24 4.1 Scrapers .................................. 24 4.1.1 Scraping the Barcelona portal .................. 25 4.1.2 Scraping L’hospitalet portal ................... 25 4.2 TinyDB and storage ........................... 25 4.3 API .................................... 26 4.4 Upload ................................... 28 5 Front-end Implementation 30 6 Unsuccessful implementations 37 7 Further work 39 8 Conclusions 41 9 Annex 42 9.1 Published code .............................. 43 9.2 Instructions for deployment ....................... 45 9.2.1 Back-end ............................. 45 9.2.2 Front-end ............................. 46 1
Figure 4: Dades Obertes Hospitalet home page Figure 5: Dades Obertes Hospitalet catalog 8
2 Data Discovery Data discovery can be defined as the process of exploring a group of datasets in order to find relations between them. These relations can be obtained by means of applying complex analysis in order to detect patterns in the contained data. Data Discovery is a vital process for any data science project, understood as the process of finding relevant data among a huge collection of datasets. Data Discovery can be considered part of the preprocessing required before starting the proper machine learning in a dataset, together with data cleaning for example. Data Discovery is more of an heuristic problem, without a clear solution, it is very time intensive for the user and there aren’t efficient computational solutions, taking into account the large amounts of data used. Data discovery processes can be divided into manual methods and smart or automated methods. Manual discovery is, as its name indicates, the manual classification by a human. Datasets are organized in categories, described and standardized for future use. The manual method is effective for very small collections of data, but it’s not scalable at all, and it’s not an option with the huge amount of data available nowadays. The smart method provides an automated solution that with the help of data mining and machine learning methods is capable of discovering patterns in data collections. Automatized data discovery is still an open problem in the computer science community, the complexity of the task and increasing amount of data makes it very difficult to find an efficient solution. There’s tendency in the business world of becoming a “data-driven” company [9], a company where business decisions are taken using collected data as a perspective of the company performance, and building the business with data generation from the first moment, in order to have large amounts of it for decision taking. So, taking into account this tendency and the exponential growth of available data on the internet (such as government open data portals), the amount of available data makes it necessary to develop automated data discovery tools. Effective data discovery is essential for any kind of data analytic, as data found and its quality will directly affect the final result. 2.1 Defining the problem On this project, the data discovery is focused around tabular data. Most of the data available in open data portals is tabular data, usually in csv format. Although there is a tendency of trying to adopt NoSQL databases in many businesses, most of the data available is still in tabular datasets. Also, the most notable previous work on the field is based on tabular datasets [10]. A data discovery process can return as a result different metrics about the datasets, as the profiling can be done in different levels (dataset level, attribute level, . . . ). The expected result for this thesis are: •Defining similarity measures between datasets, based on the contents of the datasets and the metadata provided. Using this similarity to detect duplicate 9
datasets that can be unioned. •Defining a similarity measure between dataset columns. Using the column similarity to detect columns from different datasets that represent the same variable, and that can be joined. Determining the similarity between two datasets is a very complex task, because there isn’t a clear definition of similarity and there are many variables to measure. A dataset could be understood as a set of attributes, each attribute consists of a name and a list of values (Eq.6). The similarity between attributes can be measured in different ways, but defining the similarity between two datasets remains a complex task. Di={Ai1, ..., Ain} Dj={Aj1, ..., Ajn} Di▷◁ Dj=⇒ ∃k:Aik≈Ajk Equation 6: Two datasets are joinable if they share a common atribute [11] In this project, the representation of the datasets in order to calculate similarities will be based on profiles. Profiles are representations of datasets that contain information about its schema and data values [12]. Some common similarity techniques are: •Comparison by value. This method is based on comparing the exact values contained in the datasets. This is the most precise method but its also the most complex and difficult to scale. •Comparison by hash. In this approach, similarity is measured comparing the output of hash functions. •Comparison by profile. With profile methods, some important features are extracted from the datasets to build the profiles, that can be compared between them to find common information. Figure 7: Efficiency of different approaches. The table is extracted from [12] As it can be seen in the Figure 7, there is a direct trade-off between exactitude of the result and computational expensiveness. Finding exact results needs a significantly 10
larger amount of resources, while approximate results can be found more easily. As the goal of this project is to apply data discovery to a real web app with a potential large amount of datasets in catalog, scalability is key and the efficiency of calculations has to be maximized. For these reasons the solutions studied will revolve around dataset profiles. Methods based on profiles allows for using a summary of the data available condensed in the form of profile, in this way much less data needs to be processed and a much better performance in terms of calculation speed can be obtained. The trade-off is that the profiles are only approximate representations of the data contained in the dataset or attribute, so the results will also be approximated. 2.2 Previous work Data Discovery is a problem with extensive research done, but it is a problem still not solved. The current state-of-the-art solutions still does not provide a satisfactory result, with the main issue being the trade-off between precision and computational speed [12]. As it was discussed before the different methods for data discovery lack the efficiency to be deployed on real-time web use cases, with the exception of the profile method that sacrifices precision for speed. Research seems to indicate that relying on profiles is the way to go in order to reach a satisfactory scalability, and NextiaJD 3was one of the first software to explore this approach [12]. NextiaJD is a software developed at UPC, it is a tool that extracts a complex profile from a dataset(Fig.8). These profiles are used to calculate joinability between datasets, and in this way detect pairs of attributes that can be crossed. One of the limitations of NextiaJD is that it only considers categorical attributes. Some further research has been done to develop machine learning models to predict dataset jonability based on the profiles generated by NextiaJD. There has also been research around building graph neural networks to predict joinability [13]. The conclusions from the NextiaJD paper were that profile based methods could be a solution for the scalability problem, but that there were still some unresolved challenges on how to satisfactorily identify joins. The similarity methods explored in this thesis are pretty much inspired by the research done in NextiaJD, but there is a strong focus in providing a solution that can be implemented in a web context. So there’s much more focus in producing a solution that is scalable rather than in bettering the prediction results from NextiaJD. 3Repository can be found at https://github.com/dtim-upc/NextiaJD 11
Figure 8: Profiles generated by NextiaJD. The table is extracted from [13] 2.3 A first solution The datasets used in this project all come from open portal data, so it is worth studying what kind of data these portals provide. Usually, the open data portals not only host the dataset itself, but also provide a lot of relevant information and metadata about it. All of this information it’s already provided for free by the portal itself, and it might be interesting to use it. Some additional data provided by both Barcelona and Hospitalet portal: •Dataset title •Text description of the dataset •Category •Publish date From these variables, it seems that categories could directly be used to classify the datasets in groups. The issue with it is that categories might differ a lot between different portals, so it’s not a good way to cluster datasets. This leaves us with the dataset title and description which are interesting. Having a description of the dataset provides a lot of information that can allow a human to understand what a dataset is about. Using the dataset title and description, a human would be 12
capable of approximating the similarity between two datasets. Now the challenge is to translate this into an algorithm. We have a set of datasets D, where each dataset is composed of a title tand a description d. D={D1, ..., Dn} Di={tDi, dDi} We can assume that we have a function sim that returns the similarity between two text strings. In this case, we can have two functions that respectively return the similarity between titles and descriptions. With those similarities we can have a third function that aggregates both results into a single similarity(Eq.9). Finally, the challenge is to come up with a sim function as an S function. S(St, Sd) := similarity between two datasets St(D1, D1) = sim(tD1, tD2) Sd(D1, D1) = sim(dD1, dD2) sim(text1, text2) := similarity between two texts Equation 9: Dataset similarity based on title(t) and description(d) For this algorithm we are only concerned with the title and description of the dataset, ignoring schema, profile and internal values. The goal is to find a minimum viable similarity that can be obtained only with the resources already provided by the open data portals. In order to obtain a representative representation, both title and description are preprocessed. The preprocessing consists of first eliminating punctuation signs and transforming all the words to the lowercase. After that all stopwords are removed to keep only significant words. All the descriptions used for the similarity calculation are in Catalan, so the stopword dictionary used is also in Catalan [14]. The result is a set of key words found in the text, that will be useful to identify similarities. The similarity function will be derived from Tf-idf (Eq.10). Tf-idf (term frequency - inverse document frequency) is a statistical function that intends to represent how important a word is in a document in relation to a collection of documents. The Tf-idf value increases proportionally to the number of times a word appears in the document and is offset by the number of documents in the corpus that contain the word, which helps to adjust for the fact that some words appear more frequently in general. 13
wi,j =tfi,j ∗log N dfi tfi,j = number of ocurrences of iin j dfi= number of documents containing i N= total number of documents Equation 10: Tf-idf equation Tf-idf is often used by search engines for ranking a document’s relevance based on a query. A survey conducted in 2015 showed that 83% of text-based recommender systems in digital libraries use Tf-idf [15]. Tf-idf is implemented using the sklearn library[16]. The similarities are calculated separately for the titles and descriptions. First, the texts are all condensed together in a vector that is imputed into the vectorizer function. The output is a Tf-idf vector that contains values for all the texts. Last step is to multiply it by its transpose, and the result is a matrix of similarities between all the texts. In the following piece of code it can be seen the process of generating a similarity matrix for all datasets. 1from sklearn . feature_extraction . text import TfidfVectorizer 2 3vect = TfidfVectorizer ( min_df =1) 4tfidf = vect . fit_transform ( text ) 5pairwise_similarity = tfidf * tfidf .T At this moment, we have two similarity matrices, one for the titles and one for the descriptions. A way to unify both results needs to be found, and the proposed one is defined on equation 11. sim(Di, Dj) = α∗simtitle[i, j] + (1 −α)∗simdescription[i, j] α∃[0,1] Equation 11: Equation to unify title and description similarities The equation is a weighted sum, the αparameter defines the relation between both values. A high αgives more importance to the title, while a close to zero αgives more importance to the description similarity. The resulting similarity is a value between 0 and 1, where 1 indicates that both texts are identical. In the following examples, it can be seen that the result is very satisfactory. The following results are first only comparing title similarities, then only description similarities and finally both with the described equation. It can be seen that the 14
results are very related to the original text, sharing a lot of keywords (Barcelona, Gu`ardia Urbana, accidents, . . . ) and always sharing the same topic. The most similar text is always the same text itself with a 1. Text similarity % Accidents gestionats per la Gu`ardia Urbana a la ciutat de Barcelona segons tipologia original Accidents gestionats per la Gu`ardia Urbana a la ciutat de Barcelona segons tipologia 0.99 Accidents gestionats per la Gu`ardia Urbana a la ciutat de Barcelona 0.88 Persones involucrades en accidents gestionats per la Gu`ardia Urbana a la ciutat de Barcelona 0.70 Persones involucrades en accidents gestionats per la Gu`ardia Urbana a la ciutat de Barcelona 0.70 Descripci´o de la causalitat dels accidents gestionats per la Gu`ardia Urbana a la ciutat de Barcelona 0.66 Table 1: Similarity with original title. 15
Text similarity % Llistat dels tipus d’accidents gestionats per la Gu`ardia Urbana a la ciutat de Barcelona. Un accident pot estar tipificat com m´es d’un tipus ( ex: caiguda (dues rodes) i abasti). original Llistat dels tipus d’accidents gestionats per la Gu`ardia Urbana a la ciutat de Barcelona. Un accident pot estar tipificat com m´es d’un tipus ( ex: caiguda (dues rodes) i abasti). 1.0 Llistat dels vehicles implicats en accidents gestionats per la Gu`ardia Urbana a la ciutat de Barcelona. Un accident pot tenir associat m´es d’un vehicle. Inclou si la causa ´es del vianant, el tipus de vehicle, model, marca, color i tipus carnet i antiguitat de la persona que ho condu¨ıa. 0.41 Llistat de de la causalitat dels accidents gestionats per la Gu`ardia Urbana a la ciutat de Barcelona. Un accident pot tenir una o m´es causes mediates les quals fan refer`encia a factors externs del resultat en temps, lloc o grau (ex: Alcohol`emia i Exc´es de velocitat o inadequada). 0.33 Llistat dels accidents gestionats per la Gu`ardia Urbana a la ciutat de Barcelona. Incorpora el n´umero de lesionats segons gravetat, el n´umero de vehicles implicats i el punt d’impacte. 0.23 Llistat de les persones que han estat involucrades en un accident gestionats per la Gu`ardia Urbana a la ciutat de Barcelona i que han sofert algun tipus de lesi´o ( ferit lleu, ferit greu o mort). Inclou descripci´o de la persona (conductor, passatger o vianant), sexe, edat, vehicle associat a la persona i si la causa ha sigut del vianant. 0.20 Table 2: Similarity with original description. 2.4 Similarity based on profiles The solution explained in the last section returns good results, but it completely ignores the data in the dataset itself. The problem with the text similarity solution is that it depends entirely on the description provided from the open data portal, which could be misleading and not be related to the dataset contents at all. In some cases the portal might not provide a description of the dataset, or we might want to compare it with a dataset out of context (not coming from an open data portal). Apart from that, we are leaving on the table a lot of valuable information from the insides of the dataset. To sum up, the text based solution is good to have a fast recommendation system 16
that is able to detect related datasets (related in terms of topic) very fast. It is not a good solution to detect joinable datasets, where we are more interested in detecting similarities between columns. The benefits in finding joinable datasets is that when joined, the data can be augmented with attributes from both datasets. Two datasets are considered joinable if a join operation can be performed between them. A join operation is an operation that combines columns from one or more tables into a new table. So, we can consider that if two datasets have a column in common then they are joinable, the more columns in common the highest is the probability of a satisfactory join. Taking into account these observations, the problem can be divided into two parts, first finding a similarity measure between columns, and second , aggregating datasets by the number of common columns. We have a set of datasets D. Each dataset Dnhas an arbitrary number of attributes Ai. D={D1, ..., Dn} Di={A1, ..., An} We define three functions. Pis the profile calculating function that outputs a profile from an attribute (details on implementation will be seen further). Then there’s a similarity function between profiles and a function that calculates the ease of join from the two datasets. P(A) sima(P(A1), P(A2)) J(D1, D2) First step is to define what is the profile that will be used and how to extract them. The first idea on this project was to use NextiaJD as a generator of profiles. NextiaJD is able to generate extremely detailed profiles from datasets. Its profiles consist of a set of around 30 variables measuring things such as cardinality, distribution of words, syntactic data, . . . . NextiaJD outputs one profile from the whole dataset, so there’s no way of identifying individual column similarities. The creators of NextiaJD also developed a machine learning algorithm that is capable of predicting the joinability between two profiles generated with NextiaJD. An issue with NextiaJD is that it only considers categorical attributes, so numerical attributes are ignored(Fig.8). When trying to implement NextiaJD in this problem there were several issues that ended up not being possible (which are detailed in a further section). The main reason was that it was too slow to run in real time. The goal of this project is to develop an implementation that can be used in real time by multiple users, so it’s not feasible to use a heavy tool like NextiaJD. 17
4 Back-end Implementation The back-end can be logically structured in four areas. These areas are interconnected among them and provide different utilities that are unified and accessed through the API(Fig.16). This four components are: •Scraping tool: Tool to extract the necessary data from the Barcelona and Hospitalet portals. The scraping is only used to obtain the initial data for the portal, but the idea is that adding data from new data sources should not require a scraper. •Upload: Code and data packages used to add data from new data sources into the database. The upload tool should be used to add new data sources through a csv file instead of scraping. •Similarity Calculation: Code to calculate dataset similarity, joinability, and its respective recommendations. •Database: TinyDB database that holds data and API to access it. Figure 16: Back-end detailed structure 4.1 Scrapers In the final product, new data sources should be added via the upload folder. These new data sources should follow the specified format and have all the information in a csv file. The idea is that third parties that would be interested in having their data available in this platform would provide the data in the specified format. To populate the initial proof of concept for this project some kind of data was needed, in this case the data from Barcelona and L’Hospitalet. This data was not available in the specified format required to upload it with the upload tool, but it was scattered through APIs and the websites itself. The solution was to create one script for each of both data sources that extracts the 24
data from their websites(Fig.17). There’s one additional script that unifies the data from both sources into the common format, (generateCatalog.py). The scraping script differs a lot from both data sources, because of the particularities of each portal. Figure 17: Detailed structure of scraper scripts 4.1.1 Scraping the Barcelona portal Obtaining the data from the Barcelona portal was very easy, because the website provides access to a csv catalog with information of all available datasets. It was only necessary to transform the data to a common format. The Barcelona portal also provides an API, but it was not necessary to get the initial data, because everything needed was contained in the csv catalog. 4.1.2 Scraping L’hospitalet portal The Hospitalet portal doesn’t provide such a catalog, so it was much more difficult to obtain the data. It also has an API, but because it doesn’t have an available catalog, it is not possible to access all the endpoints. Besides, many API endpoints weren’t working. It was necessary to access the html code and move page by page retrieving the desired data. 4.2 TinyDB and storage TinyDB is the database service used in the project. It is a very simple document oriented database that can be used in Python. It is basically a json format file that hosts rows of data and can be accessed with simple queries. The following piece of code is an example of some of the functionalities of TinyDB. 1from tinydb import TinyDB , Query 2db = TinyDB ( ’path /to/db. json ’) 3User = Query () 4db . insert ({ ’name ’:’John ’,’age ’: 22}) 5db . search ( User . name == ’John ’) 6# Output : [{ ’name ’: ’John ’, ’age ’: 22}] In the first iterations of the project a csv file was used instead, but for the final implementation a more robust solution was needed. TinyDB allows for a more easy 25
access of the data and simplifies the code a lot. It’s also not acceptable from an scalability standpoint to use a csv as “database”. TinyDB is a simple solution that works well for this project, because it’s just a json file that can be hosted together with the Python scripts. Because this project is just a proof of concept, this solution is enough, but in a real use case a proper database should be used. The following text is an example of how an item is stored in TinyDB’s json file. 1"1": { 2" index ": 0, 3" title ":" Unitats administratives de la ciutat de Barcelona ", 4"description":" Detall de les unitats administratives de la ciutat de Barcelona : districtes , barris , \ u00e0rea inter \ u00e8s , \ u00e0rees estad \ u00edstiques b\ u00e0siques ( AEB ) i seccions censals ", 5" category ":"Administraci\u00f3", 6"date_published":"2017-07-06", 7"source":" Ajuntament de Barcelona ", 8"web_url": 9" https :// opendata - ajuntament . barcelona . cat / data /ca/ dataset ?q=& name =20170706 - districtes - barris " , 10 "download_url":" https :// opendata - ajuntament . barcelona . cat /data / dataset /808 daafa - d9ce -48 c0 -925 afa5afdb1ed41 / resource /4 cc59b76 - a977 -40 ac -8748 -61217 c8ff367 / download " , 11 "status":"-", 12 "origin":" Barcelona " 13 } 4.3 API The API is one of the most important elements of the back-end. Its function is to allow communication between the back-end and external elements, it’s used to access its data and modify it from the front-end. As described previously, the API is built with FastAPI, a Python framework that allows easy building of REST APIs. REST is an architectural design for APIs that is based on resources with unique endpoints that can be accessed with an http request. All resources hosted on the server can be accessed via the API with a unique endpoint that is an url. The communication between server and client is stateless, meaning that no user information is stored during requests and that each request is separated and unconnected. The API is based around two files(Fig.18): •functions.py: All the complex functions that the API needs are defined here. Basically it handles all the calculations requested from the API and the access to all the internal resources. •main.py: Interface of the API, it hosts the FastAPI endpoints and accesses the functions on functions.py. 26
The use cases of the API are: •Accessing the TinyDB database in order to retrieve information about individual datasets or the whole catalog. •Access files representing similarity calculations for the text similarity. •Execute the functions required to calculate the profiles of a dataset and joinability. •Generating and updating the json files that populate the front-end based on TinyDB data. •Accessing the json files for the front-end It’s important to note that this API, together with TinyDB works on a proof of concept basis. The number of datasets contained in the catalog is small enough for the API to handle and send all the information togheter in one packet. In a real live solution it wouldn’t be possible to send all the catalog data in one packet. API endpoints: •/catalog –Returns the complete catalog with information from all the datasets –As a proof of concept works, but in case of scalability of the website with a large number of datasets, an alternative solution should be designed, to retrieve datasets in batches. •/item/{itemId} –Returns all the information of an individual dataset. –Needs itemId as a parameter, id of dataset that wants to be retrieved •/frontend/MainPage –Data required to populate MainPage.js •/frontend/Catalog –Data required to populate Catalog.js •/frontend/DataSource/{source} –Data required to populate DataSource.js –The parameter source is the identifier of the data source 27
Figure 18: Detailed structure of API scripts 4.4 Upload The upload tool is meant to be an utility to easily update and upload content to the database and automatically distribute the new content among the different areas of the back-end and the front-end(Fig.19). The main utility is to allow for upload of large packets of datasets from a new data source, but it also allows for updating the current data sources with new datasets. The way it works is by receiving the new data in a specific format and first introducing it in the TinyDB database and second updating the data in the front-end. The idea is that new data can be introduced effortlessly with one click, and that the whole front-end and back-end will accommodate it without further action needed from the user. The main peculiarity of the implementation is that new data has to be inputted in a specific format in order to be read correctly. The packed with the new data has to be introduced in the backed files, in further work an interface for uploading could be built on the front-end, but this also meant building an authentication system to allow only an administrator to modify data, and it was out of the scope for this project. The new data has to be introduced in a folder with the name of the data source on /upload/uploadPackets and it has to contain the following elements: •newData.csv •config.json The data about the new datasets introduced will be contained in newData.csv, which needs to provide a specific set of attributes in the same order in order to be read properly. The configuration file config.json contains the metadata about the 28
data source that will be used mainly to populate the front-end with the new data source. The following text is an example of the data required on the config.json file, and the table is a description of the columns on newData.csv. 1{ 2" databaseIdentifier ":"generalitat", 3" frontendIdentifier ":" Generalitat de Catalunya " , 4" title ":" Dades Obertes Catalunya " , 5"description": [ 6"...","..."," ..." 7], 8"shortDescription":" Datasets de la Generalitat de Catalunya ", 9"api":"yes" 10 } Variable name Description % title Title of the dataset description Text describing the dataset content category Category in which the dataset pertains inside the original dataset collection date published Publishing date of the dataset. Can be empty source Creator of the dataset web url URL that redirects to the website where the original dataset is hosted. download url URL to download file. Important to be able to identify similar columns status Identify the http status of the download url. Optional variable origin Dataset collection identifier Table 3: Columns of newData.csv Figure 19: Detailed structure of upload scripts 29
5 Front-end Implementation In order for the back-end functionalities to be accessed a user interface is required. For this project the option was to create a website, as the goal of it is to be publicly accessible. This website is supposed to be a way for any user to interact with the back-end, the basic functionalities provided are: •Explore the data catalog and download or access the original dataset source •See recommendations for a specific dataset, either based on description similarity or on profile joinability. •Have information about the several data sources available. •Provide a platform for users to submit new data. As mentioned before the front-end is built using React. This framework allows to design reusable components that can be then used in several different places. Other peculiarities are the use of the Router library [24] that allows linking the different pages with unique urls(Fig.21) and MaterialUI[25], a front-end library that is used for most of the UI design. The front-end is designed in conjunction with the API, in a way that all its content is automatically adapted from the API(Fig.20). All the datasets showcased on the front-end are fetched from the API, together with the data sources information and metadata. Thanks to React functionality [26] the information from the API is fetched every time the page is refreshed, so the information is always updated. Figure 20: Diagram of front-end API calls 30
Figure 21: Diagram of front-end Router connections 31
Each of the following files renders a page on the website. App.js This file is one of the only ones that doesn’t render a page on the website. This is the initial page the browser accesses and it contains the routing endpoints for the rest of pages. MainPage.js The main page(Fig.22) acts as a “home” for the website, it’s the first page that users will see. It includes a header space that should provide some initial information about the website. After that there’s a link to the catalog of datasets. There’s a section with information of all the data sources available on the website and a list of all the categories. Figure 22: Screenshot of MainPage.js render Catalog.js The catalog page(Fig.23) provides access to the whole collection of available datasets. Its intention is to allow the user to browse the collection and search for specific datasets. It contains search functionality based on the description text and title and the search can also be filtered by category or by the dataset source. Only 10 datasets are shown at the same time, and there’s a functionality to advance the page. 32
Figure 23: Screenshot of Catalog.js render Contribute.js The goal of this page(Fig.24) is to make it possible for external users to contribute to the website catalog, and propose the addition of new data sources to it. In order to add new data, users are expected to provide a catalog of datasets in csv in a required format. The format is very important to follow the guidelines, otherwise it cannot be automatically introduced into the database, that’s the reason why there’s an example row with all the necessary columns and a description of each one of them. The page links to a Google Form(Fig.25) that lets the user upload the csv together with some basic information. The answers to the form are received by the owner of the portal, who can decide whether to introduce the submitted information in the catalog. The form to submit the data was chosen because it was much easier than implementing an upload mechanism in the website itself. As future work, it would be interesting to have a way to submit directly from the website. 33
documented to make a deployment straightforward once there’s an available server. 40
8 Conclusions In general, the requirements defined during the thesis were accomplished with the delivered result. Developing and building the tool can be considered a success, as the resulting website can be used for its intended purpose, that is exploring a unified catalog of datasets. Also, the exploration of similarity measures between datasets resulted in an acceptable method that is proved to deliver good results. The general objectives described in the “Implementation scope” section are satisfied, and although as described on the “Further work” chapter there are a lot of missing things that could be implemented, the current functionalities work in an expected way and as a proof-of-concept it’s enough to have an overview of the possibilities of such tool. In regards to the search for an efficient similarity measure, the approaches explored in this thesis are much simpler than the ones done in previous work. Mainly because of the failure in trying to integrate NextiaJD into the solution, it was forced to look for simpler ways to calculate similarity and joinability. The final solution is an approximation to similarity calculation, but this approximation is traded for a much easier calculation process that allows for true scalability in a website context. The resulting recommendations from the similarity and joinability calculations seem to be good enough. It seems that in a web context where users are more interested in having a recommendation from a huge pool of available datasets, the precision of the recommendation is not something indispensable, and that an approximate recommendation is good enough for users to discern a small set of interesting datasets from the total of the collection. Finally, there’s plenty of lessons learned from the process of building this tool. First is the appreciation for the complexity of building a website with this amount of integrated parts. From the outside it can seem easy, but connecting all the parts and having a global vision of such a huge codebase is a challenge. As lessons learned, the main one is about organization. This project started with a general vision of its direction, and new ideas and features were added with time. This was a big challenge in how to manage the codebase to add these changes, and the issues of not starting with a clear vision of the project were evident. In many cases it was needed to fully refactor parts of the code that were no longer useful or required big changes. All of this added a lot of working hours that could have been avoided with a better planning from the beginning, an example of this issues was the decision of abandoning the idea of integration NextiaJD after hours and hours trying to make it work. 41
9 Annex 42
9.1 Published code The final code is publicly available on two Github repositories, one for the frontend and one for the back-end. The decision of storing the code in two different repositories is that the back-end and front-end are independent and and be hosted on two different places different. •Front-end repository: https://github.com/marcvernet31/TFG-frontend •Back-end repository: https://github.com/marcvernet31/TFG-backend The structure for the front-end(Fig.29) is the standard file structure for a React project, with the main code hosted on \src. For the back-end(Fig.28), the repository is structured in folders based on the function of the scripts. TFG-backend api frontend Catalog.json DataSource.json MainPage.json functions.py main.py atribute-similarity columnProfile.py similarityCategoricalMatrix.py similarityMatrices.py stopwords ca.py scrappers generateCatalog.py scrapperBarcelona.py scrapperHospitalet.py text-similarity similarityMatrices.py stopwords ca.py upload uploadPackets template config.json newData.csv ... update.py upload.py guide.txt Figure 28: File directory for back-end Github repository 43
TFG-frontend public ... src About.js 404.js App.js Catalog.js Contribute.js DataSources.js DatasetPage.js JoinPage.js LogIn.js MainPage.js SignUp.js index.js reportWebVitals.js userContext.js assets ... components Footer.js Main.js MainFeaturedPost.js MultipleSelect.js ResponsiveAppBar.js package-lock.json package.json Figure 29: File directory for front-end Github repository (a) Back-end (b) Front-end Figure 30: Programming languages used in each repository 44
9.2 Instructions for deployment From an overview, the project is divided in two blocks, the back-end and the frontend. Both blocks can be installed separately on different servers or together, and its installation is independent from each other. In this guide it’s assumed that the installation is done locally on the same machine, for sake of simplicity. This project was entirely developed on a 2020 Apple M1 computer, so the commands in this section are for MacOS, which should differ from the commands needed for a Linux computer. 9.2.1 Back-end In order for the front-end to work properly, an installation of the back-end is required first. The back-end is fully written in Python, so the only requirements for it are having installed Python itself (I personally used version 3.9), and the required libraries. Because of the code needs quite a lot of time to do the initial setup and be able to see the results, in the repository there’s attached a working test version already populated with data compressed in a zip file. This version is recommended to use for testing purposes, and only needs to be uncompressed and after that run the api command. Install code from the github repository and access the home folder. All the following commands after installation are assumed to be executed from the home directory. 1> git clone https :// github . com / marcvernet31 /TFG - backend . git 2>cd TFG - backend Execute the scraper scripts to generate and populate the catalog from the datasets available in Barcelona and Hospitalet portals. 1> python3 scrappers / generateCatalog . py Calculate the similarity based on text descriptions for all the dataset pairs in the catalog. 1> python3 text - similarity / similarityMatrices .py Personally, I had many troubles installing the python library scikit-learn on my work computer (Apple M1) and I ended up having to install the library through a Conda environment. In that case, the command used is instead: 1> conda run -n <env-name > python3 text - similarity / similarityMatrices . py The next step is to execute the script to extract the column values for every dataset in the catalog and calculate the profiles. This operation is very slow, because it needs to individually download every dataset in the catalog, check that the format is correct and calculate the profiles for individual columns. The long execution time 45
is not a big issue, because this process should be executed only once to create the profiles. 1> python3 atribute - similarity / columnProfiles .py Now that the column values are extracted, it’s time to calculate the profiles and similarities 1> python3 atribute - similarity / similarityCategoricalMatrix . py Again, if there are issues with the sikit-learn library, it can also be executed with: 1> conda run -n <envname > python3 atribute - similarity / similarityCategoricalMatrix.py Finally, the API can be started. While all the last commands were just to set up all the required files, this command is the one that keeps the API working, and should be kept running for a s long as the website needs to be working. The ideal would be to have a server space dedicated to running the API. 1>cd api 2> uvicorn main : app --reload (explain where the api runs, localhost, ...) There are also the update and upload utility scripts. The upload scripts introduce new data to the database in the form of a packet (specific description on . . . .) and the update script regenerates the front-end files with the current data on the database. 1> python3 upload / upload . py - packet <name > 2> python3 upload / update . py 9.2.2 Front-end The front-end because of it being a React app, it’s fully contained and needs very little configuration. The only requirement is to have installed the Node Package Manager (npm)[27] for Javascript.Assuming that npm is installed, the front-end files can be installed with: 1> git clone https :// github . com / marcvernet31 /TFG - frontend . git 2>cd TFG - frontend 3> npm install And the program can be executed with: 1> npm start By default, the frontend is hosted on the localhost:3000, and it assumes that the back-end is hosted on localhost:8000. The base url for the back-end is hardcoded in many places in the front-end, and it should be changed if the back-end is not running on the same local machine. 46
References [1] Meghan Malas. Glassdoor’s no. 3 best job in the u.s. has seen job growth surge 480%. Fortune, March 2022. [2] Thomas H. Davenport and D.J. Patil. Data scientist: The sexiest job of the 21st century. Harvard Business Review, October 2012. [3] Karl Lofgren and C. William R. Webster. The value of big data in government: The case of ‘smart cities’. Big Data Society, January 2020. [4] T. Berners-Lee C. Bizer, T. Heath. Linked data - the story so far. Int. J. Semantic Web Inf. Syst., July 2009. [5] A european strategy for data. https://digital-strategy.ec.europa.eu/ en/policies/strategy-data. Accessed: 2022-05-10. [6] Center for government excellence at johns hopkins university. https://govex. jhu.edu/. Accessed: 2022-05-10. [7] Open data portal requirements. https://labs.centerforgov.org/ open-data/portal-requirements/. Accessed: 2022-05-10. [8] The official portal for european data. https://data.europa.eu/en. Accessed: 2022-05-10. [9] Designing Data-Intesive Applications. [10] Oscar Romero Javier Flores, Sergi Nadal. Effective and scalable data discovery with nextia. OpenProceedings, 2021. [11] Christos Koutras, George Siachamis, Andra Ionescu, Kyriakos Psarakis, Jerry Brons, Marios Fragkoulis, Christoph Lofi, Angela Bonifati, and Asterios Katsifodimos. Valentine: Evaluating matching techniques for dataset discovery. CoRR, abs/2010.07386, 2020. [12] Oscar Romero Javier Flores, Sergi Nadal. Towards scalable data discovery. OpenProceedings, 2021. [13] Zo´e Marie Meini. Graph convolutional neural networks for open data discovery. UPC, 2021. [14] Catalan stopword repository. http://latel.upf.edu/morgana/altres/pub/ ca_stop.htm. Accessed: 2022-05-10. [15] Bela; Langer Stefan Breitinger, Corinna; Gipp. Research-paper recommender systems: a literature survey. International Journal on Digital Libraries, 2015. [16] scikit-learn. https://scikit-learn.org/stable/. Accessed: 2022-05-10. 47
[17] Ckan. https://ckan.org/. Accessed: 2022-05-10. [18] Socrata. https://dev.socrata.com/. Accessed: 2022-05-10. [19] Guide to creating, using, and maintaining open data portals. https://www.safe.com/blog/2021/04/ guide-creating-using-maintaining-open-data-portals/#creating. Accessed: 2022-05-10. [20] pandas. https://pandas.pydata.org/. Accessed: 2022-05-10. [21] Tinydb. https://tinydb.readthedocs.io/en/latest/. Accessed: 2022-05- 10. [22] Fastapi. https://fastapi.tiangolo.com/. Accessed: 2022-05-10. [23] React.js. https://reactjs.org/. Accessed: 2022-05-10. [24] Router for react. https://reactrouter.com/. Accessed: 2022-05-10. [25] Material ui. https://mui.com/. Accessed: 2022-05-10. [26] React’s useeffect. https://reactjs.org/docs/hooks-effect.html. Accessed: 2022-05-10. [27] Node packet manager. https://www.npmjs.com/. Accessed: 2022-05-10. 48