Example #1
0
def check_sta(data):
    print('[MAIN] - KIỂM TRA TRẠNG THÁI')
    print('')
    friendly_name = chsv.check_fr(data)
    ex, ey = chsv.export_e_d(friendly_name)
    domain_ex = ex
    entity_id_ex = ey
    domain = gih.get_config('domain')
    password = gih.get_config('hass_password')
    version = gih.get_config('version_above084')
    longlivedtoken = gih.get_config('longlived-token')
    if version == 'right':
        password = longlivedtoken
    else:
        pass
    i = 0
    sta = [0 for x in range(len(domain_ex))]
    while i < len(domain_ex):
        try:
            sta[i] = [
                friendly_name[i], domain_ex[i], entity_id_ex[i], domain,
                password
            ]
            i += 1
        except:
            i += 1
            pass

    return sta
Example #2
0
def find_hass_friendly_name(data):
    print('[MAIN] - KIỂM TRA TÊN THIẾT BỊ')
    print('')
    friendly_name = chsv.check_fr(data)
    ex, ey = chsv.export_e_d(friendly_name)
    domain_ex = ex
    entity_id_ex = ey
    domain = gih.get_config('domain')
    password = gih.get_config('hass_password')
    version = gih.get_config('version_above084')
    longlivedtoken = gih.get_config('longlived-token')
    if version == 'right':
        password = longlivedtoken
    else:
        pass
    m = 0
    object = [
        execute.define(domain_ex, entity_id_ex, domain, password)
        for x in range(len(domain_ex))
    ]
    while m < len(domain_ex):
        object[m] = execute.define(domain_ex[m], entity_id_ex[m], domain,
                                   password)
        object[m] = object[m].define()
        m += 1

    return object
Example #3
0
def weather_json(mode, arr):
    global g_ip  # Global Variable of IP Address
    global g_lat  # Global Variable of Latitude
    global g_lon  # Global Variable of Longnitude
    if (mode == 'ip' or mode == 'IP'):
        if (arr == 0):
            if (g_ip == 0):
                ip_finder()  # For Collecting IP,Lat,Lon
            else:
                g_ip = arr
                ip_finder()  # For Collecing the Lat Lon
        else:
            g_ip = arr
            ip_finder()  # For Collecing the Lat Lon
    elif (mode == 'LATLON' or mode == 'latlon'):
        if (arr[0] != 0 and arr[1] != 0):
            g_lat = arr[0]
            g_lon = arr[1]
        else:
            g_ip = 0
            g_lat = latlong[0]
            g_lon = latlong[1]
            ip_finder()
    else:
        g_lat = latlong[0]
        g_lon = latlong[1]
        ip_finder()
    if (g_lat == 0 or g_lon == 0):
        return ('Error Input')
    else:
        your_darksky_api = gih.get_config('api_darksky')
        #url = 'https://api.darksky.net/forecast/'+your_darksky_api+'/'+str(g_lat)+','+str(g_lon)+'?lang=vi'
        url = 'https://api.darksky.net/forecast/' + your_darksky_api + '/' + str(
            g_lat) + ',' + str(g_lon) + '?lang=vi'
        jsn = requests.get(url)
        if jsn.status_code != 200:
            raise ApiError('GET /tasks/ {}'.format(jsn.status_code))
        else:
            result = jsn.json()
            return (result)
Example #4
0
def config_bot():
    import gih
    from termcolor import colored
    print("HỖ TRỢ CẤU HÌNH BOT")
    print("")
    time.sleep(0.7)
    print(
        colored("VUI LÒNG NHẬP DOMAIN HOME ASSISTANT MÀ BẠN MUỐN KẾT NỐI",
                'yellow') +
        "- NHẬP DẠNG HTTPS://DOMAIN.DUCKDNS.ORG HOẶC HTTP://IP:8123")
    print("")
    print("CẤU HÌNH HIỆN TẠI CỦA DOMAIN ĐANG LÀ: " +
          colored(gih.get_config('domain'), 'red'))
    domain = input("BẠN HÃY NHẬP VÀ DOMAIN MỚI HOẶC NHẬP " +
                   colored('K', 'yellow') + " ĐỂ BỎ QUA: ")
    if str(domain).upper() == 'K':
        pass
    else:
        try:
            gih.set_config('domain', domain)
            print("THIẾT LẬP THÀNH CÔNG DOMAIN LÀ: " +
                  colored(str(domain), 'green'))
        except:
            print("Có lỗi thiết lập, vui lòng thiết lập thủ công phần domain")

    print("")
    time.sleep(0.7)
    print(
        colored("VUI LÒNG NHẬP TOKEN CỦA HOME ASSISTANT", "yellow") +
        "- NẾU CHƯA BIẾT CÁCH TẠO TOKEN XIN VUI LÒNG XEM TRÊN YOUTUBE HƯỚNG DẪN CỦA LBMINH"
    )
    print("CẤU HÌNH HIỆN TẠI CỦA TOKEN ĐANG LÀ: " +
          colored(gih.get_config('longlived-token'), 'red'))
    token = input("BẠN HÃY NHẬP VÀO TOKEN MỚI HOẶC NHẬP " +
                  colored('K', 'yellow') + " ĐỂ BỎ QUA: ")
    if str(token).upper() == 'K':
        pass
    else:
        try:
            gih.set_config('longlived-token', token)
            print("------>THIẾT LẬP THÀNH CÔNG TOKEN LÀ: " +
                  colored(str(token), 'green'))
        except:
            print(
                colored(
                    "Có lỗi thiết lập, vui lòng thiết lập thủ công phần token",
                    "red"))
    print("")
    time.sleep(0.7)
    print(
        colored("BẠN CÓ MUỐN DÙNG API NHẬN GIỌNG KHÔNG", "yellow") +
        " - NẾU KHÔNG DÙNG NHẬN GIỌNG SẼ CHẬM - NẾU DÙNG NHẬN GIỌNG SẼ NHANH HƠN - BẠN PHẢI ĐĂNG KÝ NẾU MUỐN DÙNG"
    )
    time.sleep(0.5)
    print("CẤU HÌNH HIỆN TẠI CỦA API ĐANG LÀ: " +
          colored(gih.get_config('api_active'), 'red'))
    api = input("BẠN HÃY NHẬP VÀO " + colored("0", "yellow") +
                " (KHÔNG DÙNG) HOẶC " + colored("1", "yellow") +
                " (CÓ DÙNG) HOẶC " + colored("K", "yellow") + " ĐỂ BỎ QUA: ")
    if str(api) == "1" or str(api) == "0" or str(api) == "1111":
        gih.set_config('api_active', int(api))
        print("------>THIẾT LẬP API: " + colored(str(api), 'green'))
    elif str(api).upper() == 'K':
        print("GIỮ NGUYÊN THIẾT LẬP API CÓ SẴN")
    else:
        print(
            colored(
                "BẠN NHẬP SAI GIÁ TRỊ RỒI, TIẾN HÀNH SET MẶC ĐỊNH LÀ API: 0",
                "red"))
        gih.set_config('api_active', 0)

    if api == '1':
        print("")
        time.sleep(0.7)
        print("TÊN HIỆN TẠI CỦA API ĐANG LÀ: " +
              colored(gih.get_config('google_application_credentials'), 'red'))
        jsonapi = input(
            "VUI LÒNG NHẬP TÊN MỚI CỦA JSON API - NHẬP DẠNG 'ABCD.JSON' " +
            " - HOẶC ẤN K ĐỂ BỎ QUA: ")
        if str(jsonapi).upper() != "K":
            try:
                gih.set_config('google_application_credentials', jsonapi)
                print(colored('THIẾT LẬP THÀNH CÔNG JSON', 'red'))
            except:
                print(
                    'Lỗi trong quá trình thiết lập tên api. Vui lòng config thủ công'
                )
#CHỌN TTS
    print("")
    time.sleep(0.7)
    print(
        colored("BẠN CÓ MUỐN DÙNG LỰA CHỌN GIỌNG ĐỌC GOOGLE HOẶC FPT",
                "yellow") + " FPT NẾU TRẢ PHÍ GIỌNG RẤT TRUYỀN CẢM")
    time.sleep(0.5)
    print("CẤU HÌNH HIỆN TẠI CỦA TTS ĐANG LÀ: " +
          colored(gih.get_config('tts'), 'red'))
    tts = input("BẠN HÃY NHẬP VÀO " + colored("google", "yellow") +
                " (GOOGLE TTS) HOẶC " + colored("fpt", "yellow") +
                " (FPT TTS) HOẶC " + colored("K", "yellow") + " ĐỂ BỎ QUA: ")
    if str(tts) == "google" or str(tts) == "fpt":
        gih.set_config('tts', str(tts))
        print("------>THIẾT LẬP TTS: " + colored(str(tts), 'green'))
    elif str(tts).upper() == 'K':
        print("GIỮ NGUYÊN THIẾT LẬP TTS CÓ SẴN")
    else:
        print(
            colored(
                "BẠN NHẬP SAI GIÁ TRỊ RỒI, TIẾN HÀNH SET MẶC ĐỊNH LÀ API: google",
                "red"))
        gih.set_config('tts', 'google')
