Esempio n. 1
0
def detect_motion(frameCount):
    global vs, outputFrame, lock, running
    cap = cv2.VideoCapture(0)
    while running:
        ret, frame = cap.read()
        frame, name = Recognize(frame)
        with lock:
            outputFrame = frame.copy()
    cap.release()
Esempio n. 2
0
 def __init__(self):
     self.r = Recognize("data/")
     self.template = read_template("data/translate_template.txt")
     self.chat = read_chat("data/chat.txt")
     self.greeting = read_chat("data/greeting.txt")
     self.day = 0
     self.talk_history = []
     self.my_id = None
     self.my_role = None
     self.co_role = None
     self.divine_results = []
Esempio n. 3
0
    def onRecognize(self):
        self.image = None
        if self.img_dir != '':
            model = Model(self.img_dir)
            recognize = Recognize(model)

            chars = recognize.recognize_all()
            chars = fix(self.img_dir[23], chars)
            for char in chars:
                self.text_frame.insert("end", char)
        else:
            messagebox.showwarning("Warning", "Please input image")
Esempio n. 4
0
def main(args):
    rec = Recognize()
    img = cv2.imread(args.image)

    assert img, f"No such file: '{args.image}'"

    results = rec.recognize(img)
    assert results, "No face found"

    face, scores = results
    face = cv2.resize(face, (256, 256))

    if args.save_face:
        cv2.imwrite("detected_face.png", face)

    for i, score in enumerate(scores):
        name, score = score
        print(f"{i+1}. {name}  score: {score:.5f}")
Esempio n. 5
0
def call_dom():
    Voice.speak_flite("dom is now going to sleep", "call again by saying dom")
    while True:
        response = Recognize.get_recognize_google()
        print(response)
        if response == False:
            pass
        elif "dom" in response.lower() or "start" in response.lower():
            Voice.speak_flite("Listening...")
            break
Esempio n. 6
0
def connect_media_center():
    Voice.speak_flite("Connected to media center",
                      "please speak your commands")
    while True:
        response = Recognize.get_recognize_google()
        print(response)
        if response == False:
            pass
        elif "break" in response or "back" in response or "continue" in response:
            break
        else:
            media_center_control("media center " + response)
Esempio n. 7
0
def play_video(video_name):
    query_string = urllib.parse.urlencode({"search_query": video_name})
    html_content = urllib.request.urlopen("http://www.youtube.com/results?" +
                                          query_string)
    search_results = re.findall(r'},"watchEndpoint":{"videoId":"(.*?)"}},"',
                                html_content.read().decode("utf8"))
    url = "https://www.youtube.com/watch?v=" + search_results[0]
    video = pafy.new(url)
    best = video.audiostreams[0]
    if ".m3u8" in best.url:
        cmd = ['mpv', '-ao', 'oss', best.url]
        p = subprocess.Popen(cmd,
                             stdout=subprocess.PIPE,
                             stdin=subprocess.PIPE)
        sleep(5)
        while True:
            command = Recognize.get_recognize_google()
            print(command)
            if command == False:
                pass
            else:
                if "pause" in command or "stop" in command or "exit" in command or "quit" in command:
                    os.system("pkill mpv")
                    break
    else:
        cmd = ['mpv', '-ao', 'oss', best.url]
        p = subprocess.Popen(cmd,
                             stdout=subprocess.PIPE,
                             stdin=subprocess.PIPE)
        sleep(5)
        while True:
            command = Recognize.get_recognize_google()
            print(command)
            if command == False:
                pass
            else:
                if "pause" in command or "stop" in command or "exit" in command or "quit" in command:
                    os.system("pkill mpv")
                    break
Esempio n. 8
0
def main(phone):
    user = None
    try:
        user = models.session.query(models.Customer).filter(
            models.Customer.telephone == phone).first()
    except:
        print('Ошибка запроса')
    if not user:
        user = models.Customer()
    post = Post()
    invoker = Invoker()
    recognize = Recognize(entity, intent, name, city, product, context_words)
    phrase = PromptStack(invoker, recognize, prompts_dict)
    context = Context(Hello(), user, invoker, phrase, recognize, post)
    context.request()
