generate wav file by captcha
358145
def generate(captcha, wav_file)
      # get code
      if captcha.is_a? Captcha
        code = captcha.code
      elsif captcha.is_a? String
        code = captcha
      else
        raise ArgumentError, "invalid captcha"
      end

      # add spaces
      code = code.each_char.to_a.join(" ")

      cmd = "espeak -g 10"
      cmd << " -a #{amplitude}" unless @amplitude.nil?
      cmd << " -p #{pitch}" unless @pitch.nil?
      cmd << " -g #{gap}" unless @gap.nil?
      cmd << " -v '#{voice}'" unless @voice.nil?
      cmd << " -w #{wav_file} '#{code}'"

      %x{#{cmd}}
      true
    end
828009
function captcha($font,$size=24,$len=5,
		$key=NULL,$path='',$fg=0xFFFFFF,$bg=0x000000) {
		if ((!$ssl=extension_loaded('openssl')) && ($len<4 || $len>13)) {
			user_error(sprintf(self::E_Length,$len),E_USER_ERROR);
			return FALSE;
		}
		if (!function_exists('imagettftext')) {
			user_error(self::E_TTF,E_USER_ERROR);
			return FALSE;
		}
		$fw=Base::instance();
		foreach ($fw->split($path?:$fw->UI.';./') as $dir)
			if (is_file($path=$dir.$font)) {
				$seed=strtoupper(substr(
					$ssl?bin2hex(openssl_random_pseudo_bytes($len)):uniqid(),
					-$len));
				$block=$size*3;
				$tmp=[];
				for ($i=0,$width=0,$height=0;$i<$len;$i++) {
					// Process at 2x magnification
					$box=imagettfbbox($size*2,0,$path,$seed[$i]);
					$w=$box[2]-$box[0];
					$h=$box[1]-$box[5];
					$char=imagecreatetruecolor($block,$block);
					imagefill($char,0,0,$bg);
					imagettftext($char,$size*2,0,
						($block-$w)/2,$block-($block-$h)/2,
						$fg,$path,$seed[$i]);
					$char=imagerotate($char,mt_rand(-30,30),
						imagecolorallocatealpha($char,0,0,0,127));
					// Reduce to normal size
					$tmp[$i]=imagecreatetruecolor(
						($w=imagesx($char))/2,($h=imagesy($char))/2);
					imagefill($tmp[$i],0,0,IMG_COLOR_TRANSPARENT);
					imagecopyresampled($tmp[$i],
						$char,0,0,0,0,$w/2,$h/2,$w,$h);
					imagedestroy($char);
					$width+=$i+1<$len?$block/2:$w/2;
					$height=max($height,$h/2);
				}
				$this->data=imagecreatetruecolor($width,$height);
				imagefill($this->data,0,0,IMG_COLOR_TRANSPARENT);
				for ($i=0;$i<$len;$i++) {
					imagecopy($this->data,$tmp[$i],
						$i*$block/2,($height-imagesy($tmp[$i]))/2,0,0,
						imagesx($tmp[$i]),imagesy($tmp[$i]));
					imagedestroy($tmp[$i]);
				}
				imagesavealpha($this->data,TRUE);
				if ($key)
					$fw->$key=$seed;
				return $this->save();
			}
		user_error(self::E_Font,E_USER_ERROR);
		return FALSE;
	}
152079
def _generate_MAC(segments=6, segment_length=2, delimiter=":", charset="0123456789abcdef"):
        """"""
        addr = []
        for _ in range(segments):
            sub = ''.join(random.choice(charset) for _ in range(segment_length))
            addr.append(sub)
        return delimiter.join(addr)
288719
def script():
    """"""
    parser = argparse.ArgumentParser(description="Print all textual tags of one or more audio files.")
    parser.add_argument("-b", "--batch", help="disable user interaction", action="store_true")
    parser.add_argument("file", nargs="+", help="file(s) to print tags of")
    args = parser.parse_args()
    for filename in args.file:
        if isinstance(filename, bytes):
            filename = filename.decode(sys.getfilesystemencoding())
        line = "TAGS OF '{0}'".format(os.path.basename(filename))
        print("*" * len(line))
        print(line)
        print("*" * len(line))
        audioFile = taglib.File(filename)
        tags = audioFile.tags
        if len(tags) > 0:
            maxKeyLen = max(len(key) for key in tags.keys())
            for key, values in tags.items():
                for value in values:
                    print(('{0:' + str(maxKeyLen) + '} = {1}').format(key, value))
        if len(audioFile.unsupported) > 0:
            print('Unsupported tag elements: ' + "; ".join(audioFile.unsupported))
            if sys.version_info[0] == 2:
                inputFunction = raw_input
            else:
                inputFunction = input
            if not args.batch and inputFunction("remove unsupported properties? [yN] ").lower() in ["y", "yes"]:
                audioFile.removeUnsupportedProperties(audioFile.unsupported)
                audioFile.save()
519704
def generate_subtitles( # pylint: disable=too-many-locals,too-many-arguments
        source_path,
        output=None,
        concurrency=DEFAULT_CONCURRENCY,
        src_language=DEFAULT_SRC_LANGUAGE,
        dst_language=DEFAULT_DST_LANGUAGE,
        subtitle_file_format=DEFAULT_SUBTITLE_FORMAT,
        api_key=None,
    ):
    
    audio_filename, audio_rate = extract_audio(source_path)

    regions = find_speech_regions(audio_filename)

    pool = multiprocessing.Pool(concurrency)
    converter = FLACConverter(source_path=audio_filename)
    recognizer = SpeechRecognizer(language=src_language, rate=audio_rate,
                                  api_key=GOOGLE_SPEECH_API_KEY)

    transcripts = []
    if regions:
        try:
            widgets = ["Converting speech regions to FLAC files: ", Percentage(), ' ', Bar(), ' ',
                       ETA()]
            pbar = ProgressBar(widgets=widgets, maxval=len(regions)).start()
            extracted_regions = []
            for i, extracted_region in enumerate(pool.imap(converter, regions)):
                extracted_regions.append(extracted_region)
                pbar.update(i)
            pbar.finish()

            widgets = ["Performing speech recognition: ", Percentage(), ' ', Bar(), ' ', ETA()]
            pbar = ProgressBar(widgets=widgets, maxval=len(regions)).start()

            for i, transcript in enumerate(pool.imap(recognizer, extracted_regions)):
                transcripts.append(transcript)
                pbar.update(i)
            pbar.finish()

            if src_language.split("-")[0] != dst_language.split("-")[0]:
                if api_key:
                    google_translate_api_key = api_key
                    translator = Translator(dst_language, google_translate_api_key,
                                            dst=dst_language,
                                            src=src_language)
                    prompt = "Translating from {0} to {1}: ".format(src_language, dst_language)
                    widgets = [prompt, Percentage(), ' ', Bar(), ' ', ETA()]
                    pbar = ProgressBar(widgets=widgets, maxval=len(regions)).start()
                    translated_transcripts = []
                    for i, transcript in enumerate(pool.imap(translator, transcripts)):
                        translated_transcripts.append(transcript)
                        pbar.update(i)
                    pbar.finish()
                    transcripts = translated_transcripts
                else:
                    print(
                        "Error: Subtitle translation requires specified Google Translate API key. "
                        "See --help for further information."
                    )
                    return 1

        except KeyboardInterrupt:
            pbar.finish()
            pool.terminate()
            pool.join()
            print("Cancelling transcription")
            raise

    timed_subtitles = [(r, t) for r, t in zip(regions, transcripts) if t]
    formatter = FORMATTERS.get(subtitle_file_format)
    formatted_subtitles = formatter(timed_subtitles)

    dest = output

    if not dest:
        base = os.path.splitext(source_path)[0]
        dest = "{base}.{format}".format(base=base, format=subtitle_file_format)

    with open(dest, 'wb') as output_file:
        output_file.write(formatted_subtitles.encode("utf-8"))

    os.remove(audio_filename)

    return dest
826140
def main():
    

    # make sure we have enough parameters
    if len(sys.argv) < 6:
        print("You must pass five arguments: QUIT_AFTER BACKWARDS TEXT_FILE_PATH AUDIO_FILE_PATH DATA_FILE_PATH")
        return 1

    # read parameters
    c_quit_after = float(sys.argv[1])   # NOTE: cew needs float, not TimeValue
    c_backwards = int(sys.argv[2])
    text_file_path = sys.argv[3]
    audio_file_path = sys.argv[4]
    data_file_path = sys.argv[5]

    # read (voice_code, text) from file
    s_text = []
    with io.open(text_file_path, "r", encoding="utf-8") as text:
        for line in text.readlines():
            # NOTE: not using strip() to avoid removing trailing blank characters
            line = line.replace(u"\n", u"").replace(u"\r", u"")
            idx = line.find(" ")
            if idx > 0:
                f_voice_code = line[:idx]
                f_text = line[(idx + 1):]
                s_text.append((f_voice_code, f_text))

    # convert to bytes/unicode as required by subprocess
    c_text = []
    if gf.PY2:
        for f_voice_code, f_text in s_text:
            c_text.append((gf.safe_bytes(f_voice_code), gf.safe_bytes(f_text)))
    else:
        for f_voice_code, f_text in s_text:
            c_text.append((gf.safe_unicode(f_voice_code), gf.safe_unicode(f_text)))

    try:
        import aeneas.cew.cew
        sr, sf, intervals = aeneas.cew.cew.synthesize_multiple(
            audio_file_path,
            c_quit_after,
            c_backwards,
            c_text
        )
        with io.open(data_file_path, "w", encoding="utf-8") as data:
            data.write(u"%d\n" % (sr))
            data.write(u"%d\n" % (sf))
            data.write(u"\n".join([u"%.3f %.3f" % (i[0], i[1]) for i in intervals]))
    except Exception as exc:
        print(u"Unexpected error: %s" % str(exc))
539486
def extract_ape (archive, compression, cmd, verbosity, interactive, outdir):
    """"""
    outfile = util.get_single_outfile(outdir, archive, extension=".wav")
    return [cmd, archive, outfile, '-d']
185548
def main():
    

    # Hack related to #58
    if sys.platform == "win32":
        os.system("chcp 65001");

    parser = argparse.ArgumentParser(description='SoundScrape. Scrape an artist from SoundCloud.\n')
    parser.add_argument('artist_url', metavar='U', type=str, nargs='*',
                        help='An artist\'s SoundCloud username or URL')
    parser.add_argument('-n', '--num-tracks', type=int, default=sys.maxsize,
                        help='The number of tracks to download')
    parser.add_argument('-g', '--group', action='store_true',
                        help='Use if downloading tracks from a SoundCloud group')
    parser.add_argument('-b', '--bandcamp', action='store_true',
                        help='Use if downloading from Bandcamp rather than SoundCloud')
    parser.add_argument('-m', '--mixcloud', action='store_true',
                        help='Use if downloading from Mixcloud rather than SoundCloud')
    parser.add_argument('-a', '--audiomack', action='store_true',
                        help='Use if downloading from Audiomack rather than SoundCloud')
    parser.add_argument('-c', '--hive', action='store_true',
                        help='Use if downloading from Hive.co rather than SoundCloud')
    parser.add_argument('-l', '--likes', action='store_true',
                        help='Download all of a user\'s Likes.')
    parser.add_argument('-L', '--login', type=str, default='soundscrape123@mailinator.com',
                        help='Set login')
    parser.add_argument('-d', '--downloadable', action='store_true',
                        help='Only fetch tracks with a Downloadable link.')
    parser.add_argument('-t', '--track', type=str, default='',
                        help='The name of a specific track by an artist')
    parser.add_argument('-f', '--folders', action='store_true',
                        help='Organize saved songs in folders by artists')
    parser.add_argument('-p', '--path', type=str, default='',
                        help='Set directory path where downloads should be saved to')
    parser.add_argument('-P', '--password', type=str, default='soundscraperocks',
                        help='Set password')
    parser.add_argument('-o', '--open', action='store_true',
                        help='Open downloaded files after downloading.')
    parser.add_argument('-k', '--keep', action='store_true',
                        help='Keep 30-second preview tracks')
    parser.add_argument('-v', '--version', action='store_true', default=False,
                        help='Display the current version of SoundScrape')

    args = parser.parse_args()
    vargs = vars(args)

    if vargs['version']:
        import pkg_resources
        version = pkg_resources.require("soundscrape")[0].version
        print(version)
        return

    if not vargs['artist_url']:
        parser.error('Please supply an artist\'s username or URL!')

    if sys.version_info < (3,0,0):
        vargs['artist_url'] = urllib.quote(vargs['artist_url'][0], safe=':/')
    else:
        vargs['artist_url'] = urllib.parse.quote(vargs['artist_url'][0], safe=':/')

    artist_url = vargs['artist_url']

    if not exists(vargs['path']):
        if not access(dirname(vargs['path']), W_OK):
            vargs['path'] = ''
        else:
            mkdir(vargs['path'])

    if 'bandcamp.com' in artist_url or vargs['bandcamp']:
        process_bandcamp(vargs)
    elif 'mixcloud.com' in artist_url or vargs['mixcloud']:
        process_mixcloud(vargs)
    elif 'audiomack.com' in artist_url or vargs['audiomack']:
        process_audiomack(vargs)
    elif 'hive.co' in artist_url or vargs['hive']:
        process_hive(vargs)
    elif 'musicbed.com' in artist_url:
        process_musicbed(vargs)
    else:
        process_soundcloud(vargs)
1296767
def generate_image(self, chars):
        
        background = random_color(238, 255)
        color = random_color(10, 200, random.randint(220, 255))
        im = self.create_captcha_image(chars, color, background)
        self.create_noise_dots(im, color)
        self.create_noise_curve(im, color)
        im = im.filter(ImageFilter.SMOOTH)
        return im
10349
def read_wav(self, filename):
        
        wave_input = None

        try:
            wave_input = wave.open(filename, 'r')
            wave_frames = bytearray(
                wave_input.readframes(wave_input.getnframes()))

            self.sample_data = [x >> 4 for x in wave_frames]

        finally:
            if wave_input is not None:
                wave_input.close()
58260
def convert_to_wav(files):
    ''''''
    converted = []
    for f in files:
        new_name = f + '.temp.wav'
        print(new_name)
        if (os.path.exists(f + '.transcription.txt') is False) and (os.path.exists(new_name) is False):
            subprocess.call(['ffmpeg', '-y', '-i', f, '-acodec', 'pcm_s16le', '-ac', '1', '-ar', '16000', new_name])
        converted.append(new_name)
    return converted
1243074
def frame_generator(frame_duration_ms, audio, sample_rate):
    
    n = int(sample_rate * (frame_duration_ms / 1000.0) * 2)
    offset = 0
    timestamp = 0.0
    duration = (float(n) / sample_rate) / 2.0
    while offset + n < len(audio):
        yield Frame(audio[offset:offset + n], timestamp, duration)
        timestamp += duration
        offset += n
852501
def generate_captcha(self):
        
        # Generate a fresh question
        self._question, answer = self._generate_question()

        # Get the current time, then sign the answer cryptographically
        timestamp = time.time()
        hashed = self.hash_answer(answer, timestamp)

        # Now stash all our values
        self._values = ['', timestamp, hashed]
956569
def convert_to_wav(self, filename):
        
        temp_filename = '{0}.wav'.format(self.temp_filename())
        self.run(['sox', '-G', '-c', '1', filename, temp_filename])
        return temp_filename
70058
def get_context(self, name, value, attrs):
        """"""
        context = super(CaptchaTextInput, self).get_context(name, value, attrs)
        context['image'] = self.image_url()
        context['audio'] = self.audio_url()
        return context
458924
function (opt) {
    var cap = new Captcha(opt);
    cap.use(drawBackground);
    cap.use(drawLines);
    cap.use(drawText);
    cap.use(drawLines);
    return cap;
  }
765318
def audio(hsh, key = nil)
      if !hsh.nil? && hsh.length
        if key.nil?
          hsh['mp3'] ? hsh['mp3'] : hsh['m4a'] ? hsh['m4a'] : hsh['ogg'] ? hsh['ogg'] : hsh['opus'] ? hsh['opus'] : hsh.values.first
        else
          hsh[key]
        end
      end
    end