﻿#!/usr/bin/python
# coding: utf-8
"""Generates text that repeatedly affirms in different ways."""

__author__ = 'nn'
__version__ = '1.0'
__license__ = 'nn'

# Written for the UCSD Software Studies Workshop, 21 May 2008.
# Thanks to Ralph Lombreglia, who discussed the program with me.
# Also, thanks to my students in "The Word Made Digital," MIT,
# Spring 2008 for commenting on and playing with the first voice.

from sys import stdout
from random import choice, randint
from time import sleep, localtime, time

# These two utility functions are used by the "voices" below, which 
# are otherwise independent.

def s():
	return choice([" é","s"])

def finish(string, punct):
    # To avoid lowercasing the rest of the string, don't use
    # capitalize(), just uppercase the first letter.
    return string[0].upper() + string[1:] + punct + " "

# The different voices. Can be used to do the police.

def said_that():
    """Afirmo que disse aquilo."""
    bland = ["contudo","extamente","certamente","precisamente", \
	    "definitivamente","sem dúvida","é claro","absolutamente", \
	    "sem questionamento","de todo jeito"]
    longer = choice( \
        ["isso" + s() + " " + choice(bland) + " o que eu disse", \
        choice(bland) + ", eu disse isso", \
        "eu " + choice(bland) + " disse aquilo"])
    full = choice(["sim","sim, "+longer,longer])
    return finish(full, ".")

def believe():
    """Afirmo que acredito."""
    strong = ["totalmente","inteiramente","completamente","absolutamente", \
	    "completamente","incondicionalmente"]
    longer = choice( \
        ["Eu acredito", \
        "meu " + choice(["coração", "alma"]) + " acredita", \
        "eu " + choice(strong) + " acredito"])
    holy_word = choice( ["ALELUIA", "ALELUIA ALELUIA", \
        "amem"] )
    full = choice(["sim","sim, "+longer,longer,holy_word])
    return finish(full, choice(["!","."]))

def writing():
    """Afirmo que isso é escrita."""
    intensifier = ["contudo ","certamente ","definitivamente ", \
        "sem dúvida ","claro ","sem dúvida mesmo ", \
        "de todo jeito ",""]
    form_of = ["uma forma de ","uma maneira de ","um tipo de ",""]
    writing_etc = ["escrita","trabalho textual","inscrição"]
    longer = choice( \
        ["isto é " + choice(intensifier) + choice(form_of) + \
         choice(writing_etc), ])
    full = choice(["sim","sim, "+longer,longer])
    return finish(full, ".")

def just_yes():
    """Afirmo somente dizendo sim."""
    yes_word = "sim"
    punctuation = choice([" ..."*randint(1,3),".","?"])
    if randint(0,4) == 0:
        yes_word = "s" + "e"*randint(2,6) + "s"
        punctuation = "?"
    return finish(yes_word, punctuation)

def can_do():
    """Afirmo que o falante pode fazer isso."""
    can = ["Eu posso","Eu posso","Eu posso fazê-lo","Eu tenho isso em mim", \
        "Eu posso ter sucesso","Terei sucesso"]
    maxim = ["todo dia de todas as maneiras","nao há tentativa", \
        "trabalhe duro, jogue duro","é ganhar ou ganhar","para os acionistas"]
    full = choice(["sim","sim "+choice(can),choice(can), \
        choice(maxim)])
    return finish(full, ".")

def did_it():
    """Afirma que o falante fez ao invés de quase fazê-lo."""
    did = ["Eu fiz","Eu fiz","Eu consegui","Eu consegui", \
        "Eu sou o cara que conseguiu","fui eu"]
    admit = ["eu admito","eu estou admitindo isso","eu não nego"]
    full = choice(["sim","sim, "+choice(did),choice(did), \
        choice(admit) + " " + choice(did)])
    return finish(full, ".")

def exhilarated():
    """Afirma gritando -- nosso time fez um gol?"""
    exclamation = ["sim","valeu","valeu baby","UUHHUUU","UUUAAAUUU", \
        "yeeessss","yess man","VALEU"]
    full = choice(exclamation)
    sentence = finish(full, "!")
    if randint(0,4) == 0:
        sentence = sentence.upper()
    return sentence

def did_that_one():
    """Afirma que o falante matou alguém."""
    did = ["Eu fiz","Realmente fiz","Eu fiz isso", \
        "Fui eu quem fiz","fui eu"]
    year = choice(["volte ",""]) + "a 198" + str(randint(3,9))
    place = choice(["naquele lugar de descanso","próximo da parada do carro",\
        "quase na saída da cidade"])
    full = choice(["sim","sim, "+choice(did),choice(did), \
        "Eu estou te falando " + choice(did)])
    if randint(0,5) == 0:
        full = full + ", " + choice([year,place])
    return finish(full, ".")
	
def identify():
    """Afirma a identificação de alguém mau."""
    terse = [""," certamente"," definitivamente"]
    longer = choice( \
        ["aquele" + s() + choice(terse) + " ele", \
        "eu" + choice(["tenho certeza que eu"," sim"]) + " reconheco ele", \
        "é ele"])
    positive = "eu tenho " + choice( ["positivo","certeza","certamente"] )
    full = choice(["sim","sim, "+longer,longer,positive])
    return finish(full, ".")

def great_idea():
    """Afirmo que você, chefe, teve uma grande idéia."""
    good_plan = ["Concordo","grande sacada","com certeza","parece maravilhoso", \
        "grande plano"]
    boss = ["chefe","senhor"]
    full = choice(["sim","sim, "+choice(good_plan), \
        choice(good_plan) + ", " + choice(boss)])
    return finish(full, ".")

