U
    eg                     @   s  d Z ddlZddlZddlZddlZddlZddgddgddZd	d
gddgddZdg dddgddZ	dg ddddddddgddZ
dg ddgddZdg ddgddZdg dgddZdg ddgddZdg dgddZdg dgddZddddd d!ddddg
ZeeeZeee	e
eeeeeed"
Ze ZddgZG d#d$ d$Zg fd%d&ZdEd(d)Zd*d+ Zd,d- Zd.d/ Zd0d1 Zd2d3 ZdFd4d5Z d6d7 Z!d8d9 Z"dGd:d;Z#d<d= Z$efd>d?Z%d@dA Z&dBdC Z'e(dDkre&  e'  dS )Ha  
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.

    Nborders	symmetricregionborderz
borders.pl)rel_nameclosuresschemafilenameZ	contains0
transitivecontainz
contain.plcitycountry
populationz	cities.plZlatitudeZ	longitudeZareaZcapitalcurrencyzcountries.plZcircle_of_latitudedegreesz	world1.plZcircle_of_longitude	continentZin_continentoceanseacontainscircle_of_latcircle_of_long)
r   r   r   r   r   r   r   r   r   r   c                   @   sZ   e Zd ZdZg g e fddZdd Zdd Zdd	 Zd
d Z	dd Z
dd Zdd ZdS )Conceptzc
    A Concept class, loosely based on SKOS
    (https://www.w3.org/TR/swbp-skos-core-guide/).
    c                 C   s0   || _ || _|| _|| _|| _tt|| _dS )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)	prefLabelarity	altLabelsr   
_extensionsortedlist	extension)selfr   r   r   r   r    r    P/var/www/html/assets/scripts/venv/lib/python3.8/site-packages/nltk/sem/chat80.py__init__   s    zConcept.__init__c                 C   s   d | j| j| jS )Nz&Label = '{}'
Arity = {}
Extension = {})formatr   r   r   r   r    r    r!   __str__  s
    zConcept.__str__c                 C   s
   d| j  S )NzConcept('%s'))r   r$   r    r    r!   __repr__!  s    zConcept.__repr__c                 C   s"   | j | tt| j | _| j S )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   datar    r    r!   augment$  s    	zConcept.augmentc                 C   s8   i }|D ]*\}}||kr(||  | q|g||< q|S )z[
        Convert a set of pairs into an adjacency linked list encoding of a graph.
        append)r   sgxyr    r    r!   _make_graph1  s    zConcept._make_graphc                 C   sL   |D ]B}|| D ]4}||kr|| D ]}||| kr$||  | q$qq|S )zY
        Compute the transitive closure of a graph represented as a linked list.
        r*   )r   r-   r.   adjacentr/   r    r    r!   _transclose=  s    zConcept._transclosec                 C   s2   g }|D ] }|| D ]}| ||f qqt|S )zL
        Convert an adjacency linked list back into a set of pairs.
        )r+   set)r   r-   pairsnoder1   r    r    r!   _make_pairsJ  s
    zConcept._make_pairsc           	      C   s   ddl m} || jstd| jkr\g }| jD ]\}}|||f q.t|}| j|| _d| jkr| | j}| 	|}| 
|}| j|| _tt| j| _dS )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_relr   r
   N)nltk.semr7   r   AssertionErrorr   r+   r3   unionr0   r2   r6   r   r   r   )	r   r7   r4   r.   r/   symallclosedZtransr    r    r!   closeT  s    



zConcept.closeN)__name__
__module____qualname____doc__r3   r"   r%   r&   r)   r0   r2   r6   r>   r    r    r    r!   r      s   
r   c              	   C   sn   g }d}|d }|dd }t | |}| tkr@|t||| |D ]$}	||	}
|t|	|||
| qD|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
    r      N)_str2records	not_unaryr+   unary_conceptindexbinary_concept)r	   r   r   r   conceptssubjpkeyfieldsrecordsfieldobjr    r    r!   clause2conceptsl  s    

rP   Fc                 C   s   ddl }t| |}||}| }|r2|d d}	|D ]&}
|d|	 |
 |r:td|	 |
 q:|  |rztd|  |  dS )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
    r   NzICREATE TABLE city_table
        (City text, Country text, Population int)Z
city_tablezinsert into %s values (?,?,?)zinserting values into %s: zCommitting update to %s)sqlite3rD   connectcursorexecuteprintcommitr>   )r	   r   dbnameverbosesetuprQ   rM   
connectioncurZ
table_nametr    r    r!   cities2table  s"    

