import typing import json import model # from . import model import browser # import algorithm def read_truth(file_path: str, browser: typing.Optional[browser.Browser] = None) -> typing.List[model.FacultyEntity]: ''' Reads the truth from a json file. ''' data = dict() with open(file_path, 'r') as file: data = json.load(file) result = [] for f_data in data["faculties"]: faculty = _parse_truth(model.FacultyEntity, f_data, browser) if faculty is not None: result.append(faculty) for i_data in f_data["institutes"]: institute = _parse_truth(model.InsituteEntity, i_data, browser) if institute is not None: faculty.institutes.append(institute) for c_data in i_data["chairs"]: chair = _parse_truth(model.ChairEntity, c_data, browser) if chair is not None: faculty.chairs.append(chair) for c_data in f_data["chairs"]: chair = _parse_truth(model.ChairEntity, c_data, browser) if chair is not None: faculty.chairs.append(chair) faculty.institutes = _deduplicate(faculty.institutes) faculty.chairs = _deduplicate(faculty.chairs) return result def _parse_truth(cls: type, data: dict, browser: typing.Optional[browser.Browser]) -> typing.Optional[model.Entity]: links = [ ] if data['link_en'] != 'None': links.append(data['link_en']) # links.append(data['link_en'] + "/") if 'link_en_2' in data: if data['link_en_2'] != 'None' and data['link_en_2'] not in links: links.append(data['link_en_2']) # links.append(data['link_en_2'] + "/") if 'link_en_3' in data: if data['link_en_3'] != 'None' and data['link_en_3'] not in links: links.append(data['link_en_3']) # links.append(data['link_en_3'] + "/") if data['link_de'] != 'None' and data['link_de'] not in links: links.append(data['link_de']) # links.append(data['link_de'] + "/") if 'link_de_2' in data: if data['link_de_2'] != 'None' and data['link_de_2'] not in links: links.append(data['link_de_2']) # links.append(data['link_de_2'] + "/") if 'link_de_3' in data: if data['link_de_3'] != 'None' and data['link_de_3'] not in links: links.append(data['link_de_3']) # links.append(data['link_de_3'] + "/") if len(links) == 0: return None name = "" if data["name_de"] != '': name = data["name_de"] elif data["name_en"] != '': name = data["name_en"] return cls.create(name=name, targets=_create_targets(links, browser)) def read_prediction(file_path: str, browser: typing.Optional[browser.Browser] = None) -> typing.List[model.FacultyEntity]: ''' Reads a json file with predictions. ''' aggregators = _read_aggregators(file_path) faculties = _create_faculties(aggregators, browser) aggregators_by_url = { aggregator.url: aggregator for aggregator in aggregators } for aggregator in aggregators: if aggregator.concept.type == model.ConceptType.FACULTY: continue faculty = None current = aggregator while True: search = current.parent_link faculty = _find_facultiy(search, faculties) if current.parent == '' or faculty != None: break current = aggregators_by_url[current.parent] if faculty == None: # continue raise Exception("Could not find faculty for " + aggregator.url + " with parent " + aggregator.parent + " and parent link " + aggregator.parent_link) if aggregator.concept.type == model.ConceptType.CHAIR: faculty.chairs.extend(_create_chairs(aggregator.children, browser)) elif aggregator.concept.type == model.ConceptType.INSTITUTE: faculty.institutes.extend(_create_institutes(aggregator.children, browser)) for faculty in faculties: faculty.chairs = _deduplicate(faculty.chairs) faculty.institutes = _deduplicate(faculty.institutes) return faculties def _read_aggregators(file_path: str) -> typing.List[model.AggregatorPage]: ''' Reads a json file with aggregators. ''' lines = [] with open(file_path, "r") as f: lines = f.readlines() aggregators = [] for line in lines: data = json.loads(line) data['text'] = '' aggregator = model.AggregatorPage.model_validate(data) aggregators.append(aggregator) return aggregators def _deduplicate(entities: typing.List[model.Entity]) -> typing.List[model.Entity]: ''' Deduplicates a list of entities. ''' results = [] for entity in entities: duplicate = False for result in results: if entity.equals(result): duplicate = True break if not duplicate: results.append(entity) return results def _find_facultiy(url: str, faculties: typing.List[model.FacultyEntity]) -> typing.Optional[model.FacultyEntity]: ''' Finds a faculty with the specified url. ''' for faculty in faculties: for target in faculty.targets: if target.url == url: return faculty return None def _create_chairs(links: typing.List[model.Link], browser: typing.Optional[browser.Browser]) -> typing.List[model.ChairEntity]: ''' Creates chairs from a list of links. ''' chairs = [] for link in links: chairs.append(model.ChairEntity.create(name=link.text, targets=_create_targets([link.url], browser, link.pagedepth, link.text))) return chairs def _create_institutes(links: typing.List[model.Link], browser: typing.Optional[browser.Browser]) -> typing.List[model.InsituteEntity]: ''' Creates institutes from a list of links. ''' institutes = [] for link in links: institutes.append(model.InsituteEntity.create(name=link.text, targets=_create_targets([link.url], browser, link.pagedepth, link.text))) return institutes def _create_faculties(aggregators: typing.List[model.AggregatorPage], browser: typing.Optional[browser.Browser]) -> typing.List[model.FacultyEntity]: ''' Creates faculties from a list of aggregators. ''' faculty_links = [] for aggregator in aggregators: if aggregator.concept.type == model.ConceptType.FACULTY: aggregator_url = aggregator.url if aggregator_url.endswith("/"): aggregator_url[:-1] for link in aggregator.children: link_url = link.url if link_url.endswith("/"): link_url[:-1] if aggregator_url == link_url: continue if not algorithm.contains_resource(faculty_links, link.url): faculty_links.append(link) faculties = [] for link in faculty_links: faculties.append(model.FacultyEntity.create(name=link.text, targets=_create_targets([link.url], browser, link.pagedepth, link.text))) return faculties def _create_targets(urls: typing.List[str], browser: typing.Optional[browser.Browser], pagedepth: int = 0, link_text: str = '' ) -> typing.List[model.Target]: ''' Creates a target from a list of URLs. ''' contents = [] pagedepths = [] for url in urls: if browser == None: contents.append(url) pagedepths.append(pagedepth) else: page = browser.download(url, pagedepth=pagedepth, link_text=link_text) if page.text != '': contents.append(page.text) pagedepths.append(page.pagedepth) else: contents.append(url) pagedepths.append(page.pagedepth) return [ model.Target.create(url, content, pagedepth_inner) for url, content, pagedepth_inner in zip(urls, contents, pagedepths) ] def print_faculties(faculties: typing.List[model.FacultyEntity]) -> None: ''' Prints a list of faculties. ''' for f in faculties: print (f.name, f.targets[0].url) for i in f.institutes: print(" I ", i.name, i.targets[0].url) for c in f.chairs: print(" C ", c.name, c.targets[0].url) def print_evaluation_flat(truth: typing.List[model.FacultyEntity], prediction: typing.List[model.FacultyEntity]): ''' Evaluates a prediction against the truth. ''' prediction_flat = _flatten(prediction) truth_flat = _flatten(truth) for key in prediction_flat.keys(): print("Evaluating", key) print(" Predictions", len(prediction_flat[key]), "Truth", len(truth_flat[key])) _print_evaluation(truth_flat[key], prediction_flat[key]) def print_evaluation_hierarchy(truth: typing.List[model.FacultyEntity], prediction: typing.List[model.FacultyEntity]): ''' Evaluates a prediction against the truth following the hierarchy. ''' mapping = { } counts = { } for p in range(len(prediction)): counts[p] = 0 for t in range(len(truth)): mapping[t] = [] for p in range(len(prediction)): if truth[t].matches(prediction[p]): counts[p] += 1 mapping[t].append(p) for p, count in counts.items(): if count == 0: raise Exception("Could not find matching faculty for ", prediction[p].name, prediction[p].targets[0].url, "in truth.") if count > 1: raise Exception("Found", count, "matches for faculty", prediction[p].name, prediction[p].targets[0].url, " in truth.") for tx, px in mapping.items(): if len(px) != 1: raise Exception("Found", len(px), "matches for faculty", truth[tx].name, truth[tx].targets[0].url, " in prediction.") t = truth[tx] p = prediction[px[0]] print("Evaluating", t.name, p.name) print(" Institutes") _print_evaluation(t.institutes, p.institutes) print(" Chairs") _print_evaluation(t.chairs, p.chairs) def _print_evaluation(ts: typing.List[model.Entity], ps: typing.List[model.Entity]): ''' Prints the evalution for a list of entities. ''' ps = _reset(ps) ts = _reset(ts) for p in ps: found = False for t in ts: if p.matches(t): found = True t.found = True p.found = not found tp = [x for x in ts if x.found == True] fp = [x for x in ps if x.found == True] fn = [x for x in ts if x.found == False] for f in fp: print(" FP", f.name, f.targets[0].url) # for f in fn: # print(" FN", f.name, f.targets[0].url) score = _score(len(tp), len(fp), len(fn)) print(" TP", len(tp), "FP", len(fp), "FN", len(fn)) print(" P", score[0], "R", score[1], "F1", score[2]) def _score(tp_val: int, fp_val: int, fn_val: int) -> typing.Tuple[float, float, float]: precision = tp_val / (tp_val + fp_val) if (tp_val + fp_val) > 0 else 0 recall = tp_val / (tp_val + fn_val) if (tp_val + fn_val) > 0 else 0 f1_score = 2 * (precision * recall) / (precision + recall) if (precision + recall) > 0 else 0 return precision, recall, f1_score def _reset(entities: typing.List[model.Entity]) -> typing.List[model.Entity]: ''' Resets the found flag of all entities. ''' for entity in entities: entity.found = False return entities def _flatten(faculties: typing.List[model.FacultyEntity]) -> typing.Dict[model.ConceptType, typing.List[model.Entity]]: ''' Flattens a list of faculties. ''' result = { model.ConceptType.FACULTY: [], model.ConceptType.INSTITUTE: [], model.ConceptType.CHAIR: [] } for faculty in faculties: result[model.ConceptType.FACULTY].append(faculty) for institute in faculty.institutes: result[model.ConceptType.INSTITUTE].append(institute) for chair in faculty.chairs: result[model.ConceptType.CHAIR].append(chair) for key in result.keys(): result[key] = _deduplicate(result[key]) return result def filter_urls(faculties: typing.List[model.FacultyEntity], filter: typing.Callable[[str], bool]): ''' Filters the targets of faculties, chairs and institutes by url. ''' for faculty in faculties: for target in [ t for t in faculty.targets]: if filter(target.url): faculty.targets.remove(target) for institute in [t for t in faculty.institutes]: for target in [ t for t in institute.targets]: if filter(target.url): institute.targets.remove(target) if len(institute.targets) == 0: faculty.institutes.remove(institute) for chair in [t for t in faculty.chairs]: for target in [ t for t in chair.targets]: if filter(target.url): chair.targets.remove(target) if len(chair.targets) == 0: faculty.chairs.remove(chair) return faculties