Advertisement
MegaLoler

Tatoeba Language Study

Jan 23rd, 2015
253
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 20.13 KB | None | 0 0
  1. #! /usr/bin/python3
  2.  
  3. from subprocess import Popen
  4. import os
  5. import sys
  6. import time
  7. import random
  8. import requests
  9. import urllib.parse
  10. import re
  11. import alsaaudio
  12. import audioop
  13. import speech_recognition as sr
  14. import _thread
  15. import wave
  16. import pickle
  17.  
  18. SAVE_FILE = "study.save"
  19. READ_WPM = 300
  20. STUDY_SESSION_SIZE = 5
  21. tmpAudioFile = "/tmp/textToSpeech.mp3"
  22. tmpMicrophoneRecording = "/tmp/microphoneRecording.wav"
  23.  
  24. VOCAB_STAT_NEW = 0
  25. VOCAB_STAT_GOOD = 1
  26. VOCAB_STAT_GREAT = 2
  27.  
  28. VOCAB_STAT_GOOD_LEVEL = 5
  29. VOCAB_STAT_GREAT_LEVEL = 10
  30.  
  31. class color:
  32.    PURPLE = '\033[95m'
  33.    CYAN = '\033[96m'
  34.    DARKCYAN = '\033[36m'
  35.    BLUE = '\033[94m'
  36.    GREEN = '\033[92m'
  37.    YELLOW = '\033[93m'
  38.    RED = '\033[91m'
  39.    BOLD = '\033[1m'
  40.    UNDERLINE = '\033[4m'
  41.    END = '\033[0m'
  42.  
  43. if len(sys.argv) < 5:
  44.     print("Usage: program [language code] [word list] [target language csv] [native language.csv] [links csv]")
  45.     print("Example: program nl nl.txt nld.csv eng.csv links_nld_eng.csv")
  46.     exit()
  47.  
  48. cards = []
  49. words = []
  50.  
  51. languageCode = sys.argv[1]
  52. wordFile = sys.argv[2]
  53. targetFile = sys.argv[3]
  54. nativeFile = sys.argv[4]
  55. linksFile = sys.argv[5]
  56.  
  57. def clearScreen():
  58.     os.system('clear')
  59.  
  60. class Card:
  61.     def __init__(self, sentence):
  62.         self.sentence = sentence
  63.         self.translations = []
  64.    
  65.     def __str__(self):
  66.         rep = color.BOLD + "[SENTENCE] " + color.END + self.sentence + "\n"
  67.         for translation in self.translations:
  68.             rep += color.BOLD + "[TRANSLATION] " + color.END + translation + "\n"
  69.         return rep.strip()
  70.    
  71.     def say(self):
  72.         textToSpeech(self.sentence, languageCode)
  73.    
  74.     def read(self):
  75.         speedRead(self.sentence)
  76.    
  77.     def getRelated(self):
  78.         for x in range(100): # just so it doesn't look forever
  79.             words = superStrip(self.sentence).split(" ")
  80.             random.shuffle(words)
  81.             while True:
  82.                 deck = searchCardsList(words)
  83.                 if self in deck: deck.remove(self)
  84.                 if len(deck):
  85.                     result = random.choice(deck)
  86.                     return result
  87.                 else:
  88.                     words.pop()
  89.                 if len(words) == 0: break
  90.         print("It took too long to find a related sentence!")
  91.  
  92. class Word:
  93.     def __init__(self, text, freq):
  94.         self.text = text
  95.         self.freq = freq
  96.         if self.text in wordStudySave:
  97.             self.studied = wordStudySave[self.text]
  98.         else:
  99.             self.studied = 0
  100.         self.freqPercent = None
  101.    
  102.     def say(self):
  103.         textToSpeech(self.text, languageCode)
  104.    
  105.     def study(self):
  106.         self.studied += 1
  107.         wordStudySave[self.text] = self.studied
  108.         saveData()
  109.    
  110.     def getVocabLevel(self):
  111.         if self.studied >= VOCAB_STAT_GREAT_LEVEL:
  112.             return VOCAB_STAT_GREAT
  113.         elif self.studied >= VOCAB_STAT_GOOD_LEVEL:
  114.             return VOCAB_STAT_GOOD
  115.         else:
  116.             return VOCAB_STAT_NEW
  117.    
  118.     def getVocabLevelColor(self):
  119.         level = self.getVocabLevel()
  120.         if level == VOCAB_STAT_GREAT:
  121.             return color.GREEN
  122.         elif level == VOCAB_STAT_GOOD:
  123.             return color.YELLOW
  124.         else:
  125.             return color.RED
  126.    
  127.     def __str__(self):
  128.         rep = color.BOLD + "[WORD] " + color.END + self.text + "\n"
  129.         rep += color.BOLD + "[FREQUENCY] " + color.END + self.freq + "/" + wordCountString + " (" + self.freqPercent + "%)\n"
  130.         rep += color.BOLD + "[STUDIED] " + color.END + str(self.studied) + "\n"
  131.         return rep.strip()
  132.    
  133.     def printVocab(self):
  134.         rep = color.BOLD + "[WORD] " + self.getVocabLevelColor() + self.text + color.END + "\n"
  135.         rep += color.BOLD + "[STUDIED] " + color.END + str(self.studied) + "\n"
  136.         print(rep)
  137.  
  138. def load():
  139.     print("Loading sentences...")
  140.     sentences = {}
  141.     with open(targetFile) as f:
  142.         for line in f:
  143.             parts = line.strip().split("\t")
  144.             id = parts[0]
  145.             text = parts[2]
  146.             card = Card(text)
  147.             cards.append(card)
  148.             sentences[id] = card
  149.     print("Loaded " + str(len(sentences)) + " sentences.")
  150.     print("Loading links...")
  151.     reverseLinks = {}
  152.     with open(linksFile) as f:
  153.         for line in f:
  154.             parts = line.strip().split("\t")
  155.             id = parts[0]
  156.             linkId = parts[1]
  157.             reverseLinks[linkId] = id
  158.     print("Loaded " + str(len(reverseLinks)) + " links.")
  159.     print("Loading translations...")
  160.     total = 0
  161.     with open(nativeFile) as f:
  162.         for line in f:
  163.             parts = line.strip().split("\t")
  164.             id = parts[0]
  165.             text = parts[2]
  166.             try:
  167.                 sentenceId = reverseLinks[id]
  168.                 sentences[sentenceId].translations.append(text)
  169.                 total += 1
  170.             except KeyError:
  171.                 pass
  172.     print("Loaded " + str(total) + " translations.")
  173.     print("Loading words...")
  174.     with open(wordFile) as f:
  175.         for line in f:
  176.             parts = line.strip().split(" ")
  177.             word = parts[0]
  178.             freq = parts[1]
  179.             words.append(Word(word, freq))
  180.     print("Loaded " + str(len(words)) + " words.")
  181.     print("Making precalculations...")
  182.     global wordCountString
  183.     wordCountString = str(len(words))
  184.     for word in words:
  185.         word.freqPercent = str(int(1000000.0 * int(word.freq) / len(words)) / 10000)
  186.     input("Press enter when ready.")
  187.  
  188. def inputNumber(prompt=""):
  189.     inp = input(prompt)
  190.     try:
  191.         return int(inp)
  192.     except:
  193.         return None
  194.  
  195. def inputBoolean(prompt, default=None):
  196.     if default == True:
  197.         c = "(Y/n)"
  198.     elif default == False:
  199.         c = "(y/N)"
  200.     else:
  201.         c = "(y/n)"
  202.     inp = None
  203.     while inp != "y" and inp != "n" and (inp != "" or default == None):
  204.         inp = input(prompt + " " + c + " ").strip().lower()
  205.     if inp == "":
  206.         inp = default
  207.     else:
  208.         inp = inp == "y"
  209.     return inp
  210.  
  211. def inputChoice(prompt, choices):
  212.     keys = list(choices.keys())
  213.     sorted(keys)
  214.     inp = None
  215.     while inp == None:
  216.         print(color.BOLD + prompt + color.END)
  217.         i = 0
  218.         for choice in keys:
  219.             i += 1
  220.             print(str(i) + ") " + choice)
  221.         inp = inputNumber("> ")
  222.         if inp == None:
  223.             print("That is not a number!")
  224.         elif inp < 1 or inp > len(keys):
  225.             print("That was not one of the choices!")
  226.             inp = None
  227.     return choices[keys[inp - 1]]
  228.  
  229. MENU_OPTION_NEW = 0
  230. MENU_OPTION_REVIEW = 1
  231. MENU_OPTION_WORD = 2
  232. MENU_OPTION_MORPH = 3
  233. MENU_OPTION_RANDOM = 4
  234. MENU_OPTION_VOCAB = 5
  235. MENU_OPTION_WORDS = 6
  236. MENU_OPTION_SENTENCES = 7
  237. MENU_OPTION_SEARCH = 8
  238. MENU_OPTION_QUIT = 9
  239. MENU_OPTION_TRANSCRIBE = 10
  240. MENU_OPTION_WORD_TRANSCRIBE = 11
  241.  
  242. def inputMenuOption():
  243.     return inputChoice("Select a mode:", {  "New Words":                        MENU_OPTION_NEW,
  244.                                             "Review Words":                     MENU_OPTION_REVIEW,
  245.                                             "Word Practice":                    MENU_OPTION_WORD,
  246.                                             "Sentence Morph":                   MENU_OPTION_MORPH,
  247.                                             "Random Sentences":                 MENU_OPTION_RANDOM,
  248.                                             "Transcribe Sentences":             MENU_OPTION_TRANSCRIBE,
  249.                                             "Transcribe Sentences With Word":   MENU_OPTION_WORD_TRANSCRIBE,
  250.                                             "Vocabulary Stats":                 MENU_OPTION_VOCAB,
  251.                                             "List Words":                       MENU_OPTION_WORDS,
  252.                                             "List Sentences":                   MENU_OPTION_SENTENCES,
  253.                                             "Search Sentences":                 MENU_OPTION_SEARCH,
  254.                                             "Quit":                             MENU_OPTION_QUIT
  255.                                             })
  256.  
  257. def welcome():
  258.     print("Welcome to Chunk Study!")
  259.  
  260. def bye():
  261.     print("Goodbye!")
  262.  
  263. def superStrip(s):
  264.     s = s.lower()
  265.     s = re.sub(r'([^\s\w]|_)+', '', s)
  266.     s = re.sub(' +',' ', s)
  267.     return s
  268.  
  269. def compare(a, b):
  270.     return superStrip(a) == superStrip(b)
  271.  
  272. def compareList(a, items):
  273.     for b in items:
  274.         if compare(a, b): return True
  275.     return False
  276.  
  277. def getRandomCard():
  278.     card = None
  279.     while card == None or len(card.translations) == 0:
  280.         card = random.choice(cards)
  281.     return card
  282.  
  283. def transcribe(card):
  284.     while True:
  285.         card.say()
  286.         inp = input(color.BOLD + "Transcribe:" + color.END + " ")
  287.         if inp: return compare(inp, card.sentence)
  288.  
  289. def read(card):
  290.     while True:
  291.         input("Press enter when ready to read.")
  292.         card.read()
  293.         inp = input(color.BOLD + "Copy:" + color.END + " ")
  294.         if inp: return compare(inp, card.sentence)
  295.  
  296. def speak(card):
  297.     print(color.BOLD + "Say:" + color.END + " " + card.sentence)
  298.     input("Press enter when ready.")
  299.     transcriptions = speechRecognition()
  300.     if transcriptions == None or len(transcriptions) == 0: return False
  301.     for t in transcriptions:
  302.         if compare(t["text"], card.sentence):
  303.             return True
  304.     return transcriptions[0]["text"]
  305.  
  306. def translate(card):
  307.     print(color.BOLD + "Translate:" + color.END + " " + card.sentence)
  308.     if compareList(input("> "), card.translations):
  309.         return True
  310.     else:
  311.         return False
  312.  
  313. def reverseTranslate(card):
  314.     print(color.BOLD + "Translate:" + color.END + " " + card.translations[0])
  315.     if compare(input("> "), card.sentence):
  316.         return True
  317.     else:
  318.         return False
  319.  
  320. def studyCard(card, word=None):
  321.     clearScreen()
  322.     if word: word.say()
  323.     if reverseTranslate(card):
  324.         print(color.GREEN + color.BOLD + "Awesome!" + color.END)
  325.     else:
  326.         print(color.RED + color.BOLD + "Incorrect: " + color.END + card.sentence)
  327.    
  328.     input("Press enter to continue.")
  329.     clearScreen()
  330.     if word: word.say()
  331.     if read(card):
  332.         print(color.GREEN + color.BOLD + "Exactly!" + color.END)
  333.     else:
  334.         print(color.RED + color.BOLD + "Sorry: " + color.END + card.sentence)
  335.    
  336.     input("Press enter to continue.")
  337.     clearScreen()
  338.     if transcribe(card):
  339.         print(color.GREEN + color.BOLD + "Correct!" + color.END)
  340.     else:
  341.         print(color.RED + color.BOLD + "Wrong: " + color.END + card.sentence)
  342.        
  343.     input("Press enter to continue.")
  344.     clearScreen()
  345.     if word: word.say()
  346.     result = speak(card)
  347.     if result == False:
  348.         print(color.RED + color.BOLD + "Couldn't recognize you!" + color.END)
  349.     elif result == True:
  350.         print(color.GREEN + color.BOLD + "Good!" + color.END)
  351.     else:
  352.         print(color.RED + color.BOLD + "Not quite!" + color.END + "  It sounded like you said \"" + result + "\"")
  353.    
  354.     input("Press enter to continue.")
  355.     clearScreen()
  356.     if word: word.say()
  357.     if translate(card):
  358.         print(color.GREEN + color.BOLD + "Nice!" + color.END)
  359.     else:
  360.         print(color.RED + color.BOLD + "Nope: " + color.END + card.translations[0])
  361.    
  362.     print()
  363.     print(card)
  364.     print()
  365.     input("Press enter to continue.")
  366.  
  367. def listSentences():
  368.     for card in cards:
  369.         print(card)
  370.         print()
  371.     print("Total: " + str(len(cards)))
  372.     input("Press enter to return.")
  373.  
  374. def listWords():
  375.     for word in words:
  376.         print(word)
  377.         print()
  378.     print("Total: " + str(len(words)))
  379.     input("Press enter to return.")
  380.    
  381. def searchSentences():
  382.     s = input("Enter a search string: ").strip().lower()
  383.     for card in cards:
  384.         if s in card.sentence.lower():
  385.             print(card)
  386.             print()
  387.     input("Press enter to return.")
  388.  
  389. def searchCards(word):
  390.     deck = []
  391.     for card in cards:
  392.         if len(card.translations) and word.lower() in card.sentence.lower():
  393.             deck.append(card)
  394.     return deck
  395.  
  396. def searchCardsList(words):
  397.     deck = []
  398.     for card in cards:
  399.         if len(card.translations):
  400.             contains = True
  401.             for word in words:
  402.                 if not word.lower() in card.sentence.lower():
  403.                     contains = False
  404.                     break
  405.             if contains: deck.append(card)
  406.     return deck
  407.  
  408. def getWord(s):
  409.     for word in words:
  410.         if s.lower() == word.text.lower():
  411.             return word
  412.    
  413. def vocabStats():
  414.     unknown = 0
  415.     new = 0
  416.     good = 0
  417.     great = 0
  418.     for word in words:
  419.         if word.studied:
  420.             word.printVocab()
  421.         if word.studied == 0:                       unknown += 1
  422.         elif word.studied < VOCAB_STAT_GOOD_LEVEL:  new += 1
  423.         elif word.studied < VOCAB_STAT_GREAT_LEVEL: good += 1
  424.         else:                                       great += 1
  425.     print(color.BOLD + "[UNKNOWN] " + color.END + str(unknown) + color.END)
  426.     print(color.BOLD + color.RED + "[BEGINNER] " + color.END + color.RED + str(new) + color.END)
  427.     print(color.BOLD + color.YELLOW + "[INTERMEDIATE] " + color.END + color.YELLOW + str(good) + color.END)
  428.     print(color.BOLD + color.GREEN + "[ADVANCED] " + color.END + color.GREEN + str(great) + color.END)
  429.     input("Press enter to return.")
  430.  
  431. def transcription():
  432.     while True:
  433.         card = getRandomCard()
  434.         while True:
  435.             clearScreen()
  436.             if transcribe(card):
  437.                 print(color.GREEN + color.BOLD + "Correct!" + color.END)
  438.             else:
  439.                 print(color.RED + color.BOLD + "Wrong: " + color.END + card.sentence)
  440.             print()
  441.             print(card)
  442.             print()
  443.             choice = inputChoice("What would you like to do next?", {
  444.                                     "Repeat Sentence":  0,
  445.                                     "Next Sentence":    1,
  446.                                     "Quit":             2
  447.                                     })
  448.             if choice != 0: break
  449.         if choice != 1: break
  450.  
  451. def transcribeWordPractice():
  452.     while True:
  453.         clearScreen()
  454.         while True:
  455.             while True:
  456.                 w = input("Enter a word to study: ")
  457.                 word = getWord(w)
  458.                 if word == None:
  459.                     print("That is an unknown word!")
  460.                 else:
  461.                     print()
  462.                     word.printVocab()
  463.                     break
  464.             deck = searchCards(word.text)
  465.             random.shuffle(deck)
  466.             if len(deck):
  467.                 print(str(len(deck)) + " sentences found containing that word.")
  468.                 if inputBoolean("Is this okay?", True): break
  469.             else:
  470.                 print("No sentences found containing that word!")
  471.         if len(deck):
  472.             while True:
  473.                 for card in deck:
  474.                     while True:
  475.                         clearScreen()
  476.                         if transcribe(card):
  477.                             print(color.GREEN + color.BOLD + "Correct!" + color.END)
  478.                         else:
  479.                             print(color.RED + color.BOLD + "Wrong: " + color.END + card.sentence)
  480.                         print()
  481.                         print(card)
  482.                         word.study()
  483.                         print()
  484.                         word.printVocab()
  485.                         word.say()
  486.                         choice = inputChoice("What would you like to do next?", {
  487.                                                 "Repeat Sentence":  0,
  488.                                                 "Next Sentence":    1,
  489.                                                 "Change Word":      2,
  490.                                                 "Quit":             3
  491.                                                 })
  492.                         if choice != 0: break
  493.                     if choice != 1: break
  494.                 if choice != 1: break
  495.                 if not inputBoolean("That is all of the sentences for this word. Would you like to repeat them?", False): break
  496.         else:
  497.             print("There are no sentences containing that word.")
  498.         if choice == 3:
  499.             break
  500.         elif choice != 2:
  501.             if not inputBoolean("Would you like to study a different word?", True): break
  502.  
  503. def studySession(words):
  504.     print("Words for this study session:")
  505.     print()
  506.     for word in words:
  507.         word.printVocab()
  508.     input("Press enter to continue.")
  509.     for word in words:
  510.         clearScreen()
  511.         print("Now studying:")
  512.         print()
  513.         word.printVocab()
  514.         word.say()
  515.         input("Press enter to continue.")
  516.         deck = searchCards(word.text)
  517.         if word.studied < VOCAB_STAT_GOOD_LEVEL:
  518.             goal = VOCAB_STAT_GOOD_LEVEL
  519.         elif word.studied < VOCAB_STAT_GREAT_LEVEL:
  520.             goal = VOCAB_STAT_GREAT_LEVEL
  521.         else:
  522.             goal = word.studied + 1
  523.         while word.studied < goal:
  524.             card = random.choice(deck)
  525.             while True:
  526.                 studyCard(card, word)
  527.                 word.study()
  528.                 print()
  529.                 word.printVocab()
  530.                 choice = inputChoice("What would you like to do next?", {
  531.                                         "Repeat Sentence":  0,
  532.                                         "Next Sentence":    1,
  533.                                         "Quit":             2
  534.                                         })
  535.                 if choice != 0: break
  536.             if choice != 1: break
  537.         if choice != 1: break
  538.  
  539. def newWords():
  540.     clearScreen()
  541.     studyWords = []
  542.     for word in words:
  543.         if word.studied == 0:
  544.             studyWords.append(word)
  545.         if len(studyWords) >= STUDY_SESSION_SIZE: break
  546.     if len(studyWords) == 0:
  547.         print("There are no more new words to study!")
  548.         print("Review them instead.")
  549.         input("Press enter to return.")
  550.     else:
  551.         studySession(studyWords)
  552.  
  553. def reviewWords():
  554.     introducedWords = []
  555.     for word in words:
  556.         if word.studied > 0:
  557.             introducedWords.append(word)
  558.     worstWords = sorted(introducedWords, key=lambda word: word.studied, reverse=False)[0:STUDY_SESSION_SIZE]
  559.     if len(worstWords) == 0:
  560.         print("There are no words to study!")
  561.         print("Learn new words instead.")
  562.         input("Press enter to return.")
  563.     else:
  564.         studySession(worstWords)
  565.  
  566. def wordPractice():
  567.     while True:
  568.         clearScreen()
  569.         while True:
  570.             while True:
  571.                 w = input("Enter a word to study: ")
  572.                 word = getWord(w)
  573.                 if word == None:
  574.                     print("That is an unknown word!")
  575.                 else:
  576.                     print()
  577.                     word.printVocab()
  578.                     break
  579.             deck = searchCards(word.text)
  580.             random.shuffle(deck)
  581.             if len(deck):
  582.                 print(str(len(deck)) + " sentences found containing that word.")
  583.                 if inputBoolean("Is this okay?", True): break
  584.             else:
  585.                 print("No sentences found containing that word!")
  586.         if len(deck):
  587.             while True:
  588.                 for card in deck:
  589.                     while True:
  590.                         studyCard(card, word)
  591.                         word.study()
  592.                         print()
  593.                         word.printVocab()
  594.                         choice = inputChoice("What would you like to do next?", {
  595.                                                 "Repeat Sentence":  0,
  596.                                                 "Next Sentence":    1,
  597.                                                 "Change Word":      2,
  598.                                                 "Quit":             3
  599.                                                 })
  600.                         if choice != 0: break
  601.                     if choice != 1: break
  602.                 if choice != 1: break
  603.                 if not inputBoolean("That is all of the sentences for this word. Would you like to repeat them?", False): break
  604.         else:
  605.             print("There are no sentences containing that word.")
  606.         if choice == 3:
  607.             break
  608.         elif choice != 2:
  609.             if not inputBoolean("Would you like to study a different word?", True): break
  610.  
  611. def sentenceMorph():
  612.     card = getRandomCard()
  613.     while True:
  614.         while True:
  615.             studyCard(card)
  616.             choice = inputChoice("What would you like to do next?", {
  617.                                     "Repeat Sentence":  0,
  618.                                     "Next Sentence":    1,
  619.                                     "Quit":             2
  620.                                     })
  621.             if choice != 0: break
  622.         if choice != 1: break
  623.         card = card.getRelated()
  624.  
  625. def randomSentence():
  626.     while True:
  627.         card = getRandomCard()
  628.         while True:
  629.             studyCard(card)
  630.             choice = inputChoice("What would you like to do next?", {
  631.                                     "Repeat Sentence":  0,
  632.                                     "Next Sentence":    1,
  633.                                     "Quit":             2
  634.                                     })
  635.             if choice != 0: break
  636.         if choice != 1: break
  637.  
  638. def main():
  639.     clearScreen()
  640.     welcome()
  641.     while True:
  642.         choice = inputMenuOption()
  643.         if choice == MENU_OPTION_NEW:
  644.             newWords()
  645.         elif choice == MENU_OPTION_REVIEW:
  646.             reviewWords()
  647.         elif choice == MENU_OPTION_WORD:
  648.             wordPractice()
  649.         elif choice == MENU_OPTION_WORD_TRANSCRIBE:
  650.             transcribeWordPractice()
  651.         elif choice == MENU_OPTION_MORPH:
  652.             sentenceMorph()
  653.         elif choice == MENU_OPTION_RANDOM:
  654.             randomSentence()
  655.         elif choice == MENU_OPTION_TRANSCRIBE:
  656.             transcription()
  657.         elif choice == MENU_OPTION_VOCAB:
  658.             vocabStats()
  659.         elif choice == MENU_OPTION_WORDS:
  660.             listWords()
  661.         elif choice == MENU_OPTION_SENTENCES:
  662.             listSentences()
  663.         elif choice == MENU_OPTION_SEARCH:
  664.             searchSentences()
  665.         elif choice == MENU_OPTION_QUIT:
  666.             break
  667.         else:
  668.             break
  669.         clearScreen()
  670.     bye()
  671.  
  672. def setup():
  673.     global microphone
  674.     global audioInput
  675.    
  676.     clearScreen()
  677.    
  678.     cards = alsaaudio.cards()
  679.     choices = {}
  680.     for card in cards:
  681.         choices[card] = card
  682.     microphone = inputChoice("Select a microphone source:", choices)
  683.    
  684.     audioInput = alsaaudio.PCM(alsaaudio.PCM_CAPTURE, alsaaudio.PCM_NONBLOCK, microphone)
  685.     audioInput.setchannels(1)
  686.     audioInput.setrate(44100)
  687.     audioInput.setformat(alsaaudio.PCM_FORMAT_S16_LE)
  688.     audioInput.setperiodsize(160)
  689.  
  690. def getFile(url):
  691.     return requests.Session().get(url).content
  692.  
  693. audioProcess = None
  694.  
  695. def playAudioFile(path):
  696.     global audioProcess
  697.     fnull = open(os.devnull, "w+")
  698.     if audioProcess != None: audioProcess.terminate()
  699.     audioProcess = Popen(["cvlc", path, "vlc://quit"], stdin=fnull, stdout=fnull, stderr=fnull)
  700.  
  701. def exportFile(path, data):
  702.     f = open(path, "wb")
  703.     f.write(data)
  704.     f.close()
  705.  
  706. def exportWav(path, data):
  707.     f = wave.open(path, "w")
  708.     f.setparams((1, 2, 44100, 0, 'NONE', 'not compressed'))
  709.     f.writeframes(data)
  710.     f.close()
  711.  
  712. def textToSpeech(text, language="en"):
  713.     data = getFile("http://translate.google.com/translate_tts?tl=" + language + "&q=" + text.replace(" ", "%20"))
  714.     exportFile(tmpAudioFile, data)
  715.     playAudioFile(tmpAudioFile)
  716.  
  717. def getMicrophoneData():
  718.     global micData
  719.     micData = b""
  720.     audioInput.read()
  721.     while recording:
  722.         length, data = audioInput.read()
  723.         micData += data
  724.         time.sleep(0.001)
  725.  
  726. def recordAudio():
  727.     global recording
  728.     recording = True
  729.     _thread.start_new_thread(getMicrophoneData,())
  730.     input(color.BOLD + color.RED + "[RECORDING] " + color.END + "Press enter to stop...")
  731.     print(color.BOLD + "Finished recording." + color.END)
  732.     recording = False
  733.     exportWav(tmpMicrophoneRecording, micData)
  734.     return tmpMicrophoneRecording
  735.  
  736. def speechRecognition():
  737.     rec = sr.Recognizer(language=languageCode)
  738.     audio = recordAudio()
  739.     playAudioFile(audio)
  740.     with sr.WavFile(audio) as source:
  741.         print("Analyzing audio...")
  742.         audio = rec.listen(source)
  743.     try:
  744.         return rec.recognize(audio, True)
  745.     except LookupError:
  746.         return None
  747.  
  748. def speedRead(string, wpm=READ_WPM):
  749.     string = re.sub(' +',' ', string)
  750.     words = string.split(" ")
  751.     clearScreen()
  752.     for word in words:
  753.         print(word)
  754.         time.sleep(1 / (wpm / 60.0))
  755.         clearScreen()
  756.  
  757. def saveData():
  758.     f = open(SAVE_FILE, "wb")
  759.     pickle.dump(wordStudySave, f)
  760.     f.close()
  761.    
  762. def loadData():
  763.     global wordStudySave
  764.     try:
  765.         f = open(SAVE_FILE, "rb")
  766.         wordStudySave = pickle.load(f)
  767.         f.close()
  768.     except FileNotFoundError:
  769.         wordStudySave = {}
  770.         print("Save file not found.")
  771.  
  772. loadData()
  773. setup()
  774. load()
  775. main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement