Пример #1
0
def tutorial():
    replit.clear()
    typr.typr("Welcome to the tutorial!")
    time.sleep(0.5)
    typr.typr(
        "When you are asked to make a choice in the game, please respond with '1', '2', or '3' (if applicable)."
    )
    time.sleep(0.5)
    typr.typr("Let's try it out!")
    inf.parse("Option 1 (type 1)", "Option 2 (type 2)")
    typr.typr("Good job! Last one, and then you will be ready.")
    inf.parse3("Option 1 (type 1)", "Option 2 (type 2)", "Option 3 (type 3)")
    typr.typr("You are ready now! Let's begin.")
    time.sleep(1)
    replit.clear()
Пример #2
0
    def verify_result_file(self, episode, result, outfile):
        """
        Ensure the given video file matches the user-requested criteria with
        respect to resolution, codec, etc.

        :returns: False if the file could not be parsed, or True if result is verified.
        :raises: RetrieverError if the video file was valid did not pass
                 verification, which will cause the transfer to abort
        """
        if not metadata:
            log.warning('kaa.metadata module not available; skipping file verification')
            return
        info = metadata.parse(outfile)
        if not info:
            if os.path.getsize(outfile) > 1024*1024*10:
                # We have 10MB of the file and still can't parse it.  Consider
                # it corrupt or unknown.
                raise RetrieverError('could not identify file after 10MB')
            return False
        if info.media != 'MEDIA_AV':
            raise RetrieverError('file is not a video file (is %s)' % info.media)
        elif not info.video:
            raise RetrieverError('file has no video tracks')

        # Find the video track with the highest (y) resolution.
        # TODO: don't hardcode these
        video = sorted(info.video, key=lambda track: track.height)[-1]
        if (result.quality == 'SD' and (video.height < 240 or video.height > 540)) or \
           (result.quality == 'HD' and video.height < 600):
            raise RetrieverError('video resolution %dx%d does not satisfy requested %s quality' % \
                                 (video.width, video.height, result.quality))

        # See if the audio is the right language.  If the language is specified in any of
        # the tracks, make sure one of them is the user-preferred language.
        langs = set(track.langcode or 'und' for track in info.audio)
        if langs == set(['und']):
            # No languages specified in any track. Disqualify if 'dubbed' appears in
            # the result filename.
            if re.search(r'\bdubbed\b', result.filename, re.I):
                raise RetrieverError('filename indicates dubbed audio but no language codes specified')
        else:
            lang2to3 = dict((c[1], c[0]) for c in metadata.language.codes if len(c) == 3)
            lang = episode.series.cfg.language or config.misc.language
            threecode = lang2to3.get(lang) if len(lang) == 2 else lang
            log.info('looking for preferred audio track language %s (%s)', threecode, lang)
            if (not threecode or threecode not in langs) and lang not in langs:
                # There are audio tracks with defined languages, but none of
                # them are the language we want.  Heuristic (based on real
                # world content): if the desired language is English and one
                # of the tracks is undefined, assume it's English.
                if threecode == 'eng' and 'und' in langs:
                    log.warning("no English track found, but assuming 'und' track is English")
                else:
                    raise RetrieverError('no %s audio track in file' % threecode)

        # TODO: verify codecs too
        log.debug('%s looks good (%dx%d %s, audio languages: %s)', result.filename, video.width, video.height, video.codec,
                  ', '.join(langs))

        return True
Пример #3
0
def lightAllCandles():
	typr.typr("You light two candles, and suddenly... Two doors open up.")
	time.sleep(0.5)
	choice = inf.parse("Enter Door 1", "Enter Door 2")
	if(choice in inf.ones):
		enterDoor1Choice()
	else:
		enterDoor2()
Пример #4
0
def blowOutCandles():
	typr.typr("Well that didn't help anyone. Now you're in the dark, and alone... well, except for that screeching noise...")
	time.sleep(0.5)
	choice = inf.parse("Investigate", "Run the other way.")
	if(choice in inf.ones):
		investigateNoiseB()
	else:
		runBackLeft()