r]   c              	   C   sn   ddl }z.tj| }|t|}| }||W S  t|j	fk
rh   ddl
}|d|    Y nX dS )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
    r   Nz=Make sure the database file %s is installed and uncompressed.)rQ   nltkr(   findrR   strrS   rT   
ValueErrorZOperationalErrorwarningswarn)rW   queryrQ   pathrZ   r[   rb   r    r    r!   	sql_query  s    rf   c                 C   sh   g }t jjd|  dd}| D ]B}||r t|d d|}tdd|}|d}|| q |S )zO
    Read a file into memory and convert each relation clause into a list.
    zcorpora/chat80/%stext)r#   z\( z\)\.$,)	r^   r(   load
splitlines
startswithresubsplitr+   )r	   relZrecscontentslinerecordr    r    r!   rD     s    

rD   c                 C   s,   t | dt d}|D ]}|||  q|S )a  
    Make a unary concept out of the primary key in a record.

    A record is a list of entities in some relation, such as
    ``['france', 'paris']``, where ``'france'`` is acting as the primary
    key.

    :param label: the preferred label for the concept
    :type label: string
    :param subj: position in the record of the subject of the predicate
    :type subj: int
    :param records: a list of records
    :type records: list of lists
    :return: ``Concept`` of arity 1
    :rtype: Concept
    rC   )r   r   )r   r3   r)   )labelrJ   rM   crs   r    r    r!   rF     s    rF   c                 C   sV   | dks| dks| d } t | d|t d}|D ]}||| || f q.|  |S )a$  
    Make a binary concept out of the primary key and another field in a record.

    A record is a list of entities in some relation, such as
    ``['france', 'paris']``, where ``'france'`` is acting as the primary
    key, and ``'paris'`` stands in the ``'capital_of'`` relation to
    ``'france'``.

    More generally, given a record such as ``['a', 'b', 'c']``, where
    label is bound to ``'B'``, and ``obj`` bound to 1, the derived
    binary concept will have label ``'B_of'``, and its extension will
    be a set of pairs such as ``('a', 'b')``.


    :param label: the base part of the preferred label for the concept
    :type label: str
    :param closures: closure properties for the extension of the concept
    :type closures: list
    :param subj: position in the record of the subject of the predicate
    :type subj: int
    :param obj: position in the record of the object of the predicate
    :type obj: int
    :param records: a list of records
    :type records: list of lists
    :return: ``Concept`` of arity 2
    :rtype: Concept
    r   r   Z_of   )r   r   r   )r   r3   r)   r>   )rt   r   rJ   rO   rM   ru   rs   r    r    r!   rH     s    rH   c                 C   s   i }| D ]z}|d }|d }|d }|d }t ||||}|D ]B}|j}	|	|krx|jD ]}
||	 |
 qV||	   q>|||	< q>q|S )aI  
    Given a list of relation metadata bundles, make a corresponding
    dictionary of concepts, indexed by the relation name.

    :param rels: bundle of metadata needed for constructing a concept
    :type rels: list(dict)
    :return: a dictionary of concepts, indexed by the relation name.
    :rtype: dict(str): Concept
    r   r   r   r	   )rP   r   r   r)   r>   )relsrI   rp   r   r   r   r	   Zconcept_listru   rt   r(   r    r    r!   process_bundle   s    

rx   c                 C   sb   g }| D ]}| |j|jf q|r(d}|rZddlm} |i }|| t||d}|S |S dS )aN  
    Convert a list of ``Concept`` objects into a list of (label, extension) pairs;
    optionally create a ``Valuation`` object.

    :param concepts: concepts
    :type concepts: list(Concept)
    :param read: if ``True``, ``(symbol, set)`` pairs are read into a ``Valuation``
    :type read: bool
    :rtype: list or Valuation
    Tr   	ValuationlexiconN)r+   r   r   r8   rz   updatelabel_indivs)rI   readr|   valsru   rz   valr    r    r!   make_valuation=  s    
r   c                 C   s:   t |  }t|dd}t|d}|| |  dS )aX  
    Make a ``Valuation`` from a list of relation metadata bundles and dump to
    persistent database.

    :param rels: bundle of metadata needed for constructing a concept
    :type rels: list of dict
    :param db: name of file to which data is written.
               The suffix '.db' will be automatically appended.
    :type db: str
    Tr   nN)rx   valuesr   shelveopenr}   r>   )rw   dbrI   	valuationZdb_outr    r    r!   val_dumpZ  s
    
r   c                 C   sL   | d }t |t js&td|  n"t| }ddlm} ||}|S dS )z
    Load a ``Valuation`` from a persistent database.

    :param db: name of file from which data is read.
               The suffix '.db' should be omitted from the name.
    :type db: str
    .dbCannot read file: %sr   ry   N)	osaccessR_OKsysexitr   r   r8   rz   )r   rW   Zdb_inrz   r   r    r    r!   val_loadn  s    
r   c              	   C   sN   | j }dd |D }|r@t|}tdd}|| W 5 Q R X | | | S )z
    Assign individual constants to the individuals in the domain of a ``Valuation``.

    Given a valuation with an entry of the form ``{'rel': {'a': True}}``,
    add a new entry ``{'a': 'a'}``.

    :type valuation: Valuation
    :rtype: Valuation
    c                 S   s   g | ]}||fqS r    r    ).0er    r    r!   
<listcomp>  s     z label_indivs.<locals>.<listcomp>zchat_pnames.cfgw)domainmake_lexr   
writelinesr}   )r   r|   r   r4   lexoutfiler    r    r!   r~     s    
r~   c           	      C   s\   g }d}| | d}| D ]<}|d}dd |D }d|}|||f }| | q|S )aO  
    Create lexical CFG rules for each individual symbol.

    Given a valuation with an entry of the form ``{'zloty': 'zloty'}``,
    create a lexical rule for the proper name 'Zloty'.

    :param symbols: a list of individual constants in the semantic representation
    :type symbols: sequence -- set(str)
    :rtype: list(str)
    z
##################################################################
# Lexical rules automatically generated by running 'chat80.py -x'.
##################################################################

z(PropN[num=sg, sem=<\P.(P %s)>] -> '%s'\n_c                 S   s   g | ]}|  qS r    )
capitalize)r   pr    r    r!   r     s     zmake_lex.<locals>.<listcomp>)r+   ro   join)	symbolsr   headertemplater,   partsZcapsZpnameruler    r    r!   r     s    


r   c                 C   s.   t | tr| f} dd | D }t|}| S )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)
    c                 S   s   g | ]}t | qS r    )item_metadata)r   rr    r    r!   r     s     zconcepts.<locals>.<listcomp>)
isinstancer`   rx   r   )itemsrw   concept_mapr    r    r!   rI     s
    	
rI   c                  C   s0  dd l } ddlm} d}||d}|jdddd |jdd	d
ddd |jdddddd |jddddd |jdddddd |jddddd d! |jd"d#dd$d%d! |jd&d'dd(d)d! | \}}|jr|jr|d* |jr|j	r|jd+ }t
d,|  tt|j | d n|jd k	r`|jd+ }t|tjsT| d-|  n
t|j}ntt}	|	 }
|jrtd.d/ |
D }|D ]\}}t
|| q| d |jr|
D ]}t
| t
  q|jrt
|	|j  | d n:|jr|j	r
t
d0 t|
dd1 nt|
dd2}t
| d S )3Nr   )OptionParserz
Extract data from the Chat-80 Prolog files and convert them into a
Valuation object for use in the NLTK semantics package.
    )descriptionTF)rX   r   vocabz-sz--storeoutdbzstore a valuation in DBZDB)desthelpmetavarz-lz--loadindbzload a stored valuation from DBz-cz
--concepts
store_truez%print concepts instead of a valuation)actionr   z-rz
--relationrt   zEprint concept with label REL (check possible labels with '-v' option)ZRELz-qz--quietstore_falserX   zdon't print out progress info)r   r   r   z-xz--lexr   z<write a file of lexical entries for country names, then exitz-vz--vocabr   zEprint out the vocabulary of concept labels and their arity, then exitz1Options --store and --load are mutually exclusiver   zDumping a valuation to %sr   c                 s   s   | ]}|j |jfV  qd S )N)r   r   )r   ru   r    r    r!   	<genexpr>6  s     zmain.<locals>.<genexpr>zWriting out lexical rulesr{   r   )r   optparser   set_defaults
add_option
parse_argsr   r   errorrX   rU   r   rw   r   r   r   r   r   rx   r   r   r   rI   rt   r   r   )r   r   r   optsoptionsargsr   rW   r   r   rI   r   r   rt   ru   r    r    r!   main  s    
    




r   c                  C   s*   t   t d tddD ]} t |  qdS )z:
    Print out every row from the 'city.db' database.
    z-Using SQL to extract rows from 'city.db' RDB.zcorpora/city_database/city.dbzSELECT * FROM city_tableN)rU   rf   )rowr    r    r!   sql_demoM  s    r   __main__)FF)FF)F))rB   r   rm   r   r   Z	nltk.datar^   r   r   r   r   r   r   r   r   r   r   r   tupler   r   r   rw   rE   r   rP   r]   rf   rD   rF   rH   rx   r   r   r   r~   r   rI   r   r   r?   r    r    r    r!   <module>	   s   u
v(
(&
&
#i