#TTS FPT
    if tts == 'fpt':
        print("")
        time.sleep(0.7)
        print("API HIỆN TẠI CỦA FPT LÀ: " +
              colored(gih.get_config('api_fpt'), 'red'))
        api_fpt = input("NHẬP API CỦA FPT TTS " + " - HOẶC ẤN K ĐỂ BỎ QUA: ")
        if str(api_fpt).upper() != "K":
            try:
                gih.set_config('api_fpt', str(api_fpt))
                print(colored('THIẾT LẬP THÀNH CÔNG FPT TTS', 'red'))
            except:
                print(
                    'Lỗi trong quá trình thiết lập tên api. Vui lòng config thủ công'
                )


#DARSKY
    print("")
    time.sleep(0.7)
    print(
        colored("BẠN CÓ MUỐN KIỂM TRA THỜI TIẾT", "yellow") +
        " THÔNG QUA DARSKY")
    time.sleep(0.5)
    print("CẤU HÌNH HIỆN TẠI CỦA DARKSKY ĐANG LÀ: " +
          colored(gih.get_config('api_darksky'), 'red'))
    darksky = input("BẠN HÃY NHẬP VÀO " + colored("google", "yellow") +
                    " API DARSKY HOẶC " + colored("K", "yellow") +
                    " ĐỂ BỎ QUA: ")
    if str(darksky) != '':
        gih.set_config('api_darksky', darksky)
        print("------>THIẾT LẬP DARKSKY: " + colored(str(darksky), 'green'))
    elif str(darksky).upper() == 'K':
        print("GIỮ NGUYÊN THIẾT LẬP TTS CÓ SẴN")
    else:
        print(
            colored(
                "BẠN NHẬP SAI GIÁ TRỊ RỒI, TIẾN HÀNH SET MẶC ĐỊNH LÀ API: null",
                "red"))
        gih.set_config('api_darksky', 'null')
Example #5
0
if str(b).upper() == 'Y':
    mic_set()
else:
    time.sleep(0.7)
    print('Bỏ qua phần cài đặt microphone và loa')
    time.sleep(0.7)
c = input(
    'Bạn có muốn chạy PHẦN 3- HỖ TRỢ CẤU HÌNH BOT không? - Xin trả lời (Y/N): '
)
time.sleep(0.7)
if str(c).upper() == 'Y':
    from termcolor import colored
    import gih
    config_bot()
    print("CẤU HÌNH HIỆN TẠI CỦA BOT LÀ: ")
    print('DOMAIN: ' + colored(gih.get_config('domain'), 'green'))
    print('TOKEN: ' + colored(gih.get_config('longlived-token'), 'green'))
    print('API: ' + colored(gih.get_config('api_active'), 'green'))
    print('TTS: ' + colored(gih.get_config('tts'), 'green'))
    print(
        'QUÁ TRÌNH CÀI ĐẶT ĐÃ HOÀN TẤT. KẾT THÚC TRÌNH HỖ TRỢ CÀI ĐẶT SAU 3 GIÂY'
    )
    time.sleep(3)
else:
    time.sleep(0.7)
    print('Bỏ qua phần cấu hình')
    time.sleep(0.7)
    print(
        'QUÁ TRÌNH CÀI ĐẶT ĐÃ HOÀN TẤT. KẾT THÚC TRÌNH HỖ TRỢ CÀI ĐẶT SAU 3 GIÂY'
    )
    time.sleep(3)
Example #6
0
# Cài thêm
# pip install bing_tr requests fuzzywuzzy pytest jmespath coloredlogs ratelimit
import requests
from requests import get
import datetime
from datetime import timedelta
#from bing_tr import bing_tr as translate
#from google_tr import google_tr as translate
from googletrans import Translator
translator = Translator()
import gih
latlong = gih.get_config('toado')
g_ip = 0  # Global Variable of IP Address
g_lat = latlong[0]  # Global Variable of Latitude
g_lon = latlong[1]  # Global Variable of Longnitude


def ip_finder():
    global g_ip  # Global Variable of IP Address
    global g_lat  # Global Variable of Latitude
    global g_lon  # Global Variable of Longnitude
    if (g_ip == 0):
        ip = get('https://api.ipify.org'
                 )  # Fetching Current Device Public IP address
        if ip.status_code != 200:
            raise ApiError('GET /tasks/ {}'.format(ip.status_code))
        else:
            ip = ip.text
            g_ip = ip
    yourapi = '128979ae3de728602f249354a85ac508'  # Your API key
    ip_url = 'http://api.ipstack.com/' + g_ip + '?access_key=' + yourapi
Example #7
0
from pygame import mixer
import snowboydecoder
import os
import gser
import legal
import sys
from time import ctime, strftime
import spot
import pixels
import requests
interrupted = False
spo = spot.spo('drlbminh', 'd6881de9093040d8b9c18d669224b559',
               '8f233b0f5037456b9c5e084f3f069efd', 'http://localhost:9999/')
spotipy = spo.assign()

reminder = gih.get_config('reminder')
ggcre = gih.get_config('google_application_credentials')
os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = ggcre
api_boolean = gih.get_config('api_active')
hotword = gih.get_config('hotword')
con = lite.connect('data.db', check_same_thread=False)
timlenh = lite.connect('data.db', check_same_thread=False)
hehe = lite.connect('hehe.db', check_same_thread=False)
model = gih.get_config('model')
sensitivity = gih.get_config('sensitivity')
detector = snowboydecoder.HotwordDetector(model, sensitivity=sensitivity)
domain = gih.get_config('domain')
password = gih.get_config('hass_password')
version = gih.get_config('version_above084')
longlivedtoken = gih.get_config('longlived-token')
voice = gih.get_config('voice')
Example #8
0
def xuly():
    if seed == 1:
        pixels.pixels.wakeup()
    if ok == 0:
        trial_times = 0
        speaking.speak('đây là bản dùng thử')
        trial_times += 1
        if trial_times < 20:
            print(
                colored('Số lần request còn lại: ' + str(21 - trial_times),
                        'red'))
        else:
            print(
                colored(
                    '[ERROR] - Hết giới hạn dùng thử. Vui lòng khởi động lại BOT',
                    'red'))
            speaking.speak(
                'Hết giới hạn dùng thử. Khởi động lại bot để dùng tiếp')
            sys.exit(0)
    print('[MAIN] - TIẾP NHẬN XỬ LÝ')
    print('')
    spotify = gih.get_config('spotify')
    if spotify == 1:
        try:
            dem.player.audio_set_volume(40)
        except:
            pass
        try:
            global volume
            volume = spotipy.devices()
            volume = volume['devices'][0]['volume_percent']
            #			print('volume truoc khi giam '+ str(volume))
            spotipy.volume(36)
        except:
            pass
    else:
        pass
#		player_volume=dem.radio.lay_am_luong()
#		dem.player.audio_set_volume(player_volume - 35)
    data = 'interruptinterrupt'
    while data == 'interruptinterrupt':
        print(
            colored(
                'tôi ĐANG CHỜ RA LỆNH - BẬT TẮT <TÊN THIẾT BỊ> HAY HỎI MẤY GIỜ RỒI...',
                'green'))
        conti = 1
        from pygame import mixer
        mixer.init(48000, -16, 1, 4096)
        mixer.music.load('resources/ding.wav')
        mixer.music.play()
        try:
            #	Dùng API Google
            if api_boolean == 1:
                print('------------------------------------------------------')
                print(
                    colored(
                        '-------------------------CÓ DÙNG API GOOGLE-----------------',
                        'green'))
                print('------------------------------------------------------')
                data = tsm.main()
                conti = 1
#	Không dùng API Google
            elif api_boolean == 0:
                print('------------------------------------------------------')
                print(
                    colored(
                        '---------------KHÔNG DÙNG API, SẼ NHẬN CHẬM LẮM ĐÂY, MÔI TRƯỜNG ÍT ỒN SẼ DỄ NHẬN HƠN (TRÁNH QUẠT, MÁY LẠNH)-------------',
                        'red'))
                print('------------------------------------------------------')
                data = dem.recordAudio()
                conti = 1
                if hotword.upper() in str(data).upper():
                    data == 'interruptinterrupt'
#	Dùng API FPT
            elif api_boolean == 2:
                print('------------------------------------------------------')
                print(
                    colored('---------------DÙNG API FPT-------------',
                            'yellow'))
                print('------------------------------------------------------')
                data = dem.recordFPT()
                conti = 1
                if hotword.upper() in str(data).upper():
                    data == 'interruptinterrupt'
#	Dùng API VTCC
            elif api_boolean == 3:
                print('------------------------------------------------------')
                print(
                    colored('---------------DÙNG API VIETTEL-------------',
                            'blue'))
                print('------------------------------------------------------')
                data = dem.recordVTCC()
                conti = 1
                if hotword.upper() in str(data).upper():
                    data == 'interruptinterrupt'