Esempio n. 9
0
def play_song(song_name):
    song_name = song_name.replace(" ", "+")
    html_data = urllib.request.urlopen(
        urllib.request.Request("https://songspk.mobi/search?q=" + song_name,
                               headers={'User-Agent':
                                        'Mozilla/5.0'})).read().decode("utf8")
    if "<h4>Your search did not yield any results.</h4>" in html_data:
        Voice.speak_flite("I am afraid, i cannot find any songs of that name")
    else:
        link = "https://songspk.mobi" + re.findall('<a href="(.*?)"',
                                                   html_data)[23]
        html_data = urllib.request.urlopen(
            urllib.request.Request(link, headers={'User-Agent': 'Mozilla/5.0'
                                                  })).read().decode("utf8")
        mp3_link = re.findall(
            '<a href="(.*?)" download="" class="btn btn-block btn-default">',
            html_data)[0]

        cmd = ['mplayer', '-novideo', '-ao', 'oss', mp3_link]
        p = subprocess.Popen(cmd,
                             stdout=subprocess.PIPE,
                             stdin=subprocess.PIPE)
        sleep(5)
        while True:
            command = Recognize.get_recognize_google()
            print(command)
            if command == False:
                pass
            else:
                if "pause" in command or "stop" in command or "exit" in command or "quit" in command or "top" in command:
                    os.system("pkill mplayer")
                    Voice.speak_flite("Stopping Song")
                    break
                elif "download to server" in command or "save to server" in command or "download" in command:
                    os.system("pkill mplayer")
                    os.system(
                        "sudo mount -t cifs -o user=root,pass=dietpi //192.168.1.111/dietpi /Dietpi"
                    )
                    Voice.speak_flite("Saving The File")
                    os.system("cd /Dietpi && wget '" + mp3_link + "'")
                    break
Esempio n. 10
0
            boxes, scores, label = list(zip(*data))

            hwriter.add([output], [boxes], [scores], [label])

hwriter.close()

tf.keras.backend.clear_session()

fourcc = cv2.VideoWriter_fourcc('X', 'V', 'I', 'D')
writer = cv2.VideoWriter(outputfile, fourcc, 15, size, True)
tagged = []
graph1 = Graph()
with graph1.as_default():
    session1 = Session()
    with session1.as_default():
        rec = Recognize()
        data = h5py.File(hdf5data)
        for i in range(length):
            image = data['images'][i]
            boxes = data['boxes'][i]
            scores = data['scores'][i]
            labels = data['labels'][i]
            for box, score, label in zip(boxes, scores, labels):
                if score < minc:
                    continue

                (startY, startX, endY, endX) = box
                (H, W) = image.shape[:2]
                startY = int(startY * H)
                startX = int(startX * W)
                endY = int(endY * H)