def time_is():
    """Afirma determinadamente que agora é uma certa hora."""
    h = localtime().tm_hour % 12
    m = localtime().tm_min
    s = localtime().tm_sec
    half = ["manhã","tarde"][localtime().tm_hour > 12]
    hour = str(h)
    minute = str(m)
    if len(minute) < 2:
        minute = "0" + minute
    second = ["exatamente","e quinze segundos","e trinta segundos", \
        "e quarenta e cinco segundos"][s / 15]
    if s % 15 == 0:
        if time() % 1 <= .2 :
            full = "sim, agora " + half + ", é " + \
                hour + ":" + minute + " " + second
            if h == 4 and m == 20 and second == "exatamente":
                full += " -- veja"
        else:
            full = "e"
    else:
        if time() % 1 <= .2 :
            full = "ainda"
        else:
            full = ["e","sim","certeza","hhmmm","sim"][s % 5]
        if int((time() % 1) * 100) % 7 == 0:
            full += ", " + hour + ":" + minute
    return finish(full, ".")

def ecstatic():
    """Afirma estaticamente."""
    many_yeses = ("sim " * randint(1,8))[:-1]
    god = choice(["deus", "oh deus", "oh meu deus"])
    full = choice([god, god + " sim", many_yeses, "sim " + \
        choice(["logo ali","como aquilo"])])
    return finish(full, ".")

def went_out():
    """Afirma que o falante saiu com ele e com ela ..."""
    er = ["verdade é, ","bem, ","ela, ","um, "]
    ers = choice(er) * randint(0,2)
    him_or_her = ["ele","ela"]
    he_or_she = ["ele","ela"]
    also = ["também","também","assim como"]
    dated = ["namorando","saiu","tem algo"]
    dated_with = ["namorando","saiu com","tem algo com"]
    longer = choice(["nós "+choice(dated), \
        choice(he_or_she)+" "+choice(dated_with)+" comigo", \
        "eu "+choice(dated_with)+" "+choice(him_or_her)])
    full = choice(["sim",ers+"sim",ers+"sim, "+longer,ers+"sim, "+ \
        longer+" "+choice(also)])
    return finish(full, ".")

def correct():
    """Afirmo que você teve a melhor resposta."""
    totally = ["é totalmente","é","certeza que sim"]
    longer = choice( \
        ["é isso","isso mesmo","correto","você tá certo", \
        "aquilo " + choice(totally) + " certo"])
    praise = choice( ["muito bom", "excelente", "bom trabalho", \
        "bom trabalho"] )
    full = choice(["sim","sim, "+longer,longer,praise])
    return finish(full, choice(["!","."]))

def thats_it():
    """Afirma que isso é o fim."""
    the_end = ["é isso","beleza","terminou", \
        "finalizou","fim","é tudo"]
    yes = ["sim","yes","sim"]
    full = choice([choice(yes),choice(yes)+", "+choice(the_end), \
        choice(the_end)])
    return finish(full, ".")

# If the program is run from the command line, run the "slides"
# to accompany the 21 May 2008 Software Studies talk.
#
# Otherwise it can be imported and the methods can be called
# individually.

if __name__ == '__main__':

    tick = .2 # Number of seconds (can be fractional) between utterances
    section_length = 100 # Number of utterances per section
    code_tick = .27 # Go through the code a bit more slowly

    opening = ["","Geração sobre a fala","", \
        "My Generation about Talking","","Software Studies Workshop", \
        "UCSD","21 Maio de 2008","","Autor: Nick Montfort",""]
    for line in opening:
        stdout.write("  " + line + "\n")
        sleep(2)

    # The methods that are the different voices are placed in a list.
    # This makes it possible to use the first method, at index 0,
    # and pop off that method when it's time to move to a new voice.
    
    voices = [said_that, believe, writing, just_yes, can_do, \
              did_it, exhilarated, did_that_one, identify, \
              great_idea, time_is, ecstatic, went_out, correct, \
              thats_it]

    # The main loop, which continues as long as there is at least one 
    # voice left in the voices list. After section_length iterations, 
    # iterations % section_length will be so, so two newlines will be 
    # printed and the first voice in the list will be popped off.

    iteration = 0

    while (len(voices) > 0):
        iteration += 1
        text = voices[0]()
        if iteration % section_length == 0:
            text += "\n\n"
            voices.pop(0)
        stdout.write(text)
        # With write() and sleep() it seems necessary to flush the output
        # buffer to ensure that what is in it actually gets written out.
        stdout.flush()
        # sleep() isn't a very accurate way to pause, but works well
        # enough in this program.
        sleep(tick)

    # Print the program itself.
    
    code_lines = open("vozes_sim.py","r").readlines()
    for line in code_lines:
        stdout.write(line)
        sleep(code_tick)
    stdout.write("\n\n")

#####################################################################
#
#  Copyright (c) SWS US
#
#  Permission is hereby granted, free of charge, to any person
#  obtaining a copy of this software and associated documentation
#  files (the "Software"), to deal in the Software without
#  restriction, including without limitation the rights to use,
#  copy, modify, merge, publish, distribute, sublicense, and/or sell
#  copies of the Software, and to permit persons to whom the
#  Software is furnished to do so, subject to the following
#  conditions:
#  
#  The above copyright notice and this permission notice shall be
#  included in all copies or substantial portions of the Software.
#  
#  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
#  EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
#  OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
#  NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
#  HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
#  WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
#  FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
#  OTHER DEALINGS IN THE SOFTWARE.
#
#####################################################################