#	Sử dụng text input
            else:
                data = input("Nhập lệnh cần thực thi:  ")
                conti = 1
        except:
            conti = 0
            break

    mixer.music.load('resources/dong.wav')
    mixer.music.play()
    if seed == 1:
        pixels.pixels.think()
    if conti == 1 and str(data).upper() != 'ĐƯỢC RỒI':
        try:
            jarvis(data)
        except Exception as e:
            print(e)
    giophut = str(strftime("%H")) + ':' + str(strftime("%M"))
    ai_data = (data, giophut, "")
    try:
        with hehe:
            haha = hehe.cursor()
            haha.execute("INSERT INTO ai_data VALUES(?,?,?)", ai_data)
    except:
        print('writing ai_data ee')
        pass
    if spotify == 0:
        try:
            player_volume = dem.radio.lay_am_luong()
            dem.player.audio_set_volume(player_volume - 35)
            time.sleep(0.1)
            dem.player.audio_set_volume(player_volume - 20)
            time.sleep(0.1)
            dem.player.audio_set_volume(player_volume)
        except:
            pass
    if spotify == 1:
        try:
            volume = dem.spotipy[1].devices(dem.spotipy[0])
            volume = volume[2]
            #			print('volume sau khi giam: ' + str(volume))
            spotipy.volume(volume - 35)
            time.sleep(0.1)
            spotipy.volume(volume - 20)
            time.sleep(0.1)
            spotipy.volume(volume)
        except Exception as e:
            print('spotify: ' + str(e))
    if seed == 1:
        pixels.pixels.off()
    print(colored('*****************SẴN SÀNG CHỜ GỌI****************',
                  'green'))
Example #9
0
import gih
import tsm
import sys
import spotipy
import spotipy.util as util
import time
import random
import speaking
import os
from pygame import mixer
api_boolean= gih.get_config('api_active')
ggcre = gih.get_config('google_application_credentials')
os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = ggcre
def re_ask():
	print('[MAIN] - HỎI LẠI')
	print('')
	mixer.music.load('resources/ding.wav')
	mixer.music.play()
# if api_boolean==1:
	more_data = tsm.main()
	return more_data
	# elif api_boolean ==0:
	#	 more_data = dem.recordAudio()
	#	 return more_data
class spo():
	def __init__(self,username,client_id,client_secret,redirect_uri):
		self.client_id = client_id
		self.client_secret = client_secret
		self.redirect_uri=redirect_uri
		self.username=username
		self.scope='user-read-currently-playing,app-remote-control,user-read-playback-state,user-modify-playback-state,playlist-read-collaborative,user-library-read'
Example #10
0
import amlich
import thu
import ngayle
import tintuc
import loto
import fun
import execute
import re
import radio
import weth
import wk
import spot
import speech_recognition as sr
import wether as wt
from pygame import mixer
spotify = gih.get_config('spotify')
spotify_username = gih.get_config('spotify_username')
spotify_client_id = gih.get_config('spotify_client_id')
spotify_client_secret = gih.get_config('spotify_client_secret')


def recordAudio():
    r = sr.Recognizer()
    with sr.Microphone() as source:
        r.adjust_for_ambient_noise(source, duration=1)
        audio = r.listen(source)
    data = ""
    try:
        data = r.recognize_google(audio, language="vi-VN")
        print('BOT nghe được: ' + data)
    except sr.UnknownValueError:
Example #11
0
def hamthucthi(row0_in_db, data, friendly_name_hass, sta):
    global player
    print('[MAIN] - THỰC THI TÁC VỤ')
    print('---------')
    processss.timlenhtrongdata(data)
    if row0_in_db == "KHỎE KHÔNG":
        answer("tôi khỏe.", "khỏe lắm chủ nhân", "khỏe chứ chủ nhân.")
#camera - dieu khien xoay
    elif row0_in_db == "CAMERA":
        print('vao camera')
        a = ptz.control('http://192.168.9.121', 'admin', 'Emilybro2013')
        datapreset = data
        datapreset = datapreset.split()
        iiii = 0
        while iiii < len(datapreset):
            if datapreset[iiii].isnumeric() == True:
                preset_number = datapreset[iiii]
                break
            else:
                iiii += 1
        try:
            a.set_preset(preset_number)
        except:
            pass
        if 'LÊN' in data.upper():
            print('vao len')
            a.len()
            time.sleep(2)
            return
        if 'XUỐNG' in data.upper():
            a.xuong()
            time.sleep(2)
            return
        if 'TRÁI' in data.upper():
            a.trai()
            time.sleep(2)
            return
        if 'PHẢI' in data.upper():
            a.phai()
            time.sleep(2)
            return
# Âm lịch
    elif row0_in_db == "ÂM LỊCH":
        check_day = []
        if 'MAI' in data:
            check_day = amlich.ngaymai()
        elif 'MỐT' in data:
            check_day = amlich.ngaymot()
        elif 'QUA' in data:
            check_day = amlich.homqua()
        elif 'NAY' in data:
            check_day = amlich.homnay()
        else:
            check_day = amlich.ngaykhac(data)
        amlich.kiemtra_amlich(check_day[0], check_day[1], check_day[2],
                              check_day[3], check_day[4])
#Hỏi thứ
    elif row0_in_db == "THỨ MẤY":
        check_thu = []
        if 'MAI' in data:
            check_thu = thu.ngaymai()
        elif 'MỐT' in data:
            check_thu = thu.ngaymot()
        elif 'QUA' in data:
            check_thu = thu.homqua()
        elif 'NAY' in data:
            check_thu = thu.homnay()
        else:
            check_thu = thu.ngaykhac(data)
        result_thu = thu.kiemtra_thu(check_thu[0], check_thu[1], check_thu[2],
                                     check_thu[3], check_thu[4])
        speaking.speak(result_thu[0] + " là " + result_thu[1] + result_thu[2] +
                       ' tháng ' + str(result_thu[3]))
# Ngày lễ
    elif row0_in_db == "NGÀY LỄ":
        ngayle_res = []
        ngayle_res = ngayle.ngayle_check(data)
        speaking.speak(ngayle_res[0] + ' Còn ' + str(ngayle_res[1]) +
                       ' ngày nữa là đến ' + ngayle_res[2] + '. Đó là ngày ' +
                       ngayle_res[3] + ' tháng ' + ngayle_res[4] + ' năm ' +
                       ngayle_res[5])
#Cảm ơn
    elif row0_in_db == "CẢM ƠN":
        answer('không có chi. ', 'rất vui vì giúp được chủ nhân ',
               ' đừng bận tâm ')
#HELP
    elif row0_in_db == "TRỢ GIÚP":
        if 'THỜI TIẾT' in data:
            speaking.speak(
                'Có thể hỏi các câu hỏi bao gồm các từ như, Thời tiết hôm nay, ngày mai'
            )
        elif 'GIỜ' in data:
            speaking.speak('Đặt câu hỏi mấy giờ rồi')
        elif 'NGÀY' in data:
            speaking.speak(
                'Hỏi thứ mấy, ngày nào. Có thể hỏi ngày mai là thứ mấy, ngày 30 tháng 4 là thứ mấy, vv.'
            )
        elif 'ÂM LỊCH' in data:
            speaking.speak('Hỏi âm lịch hôm nay, ngày mai, ngày bất kì')
        elif 'DỊCH' in data:
            speaking.speak(
                'Dịch từ tHoặc dịch cả câu với cấu trức: Dịch câu sau sang tiếng nào đó. Sau đó chờ âm báo rồi đọc câu. Ngôn ngữ hỗ trợ: Việt, chủ nhân, Trung, Nhật, Hàn.'
            )
        elif 'THÔNG TIN' in data:
            speaking.speak(
                'Có thể hỏi thông tin bằng câu với kết thúc là gì hoặc là ai. Ví dụ, Hồ Chí Minh là ai.'
            )
        elif 'LỆNH' in data:
            speaking.speak(
                'Có thể bật, tắt, điều chỉnh nhiệt độ máy lạnh .... bằng các câu lệnh đơn giản như: bật đèn, tắt đèn, ....'
            )
        elif 'NHẠC' in data:
            speaking.speak(
                'Dùng lệnh Phát rồi gọi tên bài hát, playlist muốn nghe. Muốn qua bài thì dùng lệnh Tiếp theo. Dừng với lệnh Dừng nhạc'
            )
        elif 'HẸN GIỜ' in data:
            speaking.speak(
                'Dùng lệnh hẹn giờ cộng thời gian, hủy với lệnh hủy hẹn giờ')
        elif 'NGÀY LỄ' in data:
            speaking.speak(
                'Hỏi còn bao nhiêu ngày nữa là đến ngày lễ. Các ngày lễ có sẵn bao gồm, Tết Tây, Tết ta, 30 tháng 4, trung thu, giỗ tổ, quốc khánh. '
            )
        else:
            speaking.speak(
                'Các lệnh thường dùng, Hỏi giờ, thời tiết, thứ ngày tháng, thông tin, lệnh, phát nhạc, hẹn giờ, dịch từ, dịch câu, âm lịch, ngày lễ. Dùng lệnh trợ giúp kèm theo các lệnh muốn tra cứu để được hướng dẫn chi tiết hơn.'
            )