Esempio n. 11
0
class RuleTranslator:
    def __init__(self):
        self.r = Recognize("data/")
        self.template = read_template("data/translate_template.txt")
        self.chat = read_chat("data/chat.txt")
        self.greeting = read_chat("data/greeting.txt")
        self.day = 0
        self.talk_history = []
        self.my_id = None
        self.my_role = None
        self.co_role = None
        self.divine_results = []

    def set_gamesetting(self, json):
        if json["gameSetting"] is not None:
            random.seed(json["gameSetting"]["randomSeed"] +
                        json["gameInfo"]["agent"])

    def set_gameinfo(self, json):
        if json["gameInfo"] is not None:
            self.my_id = json["gameInfo"]["agent"]
            self.my_role = json["gameInfo"]["roleMap"][str(self.my_id)]
            self.day = json["gameInfo"]["day"]

    def add_talk_history(self, json):
        for t in json["talkHistory"]:
            if t not in self.talk_history:
                self.talk_history.append(t)

    def _choice_reason(self, protocol_text):
        if "VOTE" in protocol_text:
            player = protocol_text.split(" ")[1]
            player_idx = int(player.replace("Agent[", "").replace("]", ""))

            # 自分が人狼 or 狂人COしているかどうか
            if self.co_role == "WEREWOLF" or self.co_role == "POSSESSED":
                return random.choice([
                    "これで終わり!", "楽勝だったね!", "これで勝ちだね。", "たぶんこれでいいと思う!",
                    "そういうわけで、", "言うまでもないかもしれないけど、"
                ])
            # 自分が占い師COしているかどうか
            if self.co_role == "SEER":
                if (player, "HUMAN") in self.divine_results and self.day == 0:
                    return random.choice(
                        ["占い結果は白だったけど、パワープレイは怖いから、", "パワープレイ防止ってことで、"])
                elif (player, "HUMAN") in self.divine_results:
                    return random.choice(["占い結果は白だったけど、もうわけわかんないから、"])
                elif (player, "WEREWOLF") in self.divine_results:
                    return random.choice([
                        "占いの結果が人狼だったから、", "占い結果が黒だったから、", "じゃあ人狼に投票するってことで、",
                        "占いの結果の通り、"
                    ])
            # 占い師COしていない場合
            if self.co_role != "SEER":
                myname = convert_it2name(self.my_id)

                for t in self.talk_history:
                    # 発話ログを検索して自分を投票先にしているものがあれば
                    if "VOTE " + myname in t["text"] and t[
                            "day"] == self.day and t["agent"] == player_idx:
                        return random.choice([
                            "ぼくに投票するって言うのはおかしいから、", "投票先がぼくって言うのは意味不明だよ。",
                            "ぼくに投票するって言うならしょうがないね。"
                        ])
                    elif "DIVINED " + myname + " WEREWOLF" in t["text"] and t[
                            "day"] == self.day and t["agent"] == player_idx:
                        return random.choice([
                            "ぼくを人狼って言う占い師は偽物だから、", "ぼくに黒判定を出した占い師は嘘つきだから、",
                            "偽物の占い師は明らかだよね。"
                        ])
                    elif "DIVINED" + myname + " HUMAN" in t["text"] and t[
                            "day"] == self.day and t["agent"] == player_idx:
                        return "ぼくに白判定を出したけど、人狼の可能性もあるから、"
            return random.choice([
                "ちょっと表情が硬い気がするから、", "とりあえず直感で、", "なんか雰囲気がおかしい気がするから、",
                "何か企んでそうな顔してるし、", "ちょっと挙動不審だし、", "さっきから目が泳いでるから、"
            ])

    def to_text(self, protocol_text, json):
        if len(json["talkHistory"]) == 0 and protocol_text.lower(
        ) == "skip" and self.day == 0:
            return random.choice(self.greeting)

        if protocol_text.lower() == "skip" and self.day == 0 and len(
                json["talkHistory"]) > 0:
            if json["talkHistory"][-1]["turn"] == 0:
                return random.choice(self.chat)

        if len(json["talkHistory"]) == 0 and protocol_text.lower(
        ) == "skip" and is_all_skip(json["talkHistory"]):
            return random.choice(self.chat)

        protocol_text = protocol_text.strip()
        if "{" in protocol_text:
            return protocol_text

        if protocol_text.lower() == "skip" or protocol_text.lower() == "over":
            if len(json["orgTalkHistory"]) > 0:
                for orgt in json["orgTalkHistory"]:
                    if ">>" + convert_it2name(self.my_id) in orgt[
                            "text"] and "?" in orgt["text"] and (
                                "誰" in orgt["text"] or "だれ" in orgt["text"]):
                        text = ">>" + convert_it2name(orgt["agent"]) + " "
                        return text + random.choice([
                            "さっき言ったばっかだよ!", "ぼくの話ちゃんと聞いてた?さっき言ったでしょ!",
                            "なんか適当に質問してない?さっき言ったとこだよ。", "さっきぼく言ったよ?"
                        ])
            return protocol_text

        if is_over_half_skip(json["talkHistory"]):
            return "Skip"

        if "REQUEST" in protocol_text:
            if "DIVINATION" in protocol_text:
                div_target = protocol_text.split("DIVINATION ")[1].split(
                    ")")[0]
                t = random.choice(self.template["REQUEST"]["DIVINATION"])
                t = t.replace("《AGENTNAME》", div_target)
                return t
            elif "VOTE" in protocol_text:
                vote_target = protocol_text.split("VOTE ")[1].split(")")[0]
                t = random.choice(self.template["REQUEST"]["VOTE"])
                t = t.replace("《AGENTNAME》", vote_target)
                return t
            else:
                return random.choice(self.chat)

        elif "CO" in protocol_text:
            role = protocol_text.split(" ")[-1]
            if role == "SEER" or role == "POSSESSED" or role == "WEREWOLF":
                t = random.choice(self.template["COMINGOUT"][role])
                self.co_role = role
                return t
            else:
                return random.choice(self.chat)

        elif "ESTIMATE" in protocol_text:
            player = protocol_text.split(" ")[1]
            role = protocol_text.split(" ")[2]
            t = random.choice(self.template["ESTIMATE"][role])
            t = t.replace("《AGENTNAME》", player)
            return t

        elif "VOTE" in protocol_text:
            player = protocol_text.split(" ")[1]
            t = random.choice(self.template["VOTE"]["ALL"])
            t = t.replace("《AGENTNAME》", player)
            # 理由を追加
            t = self._choice_reason(protocol_text) + t
            # 0日目の場合は雑談に変更
            if self.day == 0:
                t = random.choice(self.chat)

            # 直前の発話にこれから言う内容と同じものがあった場合,同意に変更
            same_talk = get_same_talk(json["talkHistory"], protocol_text,
                                      self.my_id)
            if same_talk is not None:
                t = ">>" + convert_it2name(
                    same_talk["agent"]) + " " + random.choice(
                        self.template["VOTE"]["SAME"])
                t = t.replace("《AGENTNAME》", player)
            return t

        elif "DIVINED" in protocol_text:
            player = protocol_text.split(" ")[1]
            species = protocol_text.split(" ")[2]
            t = random.choice(self.template["DIVINED"][species])
            t = t.replace("《AGENTNAME》", player)
            self.divine_results.append((player, species))
            return t
        else:
            return random.choice(self.chat)

    def to_protocol(self, json):
        # ささやきは削除
        if json['whisperHistory'] is not None:
            json['whisperHistory'] = []

        # 通常発言の処理
        if json['talkHistory'] is not None:
            #もとの発話を保存
            json['orgTalkHistory'] = copy.deepcopy(json['talkHistory'])
            translated_talk = []

            for t in json['talkHistory']:
                self.day = t["day"]  # 日付を取得しておく
                if t["text"].lower() == "over" or t["text"].lower() == "skip":
                    translated_talk.append(t)
                else:
                    res = self.r.recognize(t["text"], t["agent"])
                    if len(res) == 0:
                        t["text"] = "Skip"
                        translated_talk.append(t)
                    elif len(res) == 1:
                        t["text"] = res[0]
                        translated_talk.append(t)
                    else:
                        for s in res:
                            tmp = copy.deepcopy(t)
                            tmp["text"] = s
                            translated_talk.append(tmp)
            json["talkHistory"] = translated_talk
        return json