Пример #5
0
def goToCandles():
	typr.typr("You walk towards the candles and find 23 of them, and a few matches. Only 18 candles are lit up...")
	time.sleep(0.5)
	choice = inf.parse("Light the rest of the candles.", "Blow out all of the candles")
	if(choice in inf.ones):
		lightAllCandles()
	else:
		blowOutCandles()
Пример #6
0
def climbLadderB():
	typr.typr("You start to climb the ladder, but when you get about halfway up, the rungs start to fall off. Don't jump off, or the walls will get you...")
	time.sleep(0.5)
	choice = inf.parse("Trust your instincts and climb faster.", "Jump off and accept defeat.")
	if(choice in inf.ones):
		climbFaster()
	else:
		inf.endGame("The walls cave in on you until silence is all that remains. Oblivion has won. The end?")
Пример #7
0
def right2():
	typr.typr("You go right to find a dead end and an array of switches, but there are no lightbulbs, only candles lit up in the corner.")
	time.sleep(0.5)
	choice = inf.parse("Flip the switches.", "Go find the candles.")
	if(choice in inf.ones):
		flipSwitches()
	else:
		goToCandles()
Пример #8
0
def runBackLeft():
	typr.typr("You sprint in the other direction but trip over something. A trap? The walls begin to cave in...")
	time.sleep(0.5)
	choice = inf.parse("Go back and climb the odd ladder you saw.", "Hit the suspicious red button you see next to you.")
	if(choice in inf.ones):
		climbLadderB()
	else:
		pressRedButton()
Пример #9
0
def flipSwitches():
		typr.typr("You flip two switches, and a door opens up behind you. You flip the other two, and another one opens in front of you! Either one could get you out, or to Oblivion...")
		time.sleep(0.5)
		choice = inf.parse("Enter Door 1", "Enter Door 2")
		if(choice in inf.ones):
			enterDoor1Choice()
		else:
			enterDoor2()
Пример #10
0
def investigateNoise():
	typr.typr("You look around, and find an almost completely camouflaged ladder. You start to climb it, but when you get about halfway up the ladder, the rungs begin to fall down...")
	time.sleep(0.5)
	choice = inf.parse("Jump off while you still can.", "Trust your instincts and climb faster.")
	if(choice in inf.ones):
		inf.endGameTwoLn("You jump off the ladder, landing on... the floor? You hit nothing but keep falling, as if the floor had slid down.", "When you finally hit the ground, impact damage leaves you immobilized. Oblivion has won. The end?")
		return
	else:
		climbFaster()
Пример #11
0
def pressRedButton():
	typr.typr("The floor disappears below you, and you start to fall. At least the walls won't hurt you...")
	time.sleep(1)
	typr.typr("You think it's been about 2 hours since you started falling, when, to your surprise, you start floating upwards. It's as if... you can fly!")
	time.sleep(0.5)
	choice = inf.parse("Attempt to fly back up", "Float to the bottom of the hole.")
	if(choice in inf.ones):
		typr.typr("The walls closed in on you, remember? You float to the bottom of the hole.")
		floatPit()
	else:
		floatPit()
Пример #12
0
def enterDoor1Choice():
	global hasKey
	if(hasKey == False):
		typr.typr("You found a key!")
		time.sleep(0.5)
		typr.typr("You pick it up. You look around, nothing else here.")
		hasKey = True
	else:
		typr.typr("We've been here already.")
	choice = inf.parse("Turn back.", "Jump for joy immaturely.")
	if(choice in inf.ones):
		exitDoor1()
	else:
		inf.endGameTwoLn("You (for some reason) decide to jump for joy, but realize too late that the floor is very unstable.", "Oblivion has won (by accident this time). The end?")
Пример #13
0
def win():
	typr.typr("A water landing? Lucky you can swim well.")
	time.sleep(0.5)
	typr.typr("Your pocket begins to glow. You look inside and realize... it's the key! It looks like it's pointing in a certain direction.")
	time.sleep(0.5)
	replit.clear()
	typr.typr("Suddenly, the key stops glowing. There are two doors up ahead. The right choice would get you home safe, the other would do the opposite.")
	time.sleep(0.5)
	typr.typr("Choose wisely...")
	choice = inf.parse("The left door.", "The right door.")
	if(choice == good_door):
		replit.clear()
		win_end()
	else:
		inf.endGameTwoLn("Sometimes, life is a game of chance", "The odds were not in your favor, my friend. Oblivion has won.")