#Hỏi giờ
    elif row0_in_db == "MẤY GIỜ":
        import speaking
        from time import ctime, strftime
        gio = strftime("%H")
        gio = list(gio)
        phut = strftime("%M")
        phut = list(phut)
        if gio[0] == '1':
            if gio[1] == '0':
                docgio = 'mười giờ '
            else:
                docgio = 'mười ' + gio[1] + ' giờ '
        elif gio[0] == '0':
            docgio = gio[1] + ' giờ '
        elif gio[0] == '2':
            if gio[1] == '0':
                docgio = 'hai mươi giờ '
            elif gio[1] == '1':
                docgio = 'hai mươi mốt giờ '
            else:
                docgio = 'hai mươi ' + gio[1] + ' giờ '

        if phut[0] == '0':
            docphut = phut[1] + ' phút '
        elif phut[0] == '1':
            if phut[1] == '0':
                docphut = ' mười phút '
            else:
                docphut = ' mười ' + phut[1] + ' phút '
        else:
            if phut[1] == '0':
                docphut = phut[0] + ' mươi phút '
            elif phut[1] == '1':
                docphut = phut[0] + ' mươi mốt phút '
            else:
                docphut = phut[0] + ' mươi ' + phut[1] + ' phút '
        speaking.speakvn("BÂY GIỜ LÀ " + docgio + docphut)
#Tin tức (TTS)
    elif row0_in_db == "TIN TỨC":
        tintuc.tintucmoi()
    elif row0_in_db == "XỔ SỐ":
        print('Kết quả xổ số')
        loto.check(data)
#Truyện cười
    elif row0_in_db == "CƯỜI":
        truyen = fun.truyen()
        speaking.speak(truyen)
    elif row0_in_db == "RADIO":
        try:
            player.stop()
        except:
            pass
        player = radio.phat_radio(data)
    elif row0_in_db == "ĐI NGỦ":
        pass
    elif row0_in_db == "LÀ GÌ":

        def wifi(data):
            data = data[0:len(data) - 6]
            rep = wk.find_info(data)
            rep = rep.find_wiki()
            speaking.speak('Theo wikipedia: ' + rep)

        speaking.speak('để tôi tìm xem nào')
        execute.run_thread(wifi, data)
# Phát video
    elif row0_in_db == "PHÁT":
        if spotify == 1:
            global spotipy
            try:
                player.stop()
            except:
                pass
            spotipy = spot.play_current_playlist(spotify_username,
                                                 spotify_client_id,
                                                 spotify_client_secret,
                                                 'http://localhost:9999/',
                                                 data)
        if spotify == 0:
            global link_yt
            try:
                we.put('quit')
                w.put('quit')
                wet.put('quit')
            except:
                print('er put')
            we = queue.Queue()
            locationtim = data.find('PHÁT')
            data = data[locationtim + 5:len(data)]
            query_string = urllib.parse.urlencode({"search_query": data})
            html_content = urllib.request.urlopen(
                "http://www.youtube.com/results?" + query_string)
            search_results = re.findall(r'href=\"\/watch\?v=(.{11})',
                                        html_content.read().decode())
            random_song = random.randint(0, 10)
            urlyt = "http://www.youtube.com/watch?v=" + search_results[
                random_song]
            search_pre_write = (search_results[0], search_results[1],
                                search_results[2], search_results[3],
                                search_results[4], search_results[5],
                                search_results[6], search_results[7],
                                search_results[8], search_results[9],
                                search_results[10], random_song)
            import speaking
            import threading
            import vlc
            import pafy
            import gih
            speaking.speakvn('Chuẩn bị phát nhạc')

            def yt_play(urlyt, we):
                try:
                    video = pafy.new(urlyt)
                    best = video.getbestaudio()
                    playurl = best.url
                    Instance = vlc.Instance()
                    player = Instance.media_player_new()
                    Media = Instance.media_new(playurl)
                    Media.get_mrl()
                    player.set_media(Media)
                    player.play()
                    we.put('start')
                    m = alsaaudio.Mixer()
                    vol = m.getvolume()
                    vol = int(vol[0])
                    player_volume = vol
                    player.audio_set_volume(player_volume)
                    while True:
                        player.play()
                        item = we.get()
                        if item == 'quit':
                            player.stop()
                            break
                        if item == 'listen_mode':
                            m = alsaaudio.Mixer()
                            vol = m.getvolume()
                            vol = int(vol[0])
                            player_volume = vol
                            player.audio_set_volume(player_volume - 35)
                        if item == 'normal_mode':
                            m = alsaaudio.Mixer()
                            vol = m.getvolume()
                            vol = int(vol[0])
                            player_volume = vol
                            player.audio_set_volume(player_volume - 35)
                            time.sleep(0.7)
                            player.audio_set_volume(player_volume - 25)
                            time.sleep(0.7)
                            player.audio_set_volume(player_volume - 15)
                            time.sleep(0.7)
                            player.audio_set_volume(player_volume)
                except Exception as e:
                    print('error vlc')
                    print(e)

            t = threading.Thread(target=yt_play, args=(urlyt, we))
            t.start()
            link_yt = gih.info_user()
            with link_yt:
                link_yt_ex = link_yt.cursor()
                link_yt_ex.execute(
                    "INSERT INTO link_music_youtube VALUES(?,?,?,?,?,?)",
                    search_pre_write)
        else:
            player = radio.play_nhac(data, friendly_name_hass)
            player.play()
    elif row0_in_db == "TIẾP THEO":
        if spotify == 1:
            try:
                player.stop()
            except:
                pass
            spotipy = spot.play_current_playlist(spotify_username,
                                                 spotify_client_id,
                                                 spotify_client_secret,
                                                 'http://localhost:9999/',
                                                 data)
        else:
            player = radio.phat_tiep_theo()
# Google word translate
    elif row0_in_db == "CÓ NGHĨA":
        from googletrans import Translator
        translator = Translator()
        print(data)
        data = data.replace('TỪ ', '')
        data = data.replace('TRONG ', '')
        #		print ('Edit ' + data)
        # To Vietnamese
        if 'VIỆT' in data:
            m = re.search('(.+?) TIẾNG VIỆT', data)
            dataen = m.group(1)
            print(dataen)
            translations = translator.translate(dataen, dest='vi')
            print(translations.text)
            speaking.speak('Từ ')
            speaking.speaken(dataen)
            speaking.speak('trong tiếng việt nghĩa là: ' + translations.text)
#To English
        elif 'TIẾNG chủ nhân' in data:
            m = re.search('(.+?) TIẾNG chủ nhân', data)
            dataen = m.group(1)
            print(dataen)
            translations = translator.translate(dataen, dest='en')
            print(translations.text)
            speaking.speak('Từ ' + dataen + ' trong tiếng chủ nhân nghĩa là: ')
            speaking.speaken(translations.text)
# To Korean
        elif 'TIẾNG HÀN' in data:
            m = re.search('(.+?) TIẾNG HÀN', data)
            dataen = m.group(1)
            print(dataen)
            translations = translator.translate(dataen, dest='ko')
            print(translations.text)
            speaking.speak('Từ ' + dataen + ' trong tiếng Hàn nghĩa là: ')
            speaking.speakko(translations.text)
# To Japanese
        elif 'TIẾNG NHẬT' in data:
            m = re.search('(.+?) TIẾNG NHẬT', data)
            dataen = m.group(1)
            print(dataen)
            translations = translator.translate(dataen, dest='ja')
            print(translations.text)
            speaking.speak('Từ ' + dataen + ' trong tiếng Nhật nghĩa là: ')
            speaking.speakja(translations.text)
# To Chinese
        elif 'TIẾNG TRUNG' in data:
            m = re.search('(.+?) TIẾNG TRUNG', data)
            dataen = m.group(1)
            print(dataen)
            translations = translator.translate(dataen, dest='zh-cn')
            print(translations.text)
            speaking.speak('Từ ' + dataen + ' trong tiếng TRUNG nghĩa là: ')
            speaking.speakzh(translations.text)
# Google sentence translate
    elif row0_in_db == "DỊCH CÂU":
        from googletrans import Translator
        translator = Translator()
        continue_go = 1
        speaking.speak('OK, đọc câu cần dịch đi chủ nhân')
        processss.mixer.music.load('resources/ding.wav')
        processss.mixer.music.play()
        more_data = processss.re_ask()
        print(more_data)
        if len(more_data) > 0:
            while True:
                print('Google translate: ' + data)
                print('Data translate: ' + more_data)
                processss.mixer.music.load('resources/dong.wav')
                processss.mixer.music.play()
                if 'TIẾNG ANH' in data:
                    translations = translator.translate(more_data, dest='en')
                    print(translations.text)
                    speaking.speaken(translations.text)
                    continue_go = 1
                if 'TIẾNG VIỆT' in data:
                    translations = translator.translate(more_data, dest='vi')
                    print(translations.text)
                    speaking.speak(translations.text)
                    continue_go = 1
                if 'TIẾNG HÀN' in data:
                    translations = translator.translate(more_data, dest='ko')
                    print(translations.text)
                    speaking.speakko(translations.text)
                    continue_go = 1
                if 'TIẾNG TRUNG' in data:
                    translations = translator.translate(more_data,
                                                        dest='zh-cn')
                    print(translations.text)
                    speaking.speakzh(translations.text)
                    continue_go = 1
                if 'TIẾNG NHẬT' in data:
                    translations = translator.translate(more_data, dest='ja')
                    print(translations.text)
                    speaking.speakja(translations.text)
                    continue_go = 1
                if 'HỦY' in more_data:
                    speaking.speak('thoát khỏi chế độ dịch')
                    continue_go = 0
                    break
                else:
                    break
        else:
            speaking.speakvn('Xin lỗi, tôi không nghe được câu hỏi')
