#python
'''This counts the number of syllables in poetry and plots them against the number of syllables in text. It also returns a mean number of V between pauses.
Input: segmentation'''

import sys
import os
import pylab
import numpy

from gmisclib import fiatio
from gmisclib import wavesurfer_lab as ws

from select_paragraphs import misc
from select_paragraphs import properties

TEXTS = '/proj/aesop/Texts_for_recording'
PROC = '/proj/aesop/proc'

def get_v(f): #number of vocalic segments
    out = 0
    i = 0
    try:
	open(f, 'r')
    except IOError:
	print "%s missing" % (f)
	return 'x'
    (header, data) = ws.read(f)
    while i < len(data):
	(s, e, l) = data[i]
	if l == 'V':
	    if data[i-1][2] == 'V':
		i += 1
	    else:
		out += 1
		i += 1
	else:
	    i += 1
    return out

def count_v(f): #mean number of vocalic segments between S
    out = []
    i = 0
    ss = 0
    try:
	open(f, 'r')
    except IOError:
	print "%s missing" % (f)
	return 'x'
    (header, data) = ws.read(f)
    while i < len(data):
	(s, e, l) = data[i]
	if l == 'V':
	    if data[i-1][2] == 'V':
		i += 1
	    else:
		ss += 1
		i += 1
	elif l == 'S':
	    if ss != 0:
		out.append(ss)
	    ss = 0
	    i += 1
	else:
	    i += 1
    return numpy.average(out)

def get_s(f, lang): #number of vowels in transcription
    n = 0
    for line in open(f, 'r'):
       if len(line)<5:
	   continue
       phl = line.strip('\n').split( )
       vowels = properties.get('vowels_list', lang, phl)
       n += len(vowels)
    return n
   
def read_line(line, segm):
    v = get_v(os.path.join(PROC, 'rhythm_measures', line['d'], line['f'], segm+'.lab'))
    s = get_s(os.path.join(PROC, 'rhythm_measures', line['textfile'].rstrip('.txt')+'.phones'), line['language'])
    xv = count_v(os.path.join(PROC, 'rhythm_measures', line['d'], line['f'], segm+'.lab'))
    return v, s, xv

def read_data(data, segm):
    out = {}
    out2 = {}
    for line in data:
	if line['property'] != 'poetry':
	    continue
	#if line['language'] not in ['English', 'Russian', 'Greek']:
	 #   continue
	if not line['language'] in out.keys():
	    out[line['language']] = []
	if not line['language'] in out2.keys():
	    out2[line['language']] = []    
	(v, s, xv) = read_line(line, segm)
	out[line['language']].append((s)/float(v))
	out2[line['language']].append(xv)
    return (out, out2)
	
def plot_data(data):
    pylab.figure()
    n = 1
    for l in data[0].keys():
	pylab.subplot(len(data), len(data[0].keys()), n)
	pylab.hist(data[0][l])
	pylab.title(l)
	pylab.xlabel('How many syllables in V')
	print 'Syllables/V', l, numpy.mean(data[0][l])
	n += 1
    for l in data[0].keys():
	pylab.subplot(len(data), len(data[0].keys()), n)
	pylab.hist(data[1][l])
	pylab.xlabel('How many V between S')
	print 'V between S', l, numpy.mean(data[1][l])
	n += 1
    pylab.show()


if __name__ == '__main__':
    segm = sys.argv[1]
    (header, data, comments) = fiatio.read(open(os.path.join(PROC, 'rhythm_measures', segm+'.fiat'), 'r'))
    plot_data(read_data(data, segm))  