kuehnram / ESTHER-Ontology

Ontology for rhetorical figures in English
MIT License
0 stars 0 forks source link

Crashes if the first or second question answer is an asterisk #1

Open Manamama opened 1 week ago

Manamama commented 1 week ago

E.g.:

python Find_Your_Figure.py Welcome to Find your Figure! Please specify the following characteristics. Which Operation takes place? 0: Addition 1: Omission 2: Repetition 3: Conversion 4: Replacement 5: ? Your choice: 5 Selected: ? Which linguistic element is affected? ? of: 0: Letter 1: Vowel 2: Consonant 3: Word 4: Sentence 5: Phrase 6: Verse 7: Punctuation 8: ? Your choice: 7 Selected: Punctuation

In which area does ? occur: 0: Letter 1: Vowel 2: Consonant 3: Word 4: Sentence 5: Phrase 6: Verse 7: Punctuation 8: ? Your choice: 8 Selected: ?
Linguistic Object: ? of 0: Same form 1: Different form 2: Same meaning 3: Different meaning 4: Opposed meaning 5: ? Your choice: 5 Selected: ?

Position: ? at the 0: Beginning 1: End 2: Middle 3: Beginning and end 4: Whole 5: ? Your choice: 5 Selected: ? ...Searching for figures with ? of a PunctuationElement in ? at the ?... Traceback (most recent call last): File "/data/data/com.termux/files/home/downloads/ESTHER-Ontology/FyF/Find_Your_Figure.py", line 336, in main() File "/data/data/com.termux/files/home/downloads/ESTHER-Ontology/FyF/Find_Your_Figure.py", line 332, in main user_inputter() File "/data/data/com.termux/files/home/downloads/ESTHER-Ontology/FyF/Find_Your_Figure.py", line 146, in user_inputter query_builder(operation, area, linguistic_element, linguistic_object, position) File "/data/data/com.termux/files/home/downloads/ESTHER-Ontology/FyF/Find_Your_Figure.py", line 227, in query_builder execute_query(esther_query) File "/data/data/com.termux/files/home/downloads/ESTHER-Ontology/FyF/Find_Your_Figure.py", line 264, in execute_query result = g.query(esther_query) ^^^^^^^^^^^^^^^^^^^^^ File "/data/data/com.termux/files/usr/lib/python3.11/site-packages/rdflib/graph.py", line 1326, in query return result(processor.query(query_object, initBindings, initNs, **kwargs)) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/data/data/com.termux/files/usr/lib/python3.11/site-packages/rdflib/plugins/sparql/processor.py", line 71, in query parsetree = parseQuery(strOrQuery) ^^^^^^^^^^^^^^^^^^^^^^ File "/data/data/com.termux/files/usr/lib/python3.11/site-packages/rdflib/plugins/sparql/parser.py", line 1544, in parseQuery return Query.parseString(q, parseAll=True) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/data/data/com.termux/files/usr/lib/python3.11/site-packages/pyparsing.py", line 1955, in parseString raise exc File "/data/data/com.termux/files/usr/lib/python3.11/site-packages/pyparsing.py", line 2899, in parseImpl raise ParseException(instring, loc, self.errmsg, self) pyparsing.ParseException: Expected {SelectQuery | ConstructQuery | DescribeQuery | AskQuery}, found '?' (at char 106), (line:5, col:1) ~/.../ESTHER-Ontology/FyF $

Also, all could be coded as a regular database...

Manamama commented 1 week ago

Possible fix:

  1. Convert it all to a database:
    
    import sqlite3
    from rdflib import Graph, RDF, RDFS, OWL, Namespace

Load the OWL file

g = Graph() g.parse('~/Downloads/ESTHER-Ontology/esther.owl', format='xml')

Define the namespaces

ESTHER = Namespace('https://kuehnram.de/esther.owl#')

Connect to the SQLite database (it will be created if it doesn't exist)

conn = sqlite3.connect('esther_ontology.db') cursor = conn.cursor()

Create tables for Rhetorical Figures, Linguistic Elements, Linguistic Objects, and Positions

cursor.execute(''' CREATE TABLE IF NOT EXISTS RhetoricalFigures ( id INTEGER PRIMARY KEY AUTOINCREMENT, uri TEXT, label TEXT ) ''')

cursor.execute(''' CREATE TABLE IF NOT EXISTS LinguisticElements ( id INTEGER PRIMARY KEY AUTOINCREMENT, uri TEXT, label TEXT ) ''')

cursor.execute(''' CREATE TABLE IF NOT EXISTS LinguisticObjects ( id INTEGER PRIMARY KEY AUTOINCREMENT, uri TEXT, label TEXT ) ''')

cursor.execute(''' CREATE TABLE IF NOT EXISTS Positions ( id INTEGER PRIMARY KEY AUTOINCREMENT, uri TEXT, label TEXT ) ''')

Function to insert data into the table

def insert_data(table, uri, label): cursor.execute(f'INSERT INTO {table} (uri, label) VALUES (?, ?)', (uri, label))

Query for Rhetorical Figures

for s, p, o in g.triples((None, RDF.type, ESTHER.RhetoricalFigure)): label = g.label(s) insert_data('RhetoricalFigures', str(s), str(label))

Query for Linguistic Elements

for s, p, o in g.triples((None, RDF.type, ESTHER.LinguisticElement)): label = g.label(s) insert_data('LinguisticElements', str(s), str(label))

Query for Linguistic Objects

for s, p, o in g.triples((None, RDF.type, ESTHER.LinguisticObject)): label = g.label(s) insert_data('LinguisticObjects', str(s), str(label))

Query for Positions

for s, p, o in g.triples((None, RDF.type, ESTHER.LinguisticPosition)): label = g.label(s) insert_data('Positions', str(s), str(label))

Commit the changes and close the connection

conn.commit() conn.close()

2. Use that DB instead for a new SQL only code. 

BTW, is it an error - the German `Ende` bit here?  :

`sqlite3 ~/Downloads/ESTHER-Ontology/FyF/esther_ontology.db ".mode csv" ".output esther_ontology.csv" ".dump" `
:

INSERT INTO Positions VALUES(1,'https://kuehnram.de/esther.owl#Beginning','Beginning'); INSERT INTO Positions VALUES(2,'https://kuehnram.de/esther.owl#BeginningAndEnd','BeginningAndEnd'); INSERT INTO Positions VALUES(3,'https://kuehnram.de/esther.owl#End','**Ende**'); INSERT INTO Positions VALUES(4,'https://kuehnram.de/esther.owl#Middle','Middle'); INSERT INTO Positions VALUES(5,'https://kuehnram.de/esther.owl#Whole','Whole'); INSERT INTO Positions VALUES(6,'https://kuehnram.de/esther.owl#WholeSubsequent','WholeSubsequent'); INSERT INTO Positions VALUES(7,'https://kuehnram.de/esther.owl#WholeSubsequentWithConjunction','WholeSubsequentWithConjunction'); INSERT INTO Positions VALUES(8,'https://kuehnram.de/esther.owl#WholeSuccessiveWithoutConjunction','WholeSuccessiveWithoutConjunction'); INSERT INTO Positions VALUES(9,'https://kuehnram.de/esther.owl#WholeSymmetrical','WholeSymmetrical'); INSERT INTO Positions VALUES(10,'https://kuehnram.de/esther.owl#WholeWithInterruption','WholeWithInterruption'); COMMIT;

Manamama commented 1 week ago

esther.json

Attached is also its conversion to JSON, via below:

from owlready2 import *
import json

# Load the ontology
onto_path.append("~/Downloads/ESTHER-Ontology/")
onto = get_ontology("file://~/Downloads/ESTHER-Ontology/esther.owl").load()

# Convert ontology to dictionary
def ontology_to_dict(onto):
    ontology_dict = {
        "classes": {},
        "properties": {},
        "instances": {}
    }

    # Add classes and their subclasses
    for cls in onto.classes():
        ontology_dict["classes"][cls.name] = [subclass.name for subclass in cls.subclasses()]

    # Add properties and their domains and ranges
    for prop in onto.properties():
        try:
            domain = [domain.name for domain in prop.domain]
        except AttributeError:
            domain = []
        try:
            range_ = [range_.name for range_ in prop.range]
        except AttributeError:
            range_ = []
        ontology_dict["properties"][prop.name] = {
            "domain": domain,
            "range": range_
        }

    # Add instances and their properties
    for instance in onto.individuals():
        instance_dict = {
            "types": [],
            "properties": {}
        }
        for type_ in instance.is_a:
            if isinstance(type_, Restriction):
                instance_dict["types"].append({
                    "onProperty": type_.property.name,
                    "someValuesFrom": type_.value.name if hasattr(type_.value, 'name') else str(type_.value)
                })
            else:
                instance_dict["types"].append(type_.name)

        for prop in instance.get_properties():
            values = getattr(instance, prop.name)
            instance_dict["properties"][prop.name] = [str(value) for value in values]

        ontology_dict["instances"][instance.name] = instance_dict

    return ontology_dict

# Convert to JSON and save
ontology_dict = ontology_to_dict(onto)
with open("~/Downloads/ESTHER-Ontology/esther.json", "w") as f:
    json.dump(ontology_dict, f, indent=4)

print("Ontology saved as JSON successfully!")

The AIs claim they need the following only for each, for classification tasks:

{ "alliteration": { "definition": "Repetition of the same sound of nearby words or within a group of words.", "examples": [ "\"Mail. Message. More\" (Advertisement; with Assonance)", "\"Two terrible tigers.\"" ], "related_figures": ["assonance", "consonance"], "key_properties": { "operates_on": "phonetic level", "is_in_area": ["sentence", "verse"], "is_in_object": ["sentence object", "verse object"], "is_in_position": ["whole"] } } }