# Hẹn giờ
    elif row0_in_db == "HẸN GIỜ":
        onoff.hen_gio(data)
    elif row0_in_db == "HỦY HẸN GIỜ":
        onoff.t1.cancel()
        speaking.speak("đã hủy hẹn giờ ")
    elif row0_in_db == "DỪNG":
        if spotify == 1:
            try:
                player.stop()
            except Exception as e:
                print(e)
                pass
            at = spot.spo(spotify_username, spotify_client_id,
                          spotify_client_secret, 'http://localhost:9999/')
            sp = at.assign()
            de = sp.devices()
            de = de['devices']
            for des in de:
                print(des['id'])
                try:
                    at.pause(sp, des['id'])
                except Exception as t:
                    print(t)
                    pass
        else:
            try:
                w.put('quit')
            except:
                pass
            try:
                we.put('quit')
            except:
                pass
            try:
                wet.put('quit')
            except:
                pass
    elif row0_in_db == "TO LÊN":
        radio.to_len()
    elif row0_in_db == "NHỎ XUỐNG":
        radio.nho_xuong()
    elif row0_in_db == "ÂM LƯỢNG":
        vol_extract = radio.amluong(data)
        speaking.speak("thiết lập âm lượng mức " + str(vol_extract))
    elif row0_in_db == "THIẾT LẬP":
        onoff.thietlap(friendly_name_hass, sta, data)
    elif row0_in_db == "MỞ":
        onoff.on_mo(friendly_name_hass, data)
    elif row0_in_db == "TẮT":
        onoff.off_tat(friendly_name_hass, data)
    elif row0_in_db == "TÊN":
        if "tôi" in data:
            answer(
                'tôi là BOT LB',
                'tôi là LB ',
                'tôi tên LB',
            )
    elif row0_in_db == "":
        speaking.speak('tôi không hiểu rồi đại ca ơi')
# Trạng thái
    elif row0_in_db == "TRẠNG THÁI":
        onoff.trangthai(sta)


#Thời tiết
    elif row0_in_db == "THỜI TIẾT":
        import speaking
        import gih
        latlong = gih.get_config('toado')
        import datetime
        from datetime import timedelta
        x = datetime.datetime.now()
        answer('đang kiểm tra thông tin thời tiết', 'để tôi kiểm tra',
               'tôi kiểm tra ngay')
        if 'NGÀY MAI' in data:
            y = x + datetime.timedelta(1)
            day = str(y.day)
            tt = wt.weekly('latlon', latlong)
            speaking.speakvn('Ngày mai ' + tt[day]['overal'] +
                             ', Nhiệt độ thấp nhất ' +
                             str(tt[day]['mintemp']) +
                             ' độ C, Nhiệt độ cao nhất ' +
                             str(tt[day]['maxtemp']) + ' độ C,  độ ẩm là ' +
                             str(tt[day]['hum']) +
                             ' phần trăm, tốc độ gió trung bình ' +
                             str(tt[day]['wind']) + ' km/h.')
        elif 'HÔM NAY' in data:
            tt = wt.current('latlon', latlong)
            speaking.speakvn('Hôm nay ' + tt['overal'] + ', Nhiệt độ là ' +
                             str(tt['temp']) + ' độ C,  độ ẩm là ' +
                             str(tt['hum']) +
                             ' phần trăm, tốc độ gió trung bình ' +
                             str(tt['wind']) + ' km/h.')
        elif 'GIỜ TỚI' in data:
            string = data
            num = [int(s) for s in string.split() if s.isdigit()]
            if len(num) > 0:
                from datetime import timedelta
                y = x + timedelta(hours=num[0])
                if y.hour < 25:
                    day = 'today'
                    ngay = ' giờ hôm nay '
                elif y.hour > 24:
                    day = 'tomorrow'
                    ngay = ' giờ ngày mai '
                tt = wt.hourly('latlon', latlong)
                speaking.speakvn('Thời tiết lúc ' + str(y.hour) + ngay +
                                 tt[day]["%.1f" % y.hour]['overal'] +
                                 ', Nhiệt độ là ' +
                                 str(tt[day]["%.1f" % y.hour]['temp']) +
                                 ' độ C,  độ ẩm là ' +
                                 str(tt[day]["%.1f" % y.hour]['hum']) +
                                 ' phần trăm, tốc độ gió trung bình ' +
                                 str(tt[day]["%.1f" % y.hour]['wind']) +
                                 ' km/h.')
            else:
                pass
        elif 'TUẦN' in data.upper():
            for i in range(1, 7):
                y = x + datetime.timedelta(i)
                day = str(y.day)
                tt = wt.weekly('latlon', latlong)
                speaking.speakvn('Ngày ' + day + tt[day]['overal'] +
                                 ', Nhiệt độ thấp nhất ' +
                                 str(tt[day]['mintemp']) +
                                 ' độ C, Nhiệt độ cao nhất ' +
                                 str(tt[day]['maxtemp']) +
                                 ' độ C,  độ ẩm là ' + str(tt[day]['hum']) +
                                 ' phần trăm, tốc độ gió trung bình ' +
                                 str(tt[day]['wind']) + ' km/h.')
        elif 'NGÀY TỚI' in data.upper():
            string = data
            num = [int(s) for s in string.split() if s.isdigit()]
            if len(num) > 0:
                for i in range(0, num):
                    y = x + datetime.timedelta(i)
                    day = str(y.day)
                    tt = wt.weekly('latlon', latlong)
                    speaking.speak('Ngày ' + day + tt[day]['overal'] +
                                   ' Nhiệt độ thấp nhất ' +
                                   str(tt[day]['mintemp']) + ' độ C ' +
                                   ' Nhiệt độ cao nhất ' +
                                   str(tt[day]['maxtemp']) +
                                   ' độ C,  độ ẩm là ' + str(tt[day]['hum']) +
                                   ' phần trăm, tốc độ gió trung bình ' +
                                   str(tt[day]['wind']) + ' km/h.')
        else:
            tt = wt.current('latlon', latlong)
            speaking.speakvn('Hôm nay ' + tt['overal'] + ', Nhiệt độ là ' +
                             str(tt['temp']) + ' độ C,  độ ẩm là ' +
                             str(tt['hum']) +
                             ' phần trăm, tốc độ gió trung bình ' +
                             str(tt['wind']) + ' km/h.')
    else:
        answer('tôi không hiểu', 'tôi nghe không rõ', ' vui lòng nói lại đi')
Example #12
0
def listen_print_loop(responses):
    """Iterates through server responses and prints them.

    The responses passed is a generator that will block until a response
    is provided by the server.

    Each response may contain multiple results, and each result may contain
    multiple alternatives; for details, see https://goo.gl/tjCPAU.  Here we
    print only the transcription for the top alternative of the top result.

    In this case, responses are provided for interim results as well. If the
    response is an interim one, print a line feed at the end of it, to allow
    the next result to overwrite it, until the response is a final one. For the
    final one, print a newline to preserve the finalized transcription.
    """
    num_chars_printed = 0
    hotword = gih.get_config('hotword')
    for response in responses:
        if not response.results:

            continue

        # The `results` list is consecutive. For streaming, we only care about
        # the first result being considered, since once it's `is_final`, it
        # moves on to considering the next utterance.
        result = response.results[0]
        if not result.alternatives:

            continue

        # Display the transcription of the top alternative.
        transcript = result.alternatives[0].transcript

        # Display interim results, but with a carriage return at the end of the
        # line, so subsequent lines will overwrite them.
        #
        # If the previous result was longer than this one, we need to print
        # some extra spaces to overwrite the previous result
        overwrite_chars = ' ' * (num_chars_printed - len(transcript))

        if not result.is_final:
            sys.stdout.write('[LBMINH NGHE] : ' + transcript +
                             overwrite_chars + '\r')
            sys.stdout.flush()

            num_chars_printed = len(transcript)
            if hotword.upper() in transcript.upper():
                data = 'interruptinterrupt'
                return data
                break

        else:
            print('[LBMINH NGHE] :' + transcript + overwrite_chars)
            data = transcript + overwrite_chars
            if hotword.upper() in transcript.upper():
                data = 'interruptinterrupt'
                return data
                break
            elif ('ĐƯỢC RỒI') in transcript.upper():
                data = 'ĐƯỢC RỒI'
                return data
                break
            return data

            break
            # Exit recognition if any of the transcribed phrases could be
            # one of our keywords.

            num_chars_printed = 0
