import csv import os import owlready2 as owl import types import urllib from openpyxl import load_workbook BASE_URL = "https://trygvis.io/owl/stm32" SHARED_URL = "{}/shared.owl".format(BASE_URL) def xlsx_to_csv(xlsx_path, csv_path): wb = load_workbook(filename=xlsx_path) ws = wb.active header = [cell.value.strip() for cell in ws[6]] with open(csv_path, "w", newline="") as f: w = csv.writer(f, lineterminator=os.linesep) w.writerow(header) for row in ws.iter_rows(min_row=7): w.writerow([cell.value.strip() for cell in row]) def csv_to_owl(csv_path, owl_path): data = [] with open(csv_path, "r") as f: def fixup(s): return s.replace(u"\u00b5", "u").\ replace(u"\u00b0", "o") for row in csv.reader(f): data.append([fixup(cell) for cell in row]) header = data[0] chips = data[1:] line = owl_path.name[0:-4] url = "{}/{}.owl".format(BASE_URL, urllib.parse.quote(line)) onto = owl.get_ontology(url) shared = onto.get_namespace(SHARED_URL) class Chip(owl.Thing): namespace = shared Chip.label = "Chip" class ChipLine(owl.Thing): namespace = shared ChipLine.label = "ChipLine" class HasChipLine(owl.ObjectProperty): namespace = shared domain = [Chip] range = [ChipLine] python_name = "chip_line" HasChipLine.label = "Has Chip Line" with onto: chip_line = ChipLine(urllib.parse.quote(line)) chip_line.label = line properties = [] for field in header: class_name = field class_name = class_name.lower() class_name = class_name.replace(" ", "-") class_name = class_name.replace("/", "") class_name = class_name.replace("(", "") class_name = class_name.replace(")", "") class_name = urllib.parse.quote(class_name) cls = types.new_class(class_name, (owl.DataProperty,)) cls.label = "Has {}".format(field) cls.domain = [Chip] cls.namespace = onto python_name = class_name python_name = python_name.replace(" ", "_") python_name = python_name.replace("-", "_") cls.python_name = python_name properties.append(cls) for row in chips: chip = Chip(row[0]) chip.label = row[0] chip.chip_line = [chip_line] for idx, value in enumerate(row): prop = properties[idx] chip.__setattr__(prop.python_name, [value]) with open(owl_path, "wb") as f: onto.save(f)