ontology_parser.py 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251
  1. # %%
  2. import csv
  3. import json
  4. # BASIC CONFIGURATION
  5. DATA_FOLDER = './data/'
  6. OUTPUT_FOLDER = './output/'
  7. ONTO_FILENAME = 'man_draft' # No extension!
  8. ent_filename = ONTO_FILENAME + '_entities.csv'
  9. rel_filename = ONTO_FILENAME + '_relations.csv'
  10. # %%
  11. # PART I: parse xlsx to (multiple) csv
  12. # CONFIGURATION
  13. XLSX_FILENAME = ONTO_FILENAME + '.xlsx'
  14. ENTITIES_SHEETNAME = 'Entità'
  15. RELATIONS_SHEETNAME = 'Relazioni'
  16. # %%
  17. # Import xlsx through openpyxl
  18. import openpyxl as op
  19. input_data = op.load_workbook(DATA_FOLDER + XLSX_FILENAME) # Explicitly specify the encoding??
  20. entities_sheet = input_data[ENTITIES_SHEETNAME]
  21. relations_sheet = input_data[RELATIONS_SHEETNAME]
  22. # %%
  23. # Export sheet data to csv
  24. with open(DATA_FOLDER + ent_filename, 'w', encoding='utf-8') as out_file:
  25. writer = csv.writer(out_file)
  26. writer.writerows(entities_sheet.values)
  27. with open(DATA_FOLDER + rel_filename, 'w', encoding='utf-8') as out_file:
  28. writer = csv.writer(out_file)
  29. writer.writerows(relations_sheet.values)
  30. # %%
  31. # PART II: collect csv data into a 'pre-ontology' structure
  32. # Read csv files back in (or use them directly as starting points)
  33. HEADER_ROW = True
  34. # Not difficult to add more keys (column names)
  35. ENTITIES_COLUMN_LABEL = 'ENTITÀ'
  36. ATTRIBUTES_COLUMN_LABEL = 'ATTRIBUTO (LITERAL)'
  37. SAMEAS_COLUMN_LABEL = 'SAME AS'
  38. #
  39. RELATION_FIRST_COLUMN_LABEL = 'ENTITÀ 1'
  40. RELATION_SECOND_COLUMN_LABEL = 'ENTITÀ 2'
  41. RELATION_NAME_COLUMN_LABEL = 'NOME RELAZIONE'
  42. INVERSE_RELATION_COLUMN_LABEL = 'NOME RELAZIONE INVERSA'
  43. #
  44. with open(DATA_FOLDER + ent_filename, 'r', encoding='utf-8') as in_file:
  45. if HEADER_ROW:
  46. reader = csv.DictReader(in_file)
  47. else:
  48. reader = csv.DictReader(in_file, fieldnames=[ENTITIES_COLUMN_LABEL, ATTRIBUTES_COLUMN_LABEL, SAMEAS_COLUMN_LABEL])
  49. entities = [row for row in reader]
  50. with open(DATA_FOLDER + rel_filename, 'r', encoding='utf-8') as in_file:
  51. if HEADER_ROW:
  52. reader = csv.DictReader(in_file)
  53. else:
  54. reader = csv.DictReader(in_file, fieldnames=[RELATION_FIRST_COLUMN_LABEL, RELATION_SECOND_COLUMN_LABEL, RELATION_NAME_COLUMN_LABEL, INVERSE_RELATION_COLUMN_LABEL])
  55. relations = [row for row in reader]
  56. # %%
  57. # From here on, work with the 'entities' and 'relations' lists of dicts. Arrange them in a nested structure, for convenience
  58. def dict_lists_to_json(entities_local, relations_local):
  59. entity = {}
  60. current_entity = None
  61. for row in entities_local:
  62. entity_name = row.get(ENTITIES_COLUMN_LABEL)
  63. attribute_name = row.get(ATTRIBUTES_COLUMN_LABEL)
  64. same_as_row = row.get(SAMEAS_COLUMN_LABEL)
  65. same_as_list = same_as_row.split(',') if same_as_row else []
  66. if entity_name:
  67. current_entity = entity_name
  68. entity[current_entity] = {}
  69. if current_entity and attribute_name:
  70. if not entity[current_entity].get('Attributi'):
  71. entity[current_entity]['Attributi'] = []
  72. entity[current_entity]['Attributi'].append(attribute_name)
  73. if current_entity and same_as_list:
  74. entity[current_entity]['Sinonimi'] = [s.strip() for s in same_as_list]
  75. # Add subclass information
  76. for row in relations_local:
  77. entity1 = row.get(RELATION_FIRST_COLUMN_LABEL)
  78. entity2 = row.get(RELATION_SECOND_COLUMN_LABEL)
  79. label = row.get(RELATION_NAME_COLUMN_LABEL)
  80. if label == "is_subclass_of":
  81. if entity1 in entity:
  82. entity[entity1]["Sottoclasse di"] = entity2
  83. # Construct relations
  84. entity_relations = []
  85. for row in relations_local:
  86. if row[RELATION_NAME_COLUMN_LABEL] != "is_subclass_of":
  87. relation = {
  88. "Entità 1": row[RELATION_FIRST_COLUMN_LABEL],
  89. "Entità 2": row[RELATION_SECOND_COLUMN_LABEL],
  90. "Etichetta": row[RELATION_NAME_COLUMN_LABEL],
  91. "Inversa": row[INVERSE_RELATION_COLUMN_LABEL]
  92. }
  93. entity_relations.append(relation)
  94. # Create final JSON structure
  95. data = {
  96. "Entità": entity,
  97. "Relazioni": entity_relations
  98. }
  99. return data
  100. # %%
  101. json_data = dict_lists_to_json(entities, relations)
  102. # Export data
  103. with open(OUTPUT_FOLDER + ONTO_FILENAME + '.json', 'w') as out_json:
  104. json.dump(json_data, out_json, indent=2, ensure_ascii=False)
  105. # %%
  106. # Re-read the data and do a consistency check
  107. entity_set = set(json_data['Entità'].keys())
  108. entity_relations_set = {ent for rel in json_data['Relazioni'] for ent in [rel['Entità 1'], rel['Entità 2']]}
  109. # The check
  110. if not entity_relations_set.issubset(entity_set):
  111. print(entity_relations_set.difference(entity_set))
  112. # Commento su #any
  113. # %%
  114. # RDF Templates
  115. RDF_MAIN_TEMPLATE = 'template.rdf'
  116. with open(DATA_FOLDER + RDF_MAIN_TEMPLATE, 'r') as in_file:
  117. RAW_RDF = in_file.read()
  118. # RDF snippets; info will replace placeholder tags (in uppercase between '#')
  119. ENTITY_TEMPLATE = '''
  120. <!-- http://www.h2iosc.it/onto##NAME# -->
  121. <owl:Class rdf:about="&h2iosc;#NAME#">
  122. <rdfs:label>#LABEL#</rdfs:label>
  123. <rdfs:subClassOf>#PARENT#</rdfs:subClassOf>
  124. </owl:Class>
  125. '''
  126. SUBCLASS_STRING = " <rdfs:subClassOf>#PARENT#</rdfs:subClassOf>\n"
  127. OBJECT_PROPERTY_TEMPLATE = '''
  128. <!-- http://www.h2iosc.it/onto##NAME# -->
  129. <owl:ObjectProperty rdf:about="&h2iosc;#NAME#">
  130. <rdfs:label>#LABEL#</rdfs:label>
  131. <rdfs:range rdf:resource="&h2iosc;#RANGE#"/>
  132. <rdfs:domain rdf:resource="&h2iosc;#DOMAIN#"/>
  133. </owl:ObjectProperty>
  134. '''
  135. OBJECT_PROPERTY_INVERSE_TEMPLATE = '''
  136. <!-- http://www.h2iosc.it/onto##NAME# -->
  137. <owl:ObjectProperty rdf:about="&h2iosc;#NAME#">
  138. <rdfs:label>#LABEL#</rdfs:label>
  139. <owl:inverseOf rdf:resource="&h2iosc;#INV#"/>
  140. <rdfs:range rdf:resource="&h2iosc;#RANGE#"/>
  141. <rdfs:domain rdf:resource="&h2iosc;#DOMAIN#"/>
  142. </owl:ObjectProperty>
  143. '''
  144. DATATYPE_PROPERTY_TEMPLATE = '''
  145. <!-- http://www.h2iosc.it/onto##NAME# -->
  146. <owl:DatatypeProperty rdf:about="&h2iosc;#NAME#">
  147. <rdfs:label>#LABEL#</rdfs:label>
  148. <rdfs:domain rdf:resource="&h2iosc;#DOMAIN#"/>
  149. </owl:DatatypeProperty>
  150. '''
  151. # Utility
  152. def normalize_label(label):
  153. return label.lower().replace(' ', '_').replace('à', 'a').replace('è', 'e').replace('é', 'e').replace('ì', 'i').replace('ò', 'o').replace('ù', 'u')
  154. # %%
  155. # CREATE RDF OUTPUT
  156. def create_rdf(data):
  157. entities_rdf_list = []
  158. datatype_properties_rdf_list = []
  159. for label, ent in data['Entità'].items():
  160. entity_name = normalize_label(label)
  161. entity_rdf = ENTITY_TEMPLATE.replace('#LABEL#', label).replace('#NAME#', entity_name)
  162. # Subclasses
  163. if 'Sottoclasse di' in ent.keys():
  164. parent = ent['Sottoclasse di']
  165. data['Relazioni'].append({"Entità 1": label,
  166. "Entità 2": parent,
  167. "Etichetta": "is_subclass_of", "Inversa": "is_superclass_of"})
  168. entity_rdf = entity_rdf.replace('#PARENT#', normalize_label(parent))
  169. else:
  170. entity_rdf = entity_rdf.replace(SUBCLASS_STRING, '')
  171. entities_rdf_list.append(entity_rdf)
  172. if not ent.get('Attributi'):
  173. continue
  174. for datatype_label in ent['Attributi']:
  175. datatype_name = normalize_label(datatype_label)
  176. datatype_properties_rdf_list.append(
  177. DATATYPE_PROPERTY_TEMPLATE.replace('#LABEL#', datatype_label).replace(
  178. '#NAME#', datatype_name
  179. ).replace('#DOMAIN#', entity_name)
  180. )
  181. relations_rdf_list = []
  182. for rel in data['Relazioni']:
  183. label = rel['Etichetta']
  184. inverse_label = rel['Inversa']
  185. domain = normalize_label(rel['Entità 1'])
  186. range1 = normalize_label(rel['Entità 2'])
  187. name = domain + '_' + normalize_label(label) + '_' + range1
  188. inverse_name = range1 + '_' + normalize_label(inverse_label) + '_' + domain
  189. #
  190. relation_rdf = OBJECT_PROPERTY_TEMPLATE.replace('#NAME#', name).replace('#LABEL#', label).replace('#DOMAIN#', domain).replace('#RANGE#', range1)
  191. #
  192. relation_inverse_rdf = OBJECT_PROPERTY_INVERSE_TEMPLATE.replace('#NAME#', inverse_name).replace('#LABEL#', inverse_label).replace('#DOMAIN#', range1).replace('#RANGE#', domain).replace('#INV#', name)
  193. #
  194. relation_full_rdf = relation_rdf + '\n\n\n' + relation_inverse_rdf
  195. relations_rdf_list.append(relation_full_rdf)
  196. to_out = RAW_RDF.replace(ENTITY_TEMPLATE, '\n\n\n'.join(entities_rdf_list)).replace(DATATYPE_PROPERTY_TEMPLATE, '\n\n\n'.join(datatype_properties_rdf_list)
  197. ).replace(OBJECT_PROPERTY_INVERSE_TEMPLATE, '\n\n\n'.join(relations_rdf_list))
  198. return to_out
  199. # %%
  200. rdf_data = create_rdf(json_data)
  201. # Export
  202. with open(OUTPUT_FOLDER + ONTO_FILENAME + '.rdf', 'w') as out_file:
  203. out_file.write(rdf_data)
  204. # %%
  205. # https://service.tib.eu/webvowl/
  206. # %%