Example #13
0
import json
import requests
import threading
import gih
import sys
version = gih.get_config('version_above084')


class sensor():
    def __init__(self, entity_id_ex=[], domain='', password=''):
        self.entity_id_ex = entity_id_ex
        self.domain = domain
        self.password = password

    def domain_extract(self):
        rr = 'sensor'
        return rr


class binary_sensor():
    def __init__(self, entity_id_ex=[], domain='', password=''):
        self.entity_id_ex = entity_id_ex
        self.domain = domain
        self.password = password

    def domain_extract(self):
        rr = 'binary_sensor'
        return rr


class climate():
Example #14
0
from helper import *
import gih
import os
import time
from pygame import mixer
seed = gih.get_config('seed')
if seed == 1:
	import pixels
tts_= gih.get_config('tts')
api_fpt = gih.get_config('api_fpt')
voice = gih.get_config('voice')
import wget

def count_chars(text):
	txt = ''
	result = 0
	for char in text:
		if char.isalpha() or char.isdigit():
			result += 1
			txt += char
	return result
def speak(audioString):
	audioString = audioString.replace('-','').replace('_','')
	consequitivedots = re.compile(r'\.{2,}')
	audioString = consequitivedots.sub('.', audioString)
	sentence = sent(audioString)
	l = len(sentence)
#	mixer.init()
	if tts_ == 'google1':
		mixer.init(54000, -16, 1, 4096)
		from io import BytesIO
Example #15
0
def hamthucthi(row0_in_db, data, friendly_name_hass, sta):

    global player
    print('[MAIN] - THỰC THI TÁC VỤ')
    print('---------')
    processss.timlenhtrongdata(data)

    if row0_in_db == "KHỎE KHÔNG":
        answer(
            "tôi khỏe. ",
            "khỏe lắm chủ nhân ",
            "khỏe chứ chủ nhân. ",
        )
#camera - dieu khien xoay
    elif row0_in_db == "CAMERA":
        print('vao camera')
        a = ptz.control('http://192.168.9.121', 'admin', 'Emilybro2013')
        datapreset = data
        datapreset = datapreset.split()
        iiii = 0
        while iiii < len(datapreset):
            if datapreset[iiii].isnumeric() == True:
                preset_number = datapreset[iiii]
                break
            else:
                iiii += 1
        try:
            a.set_preset(preset_number)
        except:
            pass
        if 'LÊN' in data.upper():
            print('vao len')
            a.len()
            time.sleep(2)
            return
        if 'XUỐNG' in data.upper():
            a.xuong()
            time.sleep(2)
            return
        if 'TRÁI' in data.upper():
            a.trai()
            time.sleep(2)
            return
        if 'PHẢI' in data.upper():
            a.phai()
            time.sleep(2)
            return
# Âm lịch
    elif row0_in_db == "ÂM LỊCH":
        check_day = []
        if 'MAI' in data:
            check_day = amlich.ngaymai()
        elif 'MỐT' in data:
            check_day = amlich.ngaymot()
        elif 'QUA' in data:
            check_day = amlich.homqua()
        elif 'NAY' in data:
            check_day = amlich.homnay()
        else:
            check_day = amlich.ngaykhac(data)
        amlich.kiemtra_amlich(check_day[0], check_day[1], check_day[2],
                              check_day[3], check_day[4])

#Hỏi thứ
    elif row0_in_db == "THỨ MẤY":
        check_thu = []
        if 'MAI' in data:
            check_thu = thu.ngaymai()
        elif 'MỐT' in data:
            check_thu = thu.ngaymot()
        elif 'QUA' in data:
            check_thu = thu.homqua()
        elif 'NAY' in data:
            check_thu = thu.homnay()
        else:
            check_thu = thu.ngaykhac(data)

        result_thu = thu.kiemtra_thu(check_thu[0], check_thu[1], check_thu[2],
                                     check_thu[3], check_thu[4])
        speaking.speak(result_thu[0] + " là " + result_thu[1] + result_thu[2] +
                       ' tháng ' + str(result_thu[3]))

# Ngày lễ
    elif row0_in_db == "NGÀY LỄ":
        #		answer('không có chi. ','rất vui vì giúp được chủ nhân ',' đừng bận tâm ')
        ngayle_res = []
        ngayle_res = ngayle.ngayle_check(data)
        speaking.speak(ngayle_res[0] + ' Còn ' + str(ngayle_res[1]) +
                       ' ngày nữa là đến ' + ngayle_res[2] + '. Đó là ngày ' +
                       ngayle_res[3] + ' tháng ' + ngayle_res[4] + ' năm ' +
                       ngayle_res[5])

#Cảm ơn
    elif row0_in_db == "CẢM ƠN":
        answer('không có chi. ', 'rất vui vì giúp được chủ nhân ',
               ' đừng bận tâm ')
#HELP
    elif row0_in_db == "TRỢ GIÚP":
        if 'THỜI TIẾT' in data:
            speaking.speak(
                'Có thể hỏi các câu hỏi bao gồm các từ như, Thời tiết hôm nay, ngày mai'
            )
        elif 'GIỜ' in data:
            speaking.speak('Đặt câu hỏi mấy giờ rồi')
        elif 'NGÀY' in data:
            speaking.speak(
                'Hỏi thứ mấy, ngày nào. Có thể hỏi ngày mai là thứ mấy, ngày 30 tháng 4 là thứ mấy, vv.'
            )
        elif 'ÂM LỊCH' in data:
            speaking.speak('Hỏi âm lịch hôm nay, ngày mai, ngày bất kì')
        elif 'DỊCH' in data:
            speaking.speak(
                'Dịch từ tHoặc dịch cả câu với cấu trức: Dịch câu sau sang tiếng nào đó. Sau đó chờ âm báo rồi đọc câu. Ngôn ngữ hỗ trợ: Việt, chủ nhân, Trung, Nhật, Hàn.'
            )
        elif 'THÔNG TIN' in data:
            speaking.speak(
                'Có thể hỏi thông tin bằng câu với kết thúc là gì hoặc là ai. Ví dụ, Hồ Chí Minh là ai.'
            )
        elif 'LỆNH' in data:
            speaking.speak(
                'Có thể bật, tắt, điều chỉnh nhiệt độ máy lạnh .... bằng các câu lệnh đơn giản như: bật đèn, tắt đèn, ....'
            )
        elif 'NHẠC' in data:
            speaking.speak(
                'Dùng lệnh Phát rồi gọi tên bài hát, playlist muốn nghe. Muốn qua bài thì dùng lệnh Tiếp theo. Dừng với lệnh Dừng nhạc'
            )
        elif 'HẸN GIỜ' in data:
            speaking.speak(
                'Dùng lệnh hẹn giờ cộng thời gian, hủy với lệnh hủy hẹn giờ')
        elif 'NGÀY LỄ' in data:
            speaking.speak(
                'Hỏi còn bao nhiêu ngày nữa là đến ngày lễ. Các ngày lễ có sẵn bao gồm, Tết Tây, Tết ta, 30 tháng 4, trung thu, giỗ tổ, quốc khánh. '
            )
        else:
            speaking.speak(
                'Các lệnh thường dùng, Hỏi giờ, thời tiết, thứ ngày tháng, thông tin, lệnh, phát nhạc, hẹn giờ, dịch từ, dịch câu, âm lịch, ngày lễ. Dùng lệnh trợ giúp kèm theo các lệnh muốn tra cứu để được hướng dẫn chi tiết hơn.'
            )
#Hỏi giờ
    elif row0_in_db == "MẤY GIỜ":
        from time import ctime, strftime
        gio = strftime("%H")
        gio = list(gio)
        phut = strftime("%M")
        phut = list(phut)
        if gio[0] == '1':
            if gio[1] == '0':
                docgio = 'mười giờ '
            else:
                docgio = 'mười ' + gio[1] + ' giờ '
        elif gio[0] == '0':
            docgio = gio[1] + ' giờ '
        elif gio[0] == '2':
            if gio[1] == '0':
                docgio = 'hai mươi giờ '
            elif gio[1] == '1':
                docgio = 'hai mươi mốt giờ '
            else:
                docgio = 'hai mươi ' + gio[1] + ' giờ '

        if phut[0] == '0':
            docphut = phut[1] + ' phút '
        elif phut[0] == '1':
            if phut[1] == '0':
                docphut = ' mười phút '
            else:
                docphut = ' mười ' + phut[1] + ' phút '
        else:
            if phut[1] == '0':
                docphut = phut[0] + ' mươi phút '
            elif phut[1] == '1':
                docphut = phut[0] + ' mươi mốt phút '
            else:
                docphut = phut[0] + ' mươi ' + phut[1] + ' phút '

        speaking.speak("BÂY GIỜ LÀ " + docgio + docphut)
#Tin tức (TTS)
    elif row0_in_db == "TIN TỨC":
        tintuc.tintucmoi()

    elif row0_in_db == "XỔ SỐ":
        print('Kết quả xổ số')
        loto.check(data)
#Truyện cười
    elif row0_in_db == "CƯỜI":
        truyen = fun.truyen()
        speaking.speak(truyen)

#Hỏi ngày
# if row0_in_db=="VỊ TRÍ":
#	 if "CỦA" in data:
#		 locationcua = data.find('CỦA')
#		 data = data[locationcua+4:len(data)]
#		 location = data.strip(" ")
#		 speaking.speak("đây là vị trí của  " + location )
#		 webbrowser.open("https://www.google.nl/maps/place/" + location + "/&amp;")
# elif row0_in_db == 'NHẮC':

    elif row0_in_db == "RADIO":
        try:
            player.stop()
        except:
            pass
        player = radio.phat_radio(data)

    elif row0_in_db == "ĐI NGỦ":
        pass
    elif row0_in_db == "LÀ GÌ":

        def wifi(data):
            data = data[0:len(data) - 6]
            rep = wk.find_info(data)
            rep = rep.find_wiki()
            speaking.speak('Theo wikipedia: ' + rep)

        speaking.speak('để tôi tìm xem nào')
        execute.run_thread(wifi, data)

# Phát video
    elif row0_in_db == "PHÁT":
        global spotipy
        try:
            player.stop()
        except:
            pass
        spotipy = spot.play_current_playlist(
            'j81xwhr6zxkba3a5txkhrbsz0', 'd6881de9093040d8b9c18d669224b559',
            '8f233b0f5037456b9c5e084f3f069efd', 'http://localhost:9999/', data)
        if spotipy[0] == False:
            player = radio.play_nhac(data, friendly_name_hass)

    elif row0_in_db == "TIẾP THEO":
        try:
            player.stop()
        except:
            pass
        player = radio.phat_tiep_theo()
# Google word translate
    elif row0_in_db == "CÓ NGHĨA":
        from googletrans import Translator
        translator = Translator()
        print(data)
        data = data.replace('TỪ ', '')
        data = data.replace('TRONG ', '')
        #		print ('Edit ' + data)
        # To Vietnamese
        if 'VIỆT' in data:
            m = re.search('(.+?) TIẾNG VIỆT', data)
            dataen = m.group(1)
            print(dataen)
            translations = translator.translate(dataen, dest='vi')
            print(translations.text)
            speaking.speak('Từ ')
            speaking.speaken(dataen)
            speaking.speak('trong tiếng việt nghĩa là: ' + translations.text)
#To English
        elif 'TIẾNG chủ nhân' in data:
            m = re.search('(.+?) TIẾNG chủ nhân', data)
            dataen = m.group(1)
            print(dataen)
            translations = translator.translate(dataen, dest='en')
            print(translations.text)
            speaking.speak('Từ ' + dataen + ' trong tiếng chủ nhân nghĩa là: ')
            speaking.speaken(translations.text)
# To Korean
        elif 'TIẾNG HÀN' in data:
            m = re.search('(.+?) TIẾNG HÀN', data)
            dataen = m.group(1)
            print(dataen)
            translations = translator.translate(dataen, dest='ko')
            print(translations.text)
            speaking.speak('Từ ' + dataen + ' trong tiếng Hàn nghĩa là: ')
            speaking.speakko(translations.text)
# To Japanese
        elif 'TIẾNG NHẬT' in data:
            m = re.search('(.+?) TIẾNG NHẬT', data)
            dataen = m.group(1)
            print(dataen)
            translations = translator.translate(dataen, dest='ja')
            print(translations.text)
            speaking.speak('Từ ' + dataen + ' trong tiếng Nhật nghĩa là: ')
            speaking.speakja(translations.text)
# To Chinese
        elif 'TIẾNG TRUNG' in data:
            m = re.search('(.+?) TIẾNG TRUNG', data)
            dataen = m.group(1)
            print(dataen)
            translations = translator.translate(dataen, dest='zh-cn')
            print(translations.text)
            speaking.speak('Từ ' + dataen + ' trong tiếng TRUNG nghĩa là: ')
            speaking.speakzh(translations.text)
# Google sentence translate
    elif row0_in_db == "DỊCH CÂU":
        from googletrans import Translator
        translator = Translator()
        continue_go = 1
        speaking.speak('OK, đọc câu cần dịch đi chủ nhân')
        more_data = processss.re_ask()
        print(more_data)
        #		def gconv (data,more_data):
        #			continue_go = 1
        #			empty = []
        if len(more_data) > 0:
            while True:
                print('Google translate: ' + data)
                print('Data translate: ' + more_data)
                #			   speaking.speak('')
                processss.mixer.music.load('resources/ding.wav')
                processss.mixer.music.play()
                if 'TIẾNG chủ nhân' in data:
                    translations = translator.translate(more_data, dest='en')
                    print(translations.text)
                    speaking.speaken(translations.text)
                    continue_go = 1
                if 'TIẾNG VIỆT' in data:
                    translations = translator.translate(more_data, dest='vi')
                    print(translations.text)
                    speaking.speak(translations.text)
                    continue_go = 1
                if 'TIẾNG HÀN' in data:
                    translations = translator.translate(more_data, dest='ko')
                    print(translations.text)
                    speaking.speakko(translations.text)
                    continue_go = 1
                if 'TIẾNG TRUNG' in data:
                    translations = translator.translate(more_data,
                                                        dest='zh-cn')
                    print(translations.text)
                    speaking.speakzh(translations.text)
                    continue_go = 1
                if 'TIẾNG NHẬT' in data:
                    translations = translator.translate(more_data, dest='ja')
                    print(translations.text)
                    speaking.speakja(translations.text)
                    continue_go = 1
                if 'HỦY' in more_data:
                    speaking.speak('thoát khỏi chế độ dịch')
                    continue_go = 0
                    break

                else:
                    break

#		return more_data, continue_go
# Hẹn giờ
    elif row0_in_db == "HẸN GIỜ":
        onoff.hen_gio(data)
    elif row0_in_db == "HỦY HẸN GIỜ":
        onoff.t1.cancel()
        speaking.speak("đã hủy hẹn giờ ")
    elif row0_in_db == "DỪNG":
        try:
            player.stop()
        except Exception as e:
            print(e)
            pass
        at = spot.spo('drlbminh', 'd6881de9093040d8b9c18d669224b559',
                      '8f233b0f5037456b9c5e084f3f069efd',
                      'http://localhost:9999/')

        sp = at.assign()
        de = sp.devices()
        de = de['devices']

        for des in de:
            print(des['id'])
            try:
                at.pause(sp, des['id'])
            except Exception as t:
                print(t)
                pass
    elif row0_in_db == "TO LÊN":
        radio.to_len()
    elif row0_in_db == "NHỎ XUỐNG":
        radio.nho_xuong()
    elif row0_in_db == "ÂM LƯỢNG":
        vol_extract = radio.amluong(data)
        speaking.speak("thiết lập âm lượng mức " + str(vol_extract))
    elif row0_in_db == "THIẾT LẬP":
        onoff.thietlap(friendly_name_hass, sta, data)
    elif row0_in_db == "MỞ":
        onoff.on_mo(friendly_name_hass, data)
    elif row0_in_db == "TẮT":
        onoff.off_tat(friendly_name_hass, data)
    elif row0_in_db == "TÊN":
        if "tôi" in data:
            answer(
                'tôi là BOT LB',
                'tôi là LB ',
                'tôi tên LB',
            )

    elif row0_in_db == "":
        speaking.speak('tôi không hiểu rồi đại ca ơi')
# Trạng thái
    elif row0_in_db == "TRẠNG THÁI":
        onoff.trangthai(sta)


#Thời tiết
    elif row0_in_db == "THỜI TIẾT":
        import speaking
        import gih
        latlong = gih.get_config('toado')
        import datetime
        from datetime import timedelta
        x = datetime.datetime.now()
        answer('đang kiểm tra thông tin thời tiết', 'để tôi kiểm tra',
               'tôi kiểm tra ngay')
        if 'NGÀY MAI' in data:
            y = x + datetime.timedelta(1)
            day = str(y.day)
            tt = wt.weekly('latlon', latlong)
            speaking.speak('Ngày mai ' + tt[day]['overal'] +
                           ', Nhiệt độ thấp nhất ' + str(tt[day]['mintemp']) +
                           ' độ C, Nhiệt độ cao nhất ' +
                           str(tt[day]['maxtemp']) + ' độ C,  độ ẩm là ' +
                           str(tt[day]['hum']) +
                           ' phần trăm, tốc độ gió trung bình ' +
                           str(tt[day]['wind']) + ' km/h.')
        elif 'HÔM NAY' in data:
            tt = wt.current('latlon', latlong)
            speaking.speak('Hôm nay ' + tt['overal'] + ', Nhiệt độ là ' +
                           str(tt['temp']) + ' độ C,  độ ẩm là ' +
                           str(tt['hum']) +
                           ' phần trăm, tốc độ gió trung bình ' +
                           str(tt['wind']) + ' km/h.')
        elif 'GIỜ TỚI' in data:
            string = data
            num = [int(s) for s in string.split() if s.isdigit()]
            if len(num) > 0:
                from datetime import timedelta
                y = x + timedelta(hours=num[0])
                if y.hour < 25:
                    day = 'today'
                    ngay = ' giờ hôm nay '
                elif y.hour > 24:
                    day = 'tomorrow'
                    ngay = ' giờ ngày mai '
                tt = wt.hourly('latlon', latlong)
                speaking.speak('Thời tiết lúc ' + str(y.hour) + ngay +
                               tt[day]["%.1f" % y.hour]['overal'] +
                               ', Nhiệt độ là ' +
                               str(tt[day]["%.1f" % y.hour]['temp']) +
                               ' độ C,  độ ẩm là ' +
                               str(tt[day]["%.1f" % y.hour]['hum']) +
                               ' phần trăm, tốc độ gió trung bình ' +
                               str(tt[day]["%.1f" % y.hour]['wind']) +
                               ' km/h.')
            else:
                pass
        elif 'TUẦN' in data.upper():
            for i in range(1, 3):
                y = x + datetime.timedelta(i)
                day = str(y.day)
                tt = wt.weekly('latlon', latlong)
                speaking.speak('Ngày ' + day + tt[day]['overal'] +
                               ', Nhiệt độ thấp nhất ' +
                               str(tt[day]['mintemp']) +
                               ' độ C, Nhiệt độ cao nhất ' +
                               str(tt[day]['maxtemp']) + ' độ C,  độ ẩm là ' +
                               str(tt[day]['hum']) +
                               ' phần trăm, tốc độ gió trung bình ' +
                               str(tt[day]['wind']) + ' km/h.')
        elif 'NGÀY TỚI' in data.upper():
            string = data
            num = [int(s) for s in string.split() if s.isdigit()]
            if len(num) > 0:
                for i in range(0, num):
                    y = x + datetime.timedelta(i)
                    day = str(y.day)
                    tt = wt.weekly('latlon', latlong)
                    speaking.speak('Ngày ' + day + tt[day]['overal'] +
                                   ' Nhiệt độ thấp nhất ' +
                                   str(tt[day]['mintemp']) + ' độ C ' +
                                   ' Nhiệt độ cao nhất ' +
                                   str(tt[day]['maxtemp']) +
                                   ' độ C,  độ ẩm là ' + str(tt[day]['hum']) +
                                   ' phần trăm, tốc độ gió trung bình ' +
                                   str(tt[day]['wind']) + ' km/h.')
        else:
            tt = wt.current('latlon', latlong)
            speaking.speak(
                'Xin lỗi, tôi không nghe bạn hỏi thời tiết ngày nào')
    else:
        answer('tôi không hiểu', 'tôi nghe không rõ', ' vui lòng nói lại đi')
Example #16
0
def speak(audioString):
    audioString = audioString.replace('-', ' ').replace('_', ' ')
    consequitivedots = re.compile(r'\.{2,}')
    audioString = consequitivedots.sub('.', audioString)
    sentence = sent(audioString)
    l = len(sentence)
    #	mixer.init()
    if tts_ == 'google1':
        mixer.init(54000, -16, 1, 4096)
        from io import BytesIO
        print('[MAIN] - NÓI')
        print('')
        print('TTS: Google')
        for i in range(0, l):
            text = str(sentence[i])
            # text = text[:]
            print(text)
            count = count_chars(text)
            print(count)
            if count > 0:
                print('Nội dung: ' + text)
                #Kiểm tra tồn tại file
                import os.path
                from os import path
                while True:
                    me = path.exists('tmp/google/' + text[:150] + '.mp3')
                    if me == False:
                        tts = gTTS(text, lang='vi')
                        tts.save('tmp/google/' + text[:150] + '.mp3')
                        time_sleep = 1
                        time_wait = 20
                        tcount = 0
                        while (me == False and tcount < time_wait):
                            time.sleep(time_sleep)
                            tts.save('tmp/google/' + text[:150] + '.mp3')
                            tcount += 1
                    else:
                        if seed == 1:
                            pixels.pixels.speak()
                        audio = MP3('tmp/google/' + text[:150] + '.mp3')
                        t = float(audio.info.length)
                        mixer.music.load('tmp/google/' + text[:150] + '.mp3')
                        mixer.music.play()
                        time.sleep(t)
                        break
#FPT
    elif tts_ == 'fpt':
        import random, requests
        for i in range(0, l):
            text = str(sentence[i])
            if len(text.strip()) < 1 or text.strip() == '.':
                pass
            else:
                print('Nội dung: ' + text)
                import os.path
                from os import path
                while True:
                    me = path.exists('tmp/fpt/' + text[:150] + '.mp3')
                    if me == False:
                        api_fpt_key = random.choice(api_fpt)
                        url = 'https://api.fpt.ai/hmi/tts/v5'
                        headers = {
                            'api_key': api_fpt_key,
                            'speed': '0',
                            'prosody': '1',
                            'voice': voice
                        }
                        payload = text.encode('utf-8')
                        url_return = requests.post(
                            url, data=payload, headers=headers).json()['async']
                        res_response = requests.get(url_return)
                        res_status = res_response.status_code
                        #						print (url_return)
                        time_sleep = 0.5
                        time_wait = 20
                        tcount = 0
                        while (res_status == 404 and tcount < time_wait):
                            time.sleep(time_sleep)
                            res_response = requests.get(url_return)
                            res_status = res_response.status_code
                            tcount += 1
                        if tcount == time_wait:
                            print('error tts')
                        with open('tmp/fpt/' + text[:150] + '.mp3', 'wb') as f:
                            f.write(res_response.content)
                            f.close()
                    else:
                        mixer.music.load('tmp/fpt/' + text[:150] + '.mp3')
                        mixer.music.play()
                        audio = MP3('tmp/fpt/' + text[:150] + '.mp3')
                        t = float(audio.info.length)
                        print('Time delay :' + str(t))
                        time.sleep(t)
                        break
#TTS VIETTEL
    elif tts_ == 'viettel':
        token = gih.get_config('token')
        import json, requests, os.path
        from playsound import playsound
        from pathlib import Path
        from pygame import mixer
        url = "https://vtcc.ai/voice/api/tts/v1/rest/syn"
        for i in range(0, l):
            text = str(sentence[i])
            if len(text.strip()) < 1 or text.strip() == '.':
                pass
            else:
                print('Nội dung: ' + text)
                import os.path
                from os import path
                while True:
                    from pydub import AudioSegment
                    from pydub.playback import play
                    me = path.exists('tmp/vtcc/' + text[:150] + '.wav')
                    if me == False:
                        data = {
                            "text": text,
                            "voice": "hn-quynhanh",
                            "id": "2",
                            "without_filter": False,
                            "speed": 1.0,
                            "tts_return_option": 2
                        }
                        headers = {
                            'Content-type': 'application/json',
                            'token': token
                        }
                        s = requests.Session()
                        dirname = os.path.dirname(os.path.abspath('_file_'))
                        cert_path = (dirname + '/wwwvtccai.crt')
                        response = requests.post(url,
                                                 data=json.dumps(data),
                                                 headers=headers,
                                                 verify=cert_path)
                        print(response.headers)
                        print(response.status_code)
                        res_status = response.status_code
                        time_sleep = 0.5
                        time_wait = 20
                        tcount = 0
                        while (res_status != 200 and tcount < time_wait):
                            time.sleep(time_sleep)
                            response = requests.post(url,
                                                     data=json.dumps(data),
                                                     headers=headers,
                                                     verify=cert_path)
                            res_status = res_response.status_code
                            tcount += 1
                        if tcount == time_wait:
                            print('error tts')
                        data = response.content
                        with open('tmp/vtcc/' + text[:150] + '.wav',
                                  "wb") as f:
                            f.write(data)
                            f.close()
                    else:
                        if seed == 1:
                            pixels.pixels.speak()
                        sound = AudioSegment.from_wav('tmp/vtcc/' +
                                                      text[:150] + '.wav')
                        play(sound)
                        break
# TTS Google1
    elif tts_ == 'google':
        from pygame import mixer
        mixer.init(54000, -16, 1, 4096)
        from io import BytesIO
        print('[MAIN] - NÓI')
        print('')
        print('TTS: Google')
        for i in range(0, l):
            text = str(sentence[i])
            # text = text[:]
            print(text)
            count = count_chars(text)
            print(count)
            if count > 0:
                print('Nội dung: ' + text)
                tts = gTTS(text, lang='vi')
                mp3_fp = BytesIO()
                tts.write_to_fp(mp3_fp)
                t = mp3_fp.truncate() / 5400
                t = float(t)
                mp3_fp.seek(0)
                mixer.init()
                if seed == 1:
                    pixels.pixels.speak()
                mixer.music.load(mp3_fp)
                mixer.music.play()
                mp3_fp.flush()
                mp3_fp.seek(0)
                time.sleep(t)
            else:
                pass