Пример #14
0
 def __init__(self, filepath):
     self._filepath = filepath
     self._size = os.path.getsize(filepath)
     self._hash = self.calculateOSDBHash()
     try:
         video = metadata.parse(filepath)
         self._fps = video.video[0].fps
         if not self._fps:
             self._fps = 0
         self._timeMS = video.length * 1000
     except Exception, e:
         print filepath
         traceback.print_exc(e)
         self._fps = 0
         self._timeMS = 0
Пример #15
0
def climbFaster():
	typr.typr('You reach the top of the ladder, barely. You see a lit up staircase to your left...')
	time.sleep(0.5)
	choice = inf.parse("Climb the staircase.", "Jump back down.")
	if(choice in inf.ones): climbStairs()
	else: jumpDownLadderChoice()
Пример #16
0
def jumpDownLadderChoice():
	typr.typr("If you jump, you wouldn't be able to make it.")
	choice = inf.parse("Jump (I don't know why you would do this).", "Climb the staircase. (The logical choice).")
	if(choice in inf.ones):
		inf.endGameTwoLn("I was right, wasn't I?", "You are left immobilzed due to the impact damage. Oblivion has won. The end?")
	else: climbStairs()
Пример #17
0
def climbStairs():
	typr.typr("You sprint up the staircase, lose your balance, and almost fall over when you reach the end. A bottomless pit... Well, almost. You see a small light shining at the very bottom of the pit... Your way out? Possibly...")
	choice = inf.parse("Jump in!", "Turn back.")
	if(choice in inf.ones): jumpPit()
	else: turnBack()
Пример #18
0
def parse_cmudict(filename, checks, order_from, encoding):
    """
		Parse the entries in the cmudict file.

		The return value is of the form:
			(line, format, word, context, phonemes, comment, error)
	"""
    re_linecomment_weide = re.compile(r'^##(.*)$')
    re_linecomment_air = re.compile(r'^;;;(.*)$')
    re_entry = re.compile(
        r'^([^ a-zA-Z\x80-\xFF]?[a-zA-Z0-9\'\.\-\_\x80-\xFF]*)(\(([^\)]*)\))?([ \t]+)([^#]+)( #(.*))?[ \t]*$'
    )
    format = None
    entry_metadata = None
    for line in read_file(filename, encoding=encoding):
        if line == '':
            yield line, format, None, None, None, None, None, None
            continue

        comment = None
        m = re_linecomment_weide.match(line)
        if m:
            comment, meta, errors = parse_comment_string(m.group(1))
            comment_format = 'cmudict-weide'

        m = re_linecomment_air.match(line)
        if m:
            comment, meta, errors = parse_comment_string(m.group(1))
            comment_format = 'cmudict-air'

        if comment is not None:
            for message in errors:
                yield line, format, None, None, None, None, None, '{0} in entry: "{1}"'.format(
                    message, line)
            if meta:
                if 'format' in meta.keys():
                    format = meta['format'][0]
                    if format == 'cmudict-new':
                        spacing = ' '
                    else:
                        spacing = '  '
                if 'metadata' in meta.keys():
                    if not entry_metadata:
                        entry_metadata = {}
                    entry_metadata.update(metadata.parse(meta['metadata'][0]))
            if not format:  # detect the dictionary format ...
                format = comment_format
                if format == 'cmudict-new':
                    spacing = ' '
                else:
                    spacing = '  '
            if format != 'cmudict-weide' and comment_format == 'cmudict-weide':
                yield line, format, None, None, None, None, None, u'Old-style comment: "{0}"'.format(
                    line)
            elif format == 'cmudict-weide' and comment_format == 'cmudict-air':
                yield line, format, None, None, None, None, None, u'New-style comment: "{0}"'.format(
                    line)
            yield line, format, None, None, None, comment, meta, None
            continue

        m = re_entry.match(line)
        if not m:
            yield line, format, None, None, None, None, None, u'Unsupported entry: "{0}"'.format(
                line)
            continue

        word = m.group(1)
        context = m.group(3)  # 2 = with context markers: `(...)`
        word_phoneme_space = m.group(4)
        phonemes = m.group(5)
        comment = m.group(7) or None  # 6 = with comment marker: `#...`
        meta = None
        if comment:
            comment, meta, errors = parse_comment_string(comment,
                                                         values=entry_metadata)
            for message in errors:
                yield line, format, None, None, None, None, None, '{0} in entry: "{1}"'.format(
                    message, line)

        if not format or format == 'cmudict-air':  # detect the dictionary format ...
            cmudict_fmt = re.compile(
                dict_formats['cmudict']['word-validation'])
            if cmudict_fmt.match(word):
                format = 'cmudict'
                spacing = '  '
            else:
                format = 'cmudict-new'
                spacing = ' '

        if word_phoneme_space != spacing and 'entry-spacing' in checks:
            yield line, format, None, None, None, None, None, u'Entry needs {0} spaces between word and phoneme: "{1}"'.format(
                len(spacing), line)

        if phonemes.endswith(' ') and 'trailing-whitespace' in checks:
            yield line, format, None, None, None, None, None, u'Trailing whitespace in entry: "{0}"'.format(
                line)

        yield line, format, word, context, phonemes, comment, meta, None
