JL i8d dZddlZddlZddlZddlZddlZddgddgddZd d gdd gd dZd ggdddZ dggdddZ dgddgddZ dgddgddZ dgdgddZ dgddgddZdgdgddZdgdgddZgdZeeeZeee e e e e eeed Zej+Zdd gZGddZgfdZd.dZd Zd!Zd"Zd#Zd$Zd.d%Z d&Z!d'Z"d/d(Z#d)Z$efd*Z%d+Z&d,Z'e(d-k(re&e'yy)0a Overview ======== Chat-80 was a natural language system which allowed the user to interrogate a Prolog knowledge base in the domain of world geography. It was developed in the early '80s by Warren and Pereira; see ``https://www.aclweb.org/anthology/J82-3002.pdf`` for a description and ``http://www.cis.upenn.edu/~pereira/oldies.html`` for the source files. This module contains functions to extract data from the Chat-80 relation files ('the world database'), and convert then into a format that can be incorporated in the FOL models of ``nltk.sem.evaluate``. The code assumes that the Prolog input files are available in the NLTK corpora directory. The Chat-80 World Database consists of the following files:: world0.pl rivers.pl cities.pl countries.pl contain.pl borders.pl This module uses a slightly modified version of ``world0.pl``, in which a set of Prolog rules have been omitted. The modified file is named ``world1.pl``. Currently, the file ``rivers.pl`` is not read in, since it uses a list rather than a string in the second field. Reading Chat-80 Files ===================== Chat-80 relations are like tables in a relational database. The relation acts as the name of the table; the first argument acts as the 'primary key'; and subsequent arguments are further fields in the table. In general, the name of the table provides a label for a unary predicate whose extension is all the primary keys. For example, relations in ``cities.pl`` are of the following form:: 'city(athens,greece,1368).' Here, ``'athens'`` is the key, and will be mapped to a member of the unary predicate *city*. The fields in the table are mapped to binary predicates. The first argument of the predicate is the primary key, while the second argument is the data in the relevant field. Thus, in the above example, the third field is mapped to the binary predicate *population_of*, whose extension is a set of pairs such as ``'(athens, 1368)'``. An exception to this general framework is required by the relations in the files ``borders.pl`` and ``contains.pl``. These contain facts of the following form:: 'borders(albania,greece).' 'contains0(africa,central_africa).' We do not want to form a unary concept out the element in the first field of these records, and we want the label of the binary relation just to be ``'border'``/``'contain'`` respectively. In order to drive the extraction process, we use 'relation metadata bundles' which are Python dictionaries such as the following:: city = {'label': 'city', 'closures': [], 'schema': ['city', 'country', 'population'], 'filename': 'cities.pl'} According to this, the file ``city['filename']`` contains a list of relational tuples (or more accurately, the corresponding strings in Prolog form) whose predicate symbol is ``city['label']`` and whose relational schema is ``city['schema']``. The notion of a ``closure`` is discussed in the next section. Concepts ======== In order to encapsulate the results of the extraction, a class of ``Concept`` objects is introduced. A ``Concept`` object has a number of attributes, in particular a ``prefLabel`` and ``extension``, which make it easier to inspect the output of the extraction. In addition, the ``extension`` can be further processed: in the case of the ``'border'`` relation, we check that the relation is symmetric, and in the case of the ``'contain'`` relation, we carry out the transitive closure. The closure properties associated with a concept is indicated in the relation metadata, as indicated earlier. The ``extension`` of a ``Concept`` object is then incorporated into a ``Valuation`` object. Persistence =========== The functions ``val_dump`` and ``val_load`` are provided to allow a valuation to be stored in a persistent database and re-loaded, rather than having to be re-computed each time. Individuals and Lexical Items ============================= As well as deriving relations from the Chat-80 data, we also create a set of individual constants, one for each entity in the domain. The individual constants are string-identical to the entities. For example, given a data item such as ``'zloty'``, we add to the valuation a pair ``('zloty', 'zloty')``. In order to parse English sentences that refer to these entities, we also create a lexical item such as the following for each individual constant:: PropN[num=sg, sem=<\P.(P zloty)>] -> 'Zloty' The set of rules is written to the file ``chat_pnames.cfg`` in the current directory. Nborders symmetricregionborderz borders.pl)rel_nameclosuresschemafilename contains0 transitivecontainz contain.plcity)rcountry populationz cities.plr)rrlatitude longitudearearcapitalcurrencyz countries.plcircle_of_latitudedegreesz world1.plcircle_of_longitude continent in_continentoceansea) rcontainsrr circle_of_latcircle_of_longrrrrcReZdZdZggefdZdZdZdZdZ dZ dZ d Z y ) Conceptzc A Concept class, loosely based on SKOS (https://www.w3.org/TR/swbp-skos-core-guide/). c|||_||_||_||_||_t t ||_y)a :param prefLabel: the preferred label for the concept :type prefLabel: str :param arity: the arity of the concept :type arity: int :param altLabels: other (related) labels :type altLabels: list :param closures: closure properties of the extension (list items can be ``symmetric``, ``reflexive``, ``transitive``) :type closures: list :param extension: the extensional value of the concept :type extension: set N) prefLabelarity altLabelsr _extensionsortedlist extension)selfr#r$r%rr)s U/mnt/ssd/data/python-lab/Trading/venv/lib/python3.12/site-packages/nltk/sem/chat80.py__init__zConcept.__init__s7# "  #Y0cddj|j|j|jS)Nz&Label = '{}' Arity = {} Extension = {})formatr#r$r)r*s r+__str__zConcept.__str__s,:@@ NN JJ NN  r-c d|jzS)Nz Concept('%s'))r#r0s r+__repr__zConcept.__repr__!s//r-c|jj|tt|j|_|jS)z Add more data to the ``Concept``'s extension set. :param data: a new semantic value :type data: string or pair of strings :rtype: set )r&addr'r(r))r*datas r+augmentzConcept.augment$s5 D!T__ 56r-c\i}|D]$\}}||vr||j||g||<&|S)z[ Convert a set of pairs into an adjacency linked list encoding of a graph. append)r*sgxys r+ _make_graphzConcept._make_graph1sD  DAqAv! As!   r-c~|D]7}||D]-}||vs||D]}|||vs ||j| /9|S)zY Compute the transitive closure of a graph represented as a linked list. r9)r*r<r=adjacentr>s r+ _transclosezConcept._transclose=sa +AaD +q=x[+AaD=aDKKN+ + +r-cdg}|D]}||D]}|j||f!t|S)zL Convert an adjacency linked list back into a set of pairs. )r:set)r*r<pairsnoderAs r+ _make_pairszConcept._make_pairsJsH /DdG / dH-. / /5zr-cddlm}||jsJd|jvrTg}|jD]\}}|j ||ft |}|jj ||_d|jvr]|j|j}|j|}|j|}|jj ||_tt|j|_ y)z Close a binary relation in the ``Concept``'s extension set. :return: a new extension for the ``Concept`` in which the relation is closed under a given property r)is_relrr N) nltk.semrIr&rr:rDunionr?rBrGr'r(r)) r*rIrEr=r>symallclosedtranss r+closez Concept.closeTs $doo&&& $-- 'E %1 aV$ %e*C"oo33C8DO 4== (""4??3C%%c*F$$V,E"oo33E:DOT__ 56r-N) __name__ __module__ __qualname____doc__rDr,r1r3r7r?rBrGrPr-r+r!r!s: 46ce1.  0   7r-r!c g}d}|d}|dd}t||}|tvr|jt||||D]1} |j | } |jt | ||| |3|S)a Convert a file of Prolog clauses into a list of ``Concept`` objects. :param filename: filename containing the relations :type filename: str :param rel_name: name of the relation :type rel_name: str :param schema: the schema used in a set of relational tuples :type schema: list :param closures: closure properties for the extension of the concept :type closures: list :return: a list of ``Concept`` objects :rtype: list rN) _str2records not_unaryr: unary_conceptindexbinary_concept) r rr rconceptssubjpkeyfieldsrecordsfieldobjs r+clause2conceptsrdlsH D !9D ABZF8X.G y  dD':;Mll5!uhc7KLM Or-cLddl}t||}|j|}|j}|r|j dd} |D])} |j d| z| |st d| z| +|j |rt d|z|jy)a Convert a file of Prolog clauses into a database table. This is not generic, since it doesn't allow arbitrary schemas to be set as a parameter. Intended usage:: cities2table('cities.pl', 'city', 'city.db', verbose=True, setup=True) :param filename: filename containing the relations :type filename: str :param rel_name: name of the relation :type rel_name: str :param dbname: filename of persistent store :type schema: str rNzICREATE TABLE city_table (City text, Country text, Population int) city_tablezinsert into %s values (?,?,?)zinserting values into %s: zCommitting update to %s)sqlite3rXconnectcursorexecuteprintcommitrP) r rdbnameverbosesetuprgra connectioncur table_namets r+ cities2tablerts$8X.G(J    C   5 J @ 3j@!D  .;Q ?@ '&01IIKr-c$ddl} tjj|}|j t |}|j }|j|S#t|jf$rddl }|jd|zwxYw)z Execute an SQL query over a database. :param dbname: filename of persistent store :type schema: str :param query: SQL query :type rel_name: str rNz=Make sure the database file %s is installed and uncompressed.) rgnltkr6findrhstrrirj ValueErrorOperationalErrorwarningswarn)rmqueryrgpathrprqr{s r+ sql_queryrs yy~~f%__SY/ !{{5!! 00 1 Kf T   s AA /BcFg}tjjd|zd}|jD]g}|j |st j |dzd|}t j dd|}|jd}|j|i|S)zO Read a file into memory and convert each relation clause into a list. zcorpora/chat80/%stext)r/z\(z\)\.$,) rvr6load splitlines startswithresubsplitr:)r relrecscontentslinerecords r+rXrXs Dyy~~1H] -> '%s'\n_)r:r capitalizejoin) symbolsrheadertemplater;partspcapspnamerules r+rrs CF JJv:H  (-.1 ..1e*$ 4  J /sA8ct|tr|f}|Dcgc] }t| }}t|}|j Scc}w)a Build a list of concepts corresponding to the relation names in ``items``. :param items: names of the Chat-80 relations to extract :type items: list(str) :return: the ``Concept`` objects which are extracted from the relations :rtype: list(Concept) ) isinstancerx item_metadatarr)itemsrr concept_maps r+r]r]sK%&+ ,M!  ,D , &K     -sAcddl}ddlm}d}||}|jddd|j dd d d d |j ddddd |j dddd|j ddddd |j ddddd !|j d"d#dd$d%!|j d&d'dd(d)!|j \}}|j r|jr|jd*|j rV|jr|j d+z}td,|ztt|j |jdy|j_|jd+z}tj|tj s|jd-|zyt#|j}yt%t} | j'} |j(r:t+d.| D} | D]\} } t| | |jd|j,r| D]}t|t|j.r+t| |j.|jdy|j0r%|jr td/t3| d0yt3| d1}t|y)2Nr) OptionParserz Extract data from the Chat-80 Prolog files and convert them into a Valuation object for use in the NLTK semantics package. ) descriptionTF)rnrvocabz-sz--storeoutdbzstore a valuation in DBDB)desthelpmetavarz-lz--loadindbzload a stored valuation from DBz-cz --concepts store_truez%print concepts instead of a valuation)actionrz-rz --relationrzEprint concept with label REL (check possible labels with '-v' option)RELz-qz--quiet store_falsernzdon't print out progress info)rrrz-xz--lexrzzmain..6sH!5Hs"$zWriting out lexical rulesrr)roptparser set_defaults add_option parse_argsrrerrorrnrkrrrrrrrrrrr'r]rrr)rrroptsoptionsargsrrmrrr]rr$rrs r+mainrs%K K 0DdU;OO ig,Et OO   .  OO  4   OO   T  OO   ,  OO   K  OO   T oo'OWd}} FG}} ??MME)E -5 6w}}%  << #\\E)F99VRWW-/&89$W\\2 ).K"))+H}}HxHH$)(LE5%'( !A!HG}}k'--01 ;;9:"8T: .xd CI)$r-cfttdtddD] }t|y)z: Print out every row from the 'city.db' database. z-Using SQL to extract rows from 'city.db' RDB.zcorpora/city_database/city.dbzSELECT * FROM city_tableN)rkr)rows r+sql_demorMs1 G 9:8:TU c r-__main__)FF)F))rTrrrr nltk.datarvrrrrrrrrrrrtupler'rrrrYr!rdrtrrXrZr\rrrrrrr]rrrQrUr-r+rssj  "  #  /   "%#Y/  &$i0 m   %  i  bUGU  fUm "$     < ( s7s7l:<%P%P0  .# L::(L0F *f%R zF Jr-