ontology_parser_NEWTEMP.py 8.0 KB

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