Esempio n. 12
0
        face_file.seek(0)
        recognize.recognize_face(face_file.name)


def try_connect_kafka():
    print('Trying to connect to Kafka - url: %s, topic %s' %
          (args.faces_source, args.kafka_topic))
    for attempt in range(max_attempts):
        print('Attempt to connect to Kafka - %d tries' % attempt)
        try:
            consumer = KafkaConsumer(args.kafka_topic,
                                     bootstrap_servers=[args.faces_source])
            for msg in consumer:
                process_face(msg.value)
        except:
            print('Error connecting')

        time.sleep(1)


if __name__ == '__main__':
    args = get_command_line_arguments()

    recognize = Recognize(args.known_faces_path)

    if args.unknown_faces_batch:
        recognize.recognize_face_batch(args.unknown_faces_batch)
    elif args.unknown_face:
        recognize.recognize_face(args.unknown_face)

    try_connect_kafka()
Esempio n. 13
0
"""

from os import path
#基于微软必应语音识别
global BING_KEY
BING_KEY = "a0d5d94569064571ac331900a3a61f47"
#因为bing语音识别有7天权限,故设计出全局变量。过期后方便修改
global input_lang

from translation import Translation
from recognize import Recognize
from setting import Setting
from speech import Speech
#从其他脚本中引入设置类(Setting),语音识别类(Recognize),机器翻译类(Translation)和语音合成类(Speech)
if __name__ == '__main__':
    rec_obj = Recognize('语音识别')
    set_obj = Setting('设置')
    trans_obj = Translation("翻译")
    speech_obj = Speech('语音合成')
    #创建四个类的对象
    id_list = [
        '20170601000049695', '20170601000049695', '20180529000169010',
        '20180527000167630'
    ]
    key_list = [
        "ggOxjP2r4I9SsWRDF2ozO", "gOxjP2r4I9SsWRDF2ozO",
        "opRustpMgAtMC18WVtlR", "ct2Zql2XnOFkrmNptBiF"
    ]
    #百度翻译API的id和key列表
    '''
    正确的id_list为id_list=['20170601000049695','20170601000049695','20180529000169010','20180527000167630'];
Esempio n. 14
0
        if "break" in response or "sleep" in response:
            screen.fill((0, 0, 0))
            screen.blit(time, [0, 0])
            screen.blit(monthday, [0, 50])

            blit_text(screen,
                      "dom is now going to sleep, call again by saying dom",
                      (0, 200),
                      fontbig,
                      color=pygame.Color("white"))
            pygame.display.flip()
            pygame.display.update()
            Voice.speak_flite(
                "dom is now going to sleep, call again by saying dom")
            while True:
                response = Recognize.get_recognize_google()
                print(response)
                if response == False:
                    pass
                elif "dom" in response.lower() or "start" in response:
                    screen.fill((0, 0, 0))
                    screen.blit(time, [0, 0])
                    screen.blit(monthday, [0, 50])

                    blit_text(screen,
                              "Listening...", (0, 275),
                              fontbig,
                              color=pygame.Color("white"))
                    pygame.display.flip()
                    pygame.display.update()
                    Voice.speak_flite("Listening...")
Esempio n. 15
0
def main():

    if len(sys.argv) == 1:
        
        print "Format is \n python main.py -[r/g/l] [labels_file] video_name"
        raise Exception(INCORRECT_FORMAT_ERROR)
        
    elif sys.argv[1] == "-r":
        
        if len(sys.argv) != 3:
            print "Format is \n python main.py -[r/g/l] [labels_file] video_name"
            raise Exception(INCORRECT_FORMAT_ERROR)
            
        file_type = mimetypes.guess_type(sys.argv[2])[0]
        if file_type[:3] != "vid":#The file is not a video file
            print "Invalid video file"
            raise Exception(INCORRECT_VIDEO_FILE_ERROR)
            
        print "Recognizing: ", sys.argv[2]
        recog = Recognize(sys.argv[2])
        recog.recognize()

    elif sys.argv[1] == "-g":
        
        if len(sys.argv) != 4:
            print "Format is \n python main.py -[r/g/l] [labels_file] video_name"
            raise Exception(INCORRECT_FORMAT_ERROR)
        
        label_file_type = mimetypes.guess_type(sys.argv[2])[0]
        video_file_type = mimetypes.guess_type(sys.argv[3])[0]
        
        if label_file_type[:3] != "tex":#The file is not a labels file
            print "Invalid labels file"
            raise Exception(INCORRECT_LABEL_FILE_ERROR)
        
        if video_file_type[:3] != "vid":#The file is not a video file
            print "Invalid video file"
            raise Exception(INCORRECT_VIDEO_FILE_ERROR)
            
        print "Generating db for video: ", sys.argv[3], "\nwith labels file:", sys.argv[2]
        gen = Generate(sys.argv[2], sys.argv[3])
        gen.run()

    elif sys.argv[1] == "-l":
        
        if len(sys.argv) != 4:
            print "Format is \n python main.py -[r/g/l] [labels_file] video_name"
            raise Exception(INCORRECT_FORMAT_ERROR)
        
        label_file_type = mimetypes.guess_type(sys.argv[2])[0]
        video_file_type = mimetypes.guess_type(sys.argv[3])[0]
        
        if label_file_type[:3] != "tex":#The file is not a labels file
            return INCORRECT_LABEL_FILE_ERROR
        
        if video_file_type[:3] != "vid":#The file is not a video file
            return INCORRECT_VIDEO_FILE_ERROR
            
        print "Learning for video: ", sys.argv[3]
        video_name = sys.argv[3]
        ffmpeg.convert_video(video_name)
        name, extension = video_name[-5:].split('.')
        name = video_name.split('/')[-1]
        name = name[:-len(extension)-1]
        
        os.system("cp " + sys.argv[2] + " " + WEB_LABELS)        
        os.system("mv " + name + '.webm ' + 'web/output/static/output/' + WEB_VIDEO_NAME)
        print "Please go to the URL to edit labels"
        
    return SUCCESS
Esempio n. 16
0
def main():
    parser = argparse.ArgumentParser(description='Clip Identification system.')
    parser.add_argument('inputfile', metavar='file', type=str, nargs='?',
                    help='File to process. If none passed then read from stdin.')
    parser.add_argument('--sourceid', '-srcid', type=str, required=False, default=None,
                    help='SourceID, if present it\'s added to the Pusher notification (null otherwise).')
    parser.add_argument('--regionid', '-regid', type=str, required=False, default=None,
                    help='RegionID, if present it\'s added to the Pusher notification (null otherwise).')
    parser.add_argument('--scheduleid', '-schid', type=str, required=False, default=None,
                    help='ScheduleID, if present it\'s added to the Pusher notification (null otherwise).')
    parser.add_argument('--programid', '-prgid', type=str, required=False, default=None,
                    help='ProgramID, if present it\'s added to the Pusher notification (null otherwise).')
    parser.add_argument('--programname', '-pn', type=str, required=False, default=None,
                    help='Program Name, if present it\'s added to the Pusher notification (null otherwise).')
    parser.add_argument('--logfile', '-log', type=str,
                    help='Log file path. If not defined it will default\
                    to the tvstation name.log')
 
    args=parser.parse_args()

    if args.inputfile is None:
	print "Reading from stdin..."
        recog = Recognize(None, sourceid=args.sourceid, region=args.regionid, programname=args.programname, programid=args.programid, scheduleid=args.scheduleid)
        recog.recognize()
    else:
	print "Reading from file: ",
	print args.inputfile,
	print "..."
        recog = Recognize(args.inputfile, sourceid=args.sourceid, region=args.regionid, programname=args.programname, programid=args.programid, scheduleid=args.scheduleid)
        recog.recognize()

    sys.exit(1)

    if len(sys.argv) == 1:
        
        print "Format is \n python main.py -[r/g/l] [labels_file] video_name"
        raise Exception(INCORRECT_FORMAT_ERROR)
        
    elif sys.argv[1] == "-r":
        
#        if len(sys.argv) != 3:
#            print "Format is \n python main.py -[r/g/l] [labels_file] video_name"
#            raise Exception(INCORRECT_FORMAT_ERROR)
            
#        file_type = mimetypes.guess_type(sys.argv[2])[0]
#        if file_type[:3] != "vid":#The file is not a video file
#            print "Invalid video file"
#            raise Exception(INCORRECT_VIDEO_FILE_ERROR)
#            
        if len(sys.argv) == 3:
	    print "Recognizing: ", sys.argv[2]
            recog = Recognize(sys.argv[2])
            recog.recognize()
        if len(sys.argv) == 2:
	    print "Recognizing from stdin"
            recog = Recognize(None)
            recog.recognize()
	else:
            print "Format is \n python main.py -[r/g/l] [labels_file] video_name"
            raise Exception(INCORRECT_FORMAT_ERROR)

    elif sys.argv[1] == "-g":
        
        if len(sys.argv) != 4:
            print "Format is \n python main.py -[r/g/l] [labels_file] video_name"
            raise Exception(INCORRECT_FORMAT_ERROR)
        
        label_file_type = mimetypes.guess_type(sys.argv[2])[0]
        video_file_type = mimetypes.guess_type(sys.argv[3])[0]
        
        if label_file_type[:3] != "tex":#The file is not a labels file
            print "Invalid labels file"
            raise Exception(INCORRECT_LABEL_FILE_ERROR)
        
        if video_file_type[:3] != "vid":#The file is not a video file
            print "Invalid video file"
            raise Exception(INCORRECT_VIDEO_FILE_ERROR)
            
        print "Generating db for video: ", sys.argv[3], "\nwith labels file:", sys.argv[2]
        gen = Generate(sys.argv[2], sys.argv[3])
        gen.run()

    elif sys.argv[1] == "-l":
        
        if len(sys.argv) != 4:
            print "Format is \n python main.py -[r/g/l] [labels_file] video_name"
            raise Exception(INCORRECT_FORMAT_ERROR)
        
        label_file_type = mimetypes.guess_type(sys.argv[2])[0]
        video_file_type = mimetypes.guess_type(sys.argv[3])[0]
        
        if label_file_type[:3] != "tex":#The file is not a labels file
            return INCORRECT_LABEL_FILE_ERROR
        
        if video_file_type[:3] != "vid":#The file is not a video file
            return INCORRECT_VIDEO_FILE_ERROR
            
        print "Learning for video: ", sys.argv[3]
        video_name = sys.argv[3]
        ffmpeg.convert_video(video_name)
        name, extension = video_name[-5:].split('.')
        name = video_name.split('/')[-1]
        name = name[:-len(extension)-1]
        
        os.system("cp " + sys.argv[2] + " " + WEB_LABELS)        
        os.system("mv " + name + '.webm ' + 'web/output/static/output/' + WEB_VIDEO_NAME)
        print "Please go to the URL to edit labels"
        
    return SUCCESS
Esempio n. 17
0
def chat():
    news_number = 1
    Name = ""
    Age = 0
    Birthday = ""
    while True:
        inp = Recognize.get_recognize_google()
        #inp = input("Input: ")
        if not inp:
            pass
        else:
            results = model.predict([bag_of_words(inp, words)])[0]
            results_index = numpy.argmax(results)
            tag = labels[results_index]
            if results[results_index] > 0.7:
                for tg in data["intents"]:
                    if tg["tag"] == tag:
                        responses = tg['responses']
                if "song" == responses[0] and "songs" not in responses[0]:
                    if "song" in inp.lower():
                        inp = inp.replace("song", "", 1)
                    if " the " in inp.lower():
                        inp = inp.replace("the", "", 1)
                    if "play" in inp.lower():
                        inp = inp.replace("play", "", 1)
                    if "start" in inp.lower():
                        inp = inp.replace("start", "", 1)
                    if "video" in inp.lower():
                        inp = inp.replace("video", "", 1)
                    if "audio" in inp.lower():
                        inp = inp.replace("audio", "", 1)
                    inp = inp.replace(" ", "")
                    Voice.speak_flite("Playing Audio - " + inp)
                    play_video(inp.lower())
                elif "sleep" == responses[0]:
                    call_dom()
                elif "convert" == responses[0]:
                    us_string_place = 0
                    pkr_string_place = 0
                    for row in range(len(inp.split())):
                        inp = inp.lower()
                        inp = inp.lower()
                        if inp.split()[row] == "us":
                            us_string_place += row
                        elif inp.split()[row] == "rupees":
                            pkr_string_place += row
                    res = [int(i) for i in inp.split() if i.isdigit()][0]
                    if us_string_place > pkr_string_place:
                        number = pkr_to_usd(res)
                        Voice.speak_flite(str(number))
                    else:
                        number = usd_to_pkr(res)
                        Voice.speak_flite(str(number))
                elif "spelling" == responses[0]:
                    if "what" in inp:
                        inp = inp.replace("what", "")
                    if "is" in inp:
                        inp = inp.replace("is", "")
                    if "does" in inp:
                        inp = inp.replace("does", "")
                    if "of" in inp:
                        inp = inp.replace("of", "")
                    if "spelling" in inp:
                        inp = inp.replace("spelling", "")
                    if "spell" in inp:
                        inp = inp.replace("spell", "")
                    inp = inp.replace(" ", "")
                    word = " ".join(inp)
                    for row in range(len(word)):
                        Voice.speak_flite(word[row])
                elif "maths" == responses[0]:
                    if 'square root' in inp:
                        num = [int(i) for i in inp.split() if i.isdigit()][0]
                        square_root = num**0.5
                        Voice.speak_flite(str(square_root))
                    else:
                        first = [int(i) for i in inp.split() if i.isdigit()][0]
                        second = [int(i) for i in inp.split()
                                  if i.isdigit()][1]
                        if '+' in inp:
                            Voice.speak_flite(str(first + second))
                        if '-' in inp:
                            Voice.speak_flite(str(first - second))
                        if '/' in inp:
                            Voice.speak_flite(str(first / second))
                        if '*' in inp:
                            Voice.speak_flite(str(first * second))
                elif "translate" == responses[0]:
                    if "translate" in inp:
                        inp = inp.replace("translate", "")
                    if "to" in inp:
                        inp = inp.replace("to", "")
                    if "what" in inp:
                        inp = inp.replace("what", "")
                    if "does" in inp:
                        inp = inp.replace("does", "")
                    if "english" in inp.lower():
                        inp = inp.replace("english", "")
                        inp = inp.replace(" ", "")
                        Voice.speak_flite(translate_urdu_to_english(inp))
                    elif "urdu" in inp.lower():
                        inp = inp.replace("urdu", "")
                        inp = inp.replace(" ", "")
                        Voice.speak_flite(translate_english_to_urdu(inp))
                elif "system" == responses[0]:
                    if "shutdown" in inp or "poweroff" in inp:
                        os.system("shutdown")
                    elif "reboot" in inp:
                        os.system("reboot")
                elif "time" == responses[0]:
                    currentDT = datetime.datetime.now()
                    if int(currentDT.strftime("%I")) <= 9:
                        Voice.speak_flite(
                            currentDT.strftime("%I:%M %p").replace('0', '', 1))
                    else:
                        Voice.speak_flite(currentDT.strftime("%I:%M %p"))
                elif "day" == responses[0]:
                    currentDT = datetime.datetime.now()
                    Voice.speak_flite(currentDT.strftime("%A, %B, %Y"))
                elif "exit" == responses[0]:
                    break
                elif "recipe" == responses[0]:
                    if "recipe" in inp:
                        inp = inp.replace("recipe", "")
                    elif "for" in inp:
                        inp = inp.replace("for", "")
                    elif "of" in inp:
                        inp = inp.replace("of", "")
                    inp = inp.replace("give", "").replace("me", "").replace(
                        " a ",
                        "").replace("tell",
                                    "").replace("me", "").replace("about", "")
                    info = get_recipe(inp)
                    Voice.speak_flite(info[0])
                    Voice.speak_flite(
                        "You will need the following ingredients")
                    for row in info[1]:
                        Voice.speak_flite(row)
                    for row in info[2]:
                        Voice.speak_flite(row)
                elif "weather" == responses[
                        0] and "i can play songs, tell the weather, tell a joke" not in responses[
                            0]:
                    text = get_weather()
                    Voice.speak_flite(text)
                elif "news" == responses[0]:
                    if "next" in inp:
                        news_number += 1
                        Voice.speak_flite(read_news_headlines(news_number))
                    else:
                        Voice.speak_flite(read_news_headlines(news_number))
                elif "joke" == responses[
                        0] and not "i can play songs, tell the weather, tell a joke" == responses[
                            0]:
                    random_joke = joke()
                    Voice.speak_flite(random_joke[0])
                    Voice.speak_flite(random_joke[1])
                elif "update" == responses[0]:
                    os.system("cd / && ./update.sh")
                    sys.exit()
                elif "create" == responses[0]:
                    Voice.speak_flite("Say The Users Name You Want to Create")
                    name = Recognize.get_recognize_google()
                    Voice.speak_flite("Say The Users Age")
                    age = Recognize.get_recognize_google()
                    Voice.speak_flite("Say The Users Birthday")
                    birthday = Recognize.get_recognize_google()
                    Voice.speak_flite("Name, " + name + " Age, " + age +
                                      " Birthday, " + birthday)
                    Voice.speak_flite(
                        "Are you sure you want to create this user")
                    response = Recognize.get_recognize_google()
                    if "yes" in response:
                        Voice.speak_flite("Creating User")
                        create_user(name, age, birthday)
                elif "user" == responses[0]:
                    for row in get_all_users():
                        response_split = inp.split()
                        for index in response_split:
                            if row[0] == index:
                                Name = row[0]
                                Age = row[1]
                                Birthday = row[2]
                                if row[0] == "Zara":
                                    Voice.speak_flite(
                                        "Hello There Zarah, Welcome Back")
                                elif row[0] == "Ayaan":
                                    Voice.speak_flite(
                                        "Hello There Aion, Welcome Back")
                                else:
                                    Voice.speak_flite("Hello There " + row[0] +
                                                      ", Welcome Back")
                elif "info" == responses[0]:
                    if "birthday" in inp:
                        if Birthday:
                            Voice.speak_flite("Your Birthday comes on " +
                                              Birthday)
                        else:
                            Voice.speak_flite("Please say who you are")
                    elif "age" in inp:
                        if Age:
                            Voice.speak_flite("Your Age is " + str(Age))
                        else:
                            Voice.speak_flite("Please say who you are")
                    elif "name" in inp:
                        if Name:
                            if Name == "Ayaan":
                                Voice.speak_flite("Your Name is Aion")
                            elif Name == "Zara":
                                Voice.speak_flite("You Name is Zarah")
                            else:
                                Voice.speak_flite("Your Name is " + Name)
                        else:
                            Voice.speak_flite("Please say who you are")
                elif "search" == responses[0]:
                    inp = inp.split()
                    srch = []
                    for inp1 in inp:
                        inp = inp1
                        if "is" in inp and "histroy" not in inp:
                            pass
                        elif "was" in inp:
                            pass
                        elif "are" in inp:
                            pass
                        elif "of" in inp:
                            pass
                        elif "who" in inp:
                            pass
                        elif "what" in inp:
                            pass
                        elif "how" in inp:
                            pass
                        elif "why" in inp:
                            pass
                        elif "does" in inp:
                            pass
                        elif "tell" in inp:
                            pass
                        elif "me" in inp:
                            pass
                        elif "about" in inp:
                            pass
                        elif "to" in inp and "histroy" not in inp:
                            pass
                        else:
                            srch.append(inp)
                    inp = srch
                    Voice.speak_flite("Searching about " + " ".join(inp))
                    search = search_wikipedia(inp)
                    Voice.speak_flite(search)
                else:
                    Voice.speak_flite(random.choice(responses))
            else:
                Voice.speak_flite("I do not Understand Please Retry")
Esempio n. 18
0
def main():

    if len(sys.argv) == 1:

        print "Format is \n python main.py -[r/g/l] [labels_file] video_name"
        raise Exception(INCORRECT_FORMAT_ERROR)

    elif sys.argv[1] == "-r":

        if len(sys.argv) != 3:
            print "Format is \n python main.py -[r/g/l] [labels_file] video_name"
            raise Exception(INCORRECT_FORMAT_ERROR)

        file_type = mimetypes.guess_type(sys.argv[2])[0]
        if file_type[:3] != "vid":  #The file is not a video file
            print "Invalid video file"
            raise Exception(INCORRECT_VIDEO_FILE_ERROR)

        print "Recognizing: ", sys.argv[2]
        recog = Recognize(sys.argv[2])
        recog.recognize()

    elif sys.argv[1] == "-g":

        if len(sys.argv) != 4:
            print "Format is \n python main.py -[r/g/l] [labels_file] video_name"
            raise Exception(INCORRECT_FORMAT_ERROR)

        label_file_type = mimetypes.guess_type(sys.argv[2])[0]
        video_file_type = mimetypes.guess_type(sys.argv[3])[0]

        if label_file_type[:3] != "tex":  #The file is not a labels file
            print "Invalid labels file"
            raise Exception(INCORRECT_LABEL_FILE_ERROR)

        if video_file_type[:3] != "vid":  #The file is not a video file
            print "Invalid video file"
            raise Exception(INCORRECT_VIDEO_FILE_ERROR)

        print "Generating db for video: ", sys.argv[
            3], "\nwith labels file:", sys.argv[2]
        gen = Generate(sys.argv[2], sys.argv[3])
        gen.run()

    elif sys.argv[1] == "-l":

        if len(sys.argv) != 4:
            print "Format is \n python main.py -[r/g/l] [labels_file] video_name"
            raise Exception(INCORRECT_FORMAT_ERROR)

        label_file_type = mimetypes.guess_type(sys.argv[2])[0]
        video_file_type = mimetypes.guess_type(sys.argv[3])[0]

        if label_file_type[:3] != "tex":  #The file is not a labels file
            return INCORRECT_LABEL_FILE_ERROR

        if video_file_type[:3] != "vid":  #The file is not a video file
            return INCORRECT_VIDEO_FILE_ERROR

        print "Learning for video: ", sys.argv[3]
        video_name = sys.argv[3]
        ffmpeg.convert_video(video_name)
        name, extension = video_name[-5:].split('.')
        name = video_name.split('/')[-1]
        name = name[:-len(extension) - 1]

        os.system("cp " + sys.argv[2] + " " + WEB_LABELS)
        os.system("mv " + name + '.webm ' + 'web/output/static/output/' +
                  WEB_VIDEO_NAME)
        print "Please go to the URL to edit labels"

    return SUCCESS