#!/usr/bin/env python2.7

##!/usr/bin/env python3
## seems python3 doesn't have access to nltk?!

# script to read conll format treebanks and
# output some info about word orders

# take a vector of file names to open is prolly easiest
import sys
# prolly use an nltk class for this job
#from nltk.corpus.reader import ConllCorpusReader
import nltk
from nltk.corpus import LazyCorpusLoader
from nltk.corpus.reader import DependencyCorpusReader

import operator
from collections import Counter

# this experiment is going to run over lots of treebanks with 
# different structures
# some hashes will keep 'config' info for the various treebanks
# as I discover it

config = { 'arabic' : { 'files':['all'],
                        'poslabels': { 'v': ['P'] },
                        'clabels': { 's': ['Sb'],
                                     'o': ['Obj'] } },
           'basque' : { 'files':['all'],
                        'poslabels': { 'v': ['ADI', 'ADT', 'ADI_SIN', 'ADT_SIN'] },
                        'clabels': { 's': ['ncsubj'],
                                     'o': ['ncobj'] } },
           'bulgarian': { 'files':['all'],
                          'poslabels': { 'v': ['V','Vii','Vni','Vnp','Vpi','Vpp','Vxi','Vyp'] },
                          'clabels': { 's': [ 'subj'],
                                       'o': [ 'obj' ] } },
           'catalan': { 'files':['all'],
                        'poslabels': { 'v': [ 'va', 'vm', 'vs' ] },
                        'clabels': { 's': [ 'SUJ' ], 'o': [ 'CD' ] } },
           'chinese': { 'files':['all'],
                        'poslabels': { 'v': [ 'VV' ] },
                        'clabels': { 's': ['SUB'], 'o': ['OBJ'] } },
           'czech':   { 'files':['all'],
                        'poslabels': { 'v': [ 'B','e','m','t' ] },
                        'clabels': { 's': [ 'Sb' ], 'o': [ 'Obj' ] } },
           'danish': { 'files':['all'],
                       'poslabels': { 'v': [ 'VA' ] },
                       'clabels': { 's': [ 'subj' ], 'o': [ 'dobj' ] } },
           'dutch':  { 'files':['all'],
                       'poslabels': { 'v': [ 'V' ] },
                       'clabels': { 's': [ 'su' ], 'o': [ 'obj1' ] } },
           'english': { 'files':['all'],
                        'poslabels': { 'v': [ 'VB', 'VBD' ] },
                        'clabels': { 's': ['SBJ'], 'o': ['OBJ'] } },
           'finnish': { 'files':['all'],
                       'poslabels': { 'v': [ 'V' ] },
                       'clabels': { 's': [ 'nsubj' ], 'o': [ 'dobj' ] } },
     'greek-ancient': { 'files':['all'],
                       'poslabels': { 'v': [ 'v' ] },
                       'clabels': { 's': [ 'SBJ' ], 'o': [ 'OBJ' ] } },
           'hebrew':  { 'files':['all'],
                       'poslabels': { 'v': [ 'VB' ] },
                       'clabels': { 's': [ 'SBJ' ], 'o': [ 'OBJ' ] } },
           'hindi':  { 'files':['all'],
                       'poslabels': { 'v': [ 'VM' ] },
                       'clabels': { 's': [ 'k1' ], 'o': [ 'k2' ] } },
           'hungarian':  { 'files':['all'],
                       'poslabels': { 'v': [ 'Vm' ] },
                       'clabels': { 's': [ 'SUBJ' ], 'o': [ 'OBJ' ] } },
           'italian':  { 'files':['all'],
                       'poslabels': { 'v': [ 'VERB' ] },
                       'clabels': { 's': [ 'SUBJ' ], 'o': [ 'OBJ' ] } },
           'latin':  { 'files':['all'],
                       'poslabels': { 'v': [ 'v' ] },
                       'clabels': { 's': [ 'SBJ' ], 'o': [ 'OBJ' ] } },
           'thai':   { 'files':['all'],
                       'root': 'MISC/thai',
                       'poslabels': { 'v': [ 'vi','vt' ] },
                       'clabels': { 's': [ 'subj' ], 'o': [ 'dobj' ] } },
           'portuguese':  { 'files':['all'],
                       'poslabels': { 'v': [ 'v-fin' ] },
                       'clabels': { 's': [ 'SUBJ' ], 'o': [ 'ACC' ] } },
           'romanian':  { 'files':['all'],
                       'poslabels': { 'v': [ 'verb' ] },
                       'clabels': { 's': [ 'subiect' ], 'o': [ 'complement_dir.' ] } },
           'slovene':  { 'files':['all'],
                       'poslabels': { 'v': [ 'Verb-main' ] },
                       'clabels': { 's': [ 'Sb' ], 'o': [ 'Obj' ] } },
           'tamil':  { 'files':['normalized_cpos_and_pos'],
                       'poslabels': { 'v': [ 'Vr' ] },
                       'clabels': { 's': [ 'Sb' ], 'o': [ 'Obj' ] } },
           'turkish': { 'files':['all'],
                        'poslabels': { 'v': ['Verb'] } ,
                        'clabels': { 's':['SUBJECT'], 
                                     'o':['OBJECT'] } },
           'german': { 'files': ['sec1/sec1_conll', 'sec2/sec2_conll', 'sec3/sec3_conll' ],
                       'poslabels': { 'v': ['VVFIN','VVINF','VVIMP','VVIZU','VVPP'] }, # negra treebank uses special verb labels
                       'clabels': { 's':['SUBJ'],
                                    'o':['OBJA'] } },
           'japanese': { 'root': 'MISC/japanese',
                         'files': ['all'],
                         'poslabels': { 'v': [ 'Vfin' ] },
                         'clabels': { 's': ['SBJ'],
                                      'o': ['COMP'] } },
           'swedish': { 'root': 'MISC/swedish',
                         'files': ['all'],
                         'poslabels': { 'v': [ 'FV' ] },
                         'clabels': { 's': ['SS'],
                                      'o': ['OO'] } } }

nltk.data.path.append('/home/jcrowgey')
if sys.argv[1:] == []:
  lns = config.keys()
else: lns=sys.argv[1:]

allverbscounted=0
for lname in lns:
  verbsthislang=0
  lonelyverbs=0
  dbroot = ''
  if 'root' in config[lname]: dbroot = config[lname]['root']
  else: dbroot = lname

  conll2007 = LazyCorpusLoader('data/'+dbroot, DependencyCorpusReader,\
         'all', encoding='utf-8')
  
  ps = []
  for f in config[lname]['files']: 
    ps.extend(conll2007.parsed_sents(f))
  
  
  ## gather some statistics about tags and arclabels
  rels = {}
  tags = {}
  for dg in ps:
    for n in dg.nodelist:
      r = n['rel']
      t = n['tag']
      if t not in tags: tags[t] = 1
      else: tags[t] += 1
      if r not in rels: rels[r] = 1
      else: rels[r] += 1
  
  obs = []
  otherdeprels = {}
  
  for dg in ps:
    for n in dg.nodelist:
      if n['tag'] in config[lname]['poslabels']['v']:
        verbsthislang+=1
        c = {'s':-1,'o':-1,'v':n['address']}
      # get the dependents
        deps = n['deps']
        for i in deps:
          # get the rel
          r = dg.get_by_address(i)['rel']
          if r  in config[lname]['clabels']['s']: 
            c['s'] = i 
          elif r  in config[lname]['clabels']['o']: 
            c['o'] = i
          else:
            if r in otherdeprels: otherdeprels[r]+=1
            else: otherdeprels[r]=1
  
  
        # okay see what we found
        # remove s/o if they still == -1 (not found)
        newc={}
        for k,v in c.iteritems():
          if not v == -1:
            newc[k]=v
        if len(newc) > 1: # we don't care about verbs with no args
          s = "".join([x[0] for x in sorted(newc.iteritems(), key=operator.itemgetter(1))])
          if len(s) == 2:
            obs.append(s)
          else:
            obs.append(s[0]+s[1])
            obs.append(s[0]+s[2])
            obs.append(s[1]+s[2])
        else: lonelyverbs+=1

  
  obscounts = Counter(obs) 
  l= sorted(obscounts.iteritems(), key=operator.itemgetter(1),reverse=True)
  print(lname, 'allverbs:', verbsthislang, 'verbs without any args found:', lonelyverbs)
  print("\n".join([str(i) for i in l]))
  print("----------------------------")
  allverbscounted+=verbsthislang