Пример #19
0
def parse_cmudict(filename, checks, order_from, encoding):
	"""
		Parse the entries in the cmudict file.

		The return value is of the form:
			(line, format, word, context, phonemes, comment, error)
	"""
	re_linecomment_weide = re.compile(r'^##(.*)$')
	re_linecomment_air   = re.compile(r'^;;;(.*)$')
	re_entry = re.compile(r'^([^ a-zA-Z\x80-\xFF]?[a-zA-Z0-9\'\.\-\_\x80-\xFF]*)(\(([^\)]*)\))?([ \t]+)([^#]+)( #(.*))?[ \t]*$')
	format = None
	entry_metadata = None
	for line in read_file(filename, encoding=encoding):
		if line == '':
			yield line, format, None, None, None, None, None, None
			continue

		comment = None
		m = re_linecomment_weide.match(line)
		if m:
			comment, meta, errors = parse_comment_string(m.group(1))
			comment_format = 'cmudict-weide'

		m = re_linecomment_air.match(line)
		if m:
			comment, meta, errors = parse_comment_string(m.group(1))
			comment_format = 'cmudict-air'

		if comment is not None:
			for message in errors:
				yield line, format, None, None, None, None, None, '{0} in entry: "{1}"'.format(message, line)
			if meta:
				if 'format' in meta.keys():
					format = meta['format'][0]
					if format == 'cmudict-new':
						spacing = ' '
					else:
						spacing = '  '
				if 'metadata' in meta.keys():
					if not entry_metadata:
						entry_metadata = {}
					entry = meta['metadata'][0]
					if entry.startswith('@'):
						t, key = entry[1:].split(':')
						entry_metadata[key] = TypeValidator(t)
					else:
						path = os.path.join(os.path.dirname(filename), entry)
						for key, value in metadata.parse(path).items():
							entry_metadata[key] = SetValidator(value)
			if not format: # detect the dictionary format ...
				format = comment_format
				if format == 'cmudict-new':
					spacing = ' '
				else:
					spacing = '  '
			if format != 'cmudict-weide' and comment_format == 'cmudict-weide':
				yield line, format, None, None, None, None, None, u'Old-style comment: "{0}"'.format(line)
			elif format == 'cmudict-weide' and comment_format == 'cmudict-air':
				yield line, format, None, None, None, None, None, u'New-style comment: "{0}"'.format(line)
			yield line, format, None, None, None, comment, meta, None
			continue

		m = re_entry.match(line)
		if not m:
			yield line, format, None, None, None, None, None, u'Unsupported entry: "{0}"'.format(line)
			continue

		word = m.group(1)
		context = m.group(3) # 2 = with context markers: `(...)`
		word_phoneme_space = m.group(4)
		phonemes = m.group(5)
		comment = m.group(7) or None # 6 = with comment marker: `#...`
		meta = None
		if comment:
			comment, meta, errors = parse_comment_string(comment, values=entry_metadata)
			for message in errors:
				yield line, format, None, None, None, None, None, '{0} in entry: "{1}"'.format(message, line)

		if not format or format == 'cmudict-air': # detect the dictionary format ...
			cmudict_fmt = re.compile(dict_formats['cmudict']['word-validation'])
			if cmudict_fmt.match(word):
				format = 'cmudict'
				spacing = '  '
			else:
				format = 'cmudict-new'
				spacing = ' '

		if word_phoneme_space != spacing and 'entry-spacing' in checks:
			yield line, format, None, None, None, None, None, u'Entry needs {0} spaces between word and phoneme: "{1}"'.format(len(spacing), line)

		if phonemes.endswith(' ') and 'trailing-whitespace' in checks:
			yield line, format, None, None, None, None, None, u'Trailing whitespace in entry: "{0}"'.format(line)

		yield line, format, word, context, phonemes, comment, meta, None
Пример #20
0
    def verify_result_file(self, episode, result, outfile):
        """
        Ensure the given video file matches the user-requested criteria with
        respect to resolution, codec, etc.

        :returns: False if the file could not be parsed, or True if result is verified.
        :raises: RetrieverError if the video file was valid did not pass
                 verification, which will cause the transfer to abort
        """
        if not metadata:
            log.warning(
                'kaa.metadata module not available; skipping file verification'
            )
            return
        info = metadata.parse(outfile)
        if not info:
            if os.path.getsize(outfile) > 1024 * 1024 * 10:
                # We have 10MB of the file and still can't parse it.  Consider
                # it corrupt or unknown.
                raise RetrieverError('could not identify file after 10MB')
            return False
        if info.media != 'MEDIA_AV':
            raise RetrieverError('file is not a video file (is %s)' %
                                 info.media)
        elif not info.video:
            raise RetrieverError('file has no video tracks')

        # Find the video track with the highest (y) resolution.
        # TODO: don't hardcode these
        video = sorted(info.video, key=lambda track: track.height)[-1]
        if (result.quality == 'SD' and (video.height < 240 or video.height > 540)) or \
           (result.quality == 'HD' and video.height < 600):
            raise RetrieverError('video resolution %dx%d does not satisfy requested %s quality' % \
                                 (video.width, video.height, result.quality))

        # See if the audio is the right language.  If the language is specified in any of
        # the tracks, make sure one of them is the user-preferred language.
        langs = set(track.langcode or 'und' for track in info.audio)
        if langs == set(['und']):
            # No languages specified in any track. Disqualify if 'dubbed' appears in
            # the result filename.
            if re.search(r'\bdubbed\b', result.filename, re.I):
                raise RetrieverError(
                    'filename indicates dubbed audio but no language codes specified'
                )
        else:
            lang2to3 = dict(
                (c[1], c[0]) for c in metadata.language.codes if len(c) == 3)
            lang = episode.series.cfg.language or config.misc.language
            threecode = lang2to3.get(lang) if len(lang) == 2 else lang
            log.info('looking for preferred audio track language %s (%s)',
                     threecode, lang)
            if (not threecode or threecode not in langs) and lang not in langs:
                # There are audio tracks with defined languages, but none of
                # them are the language we want.  Heuristic (based on real
                # world content): if the desired language is English and one
                # of the tracks is undefined, assume it's English.
                if threecode == 'eng' and 'und' in langs:
                    log.warning(
                        "no English track found, but assuming 'und' track is English"
                    )
                else:
                    raise RetrieverError('no %s audio track in file' %
                                         threecode)

        # TODO: verify codecs too
        log.debug('%s looks good (%dx%d %s, audio languages: %s)',
                  result.filename, video.width, video.height, video.codec,
                  ', '.join(langs))

        return True
Пример #21
0
def metadata_for(path):
    return metadata.parse(path)