def testing(q, t=False, e=False): if t: solved = input("Solved? ") if not solved: solved = "true" else: solved = "false" sqlite.execute( f"INSERT INTO HISTORY VALUES('{q}', '{solved}')", databPath=r"data/database/history.db", ) elif e: sqlite.execute( f"INSERT INTO HISTORY VALUES('{q}', 'false')", databPath=r"data/database/history.db", ) print( sqlite.execute( "SELECT * FROM HISTORY WHERE solved='false'", databPath=r"data/database/history.db", )[0] ) return True
def index(request, productId): sqlite.connect( "database/data/products.sqlite3", raiseError=False, ) paytmParams = { "MID": "WorldP64425807474247", "ORDER_ID": hashlib.sha1( str(productId).encode("utf-8") + str(time.time()).encode("utf-8")).hexdigest()[-15:], "TXN_AMOUNT": str( sqlite.execute( f'SELECT price FROM PRODUCT WHERE id="{productId}"', "database/data/products.sqlite3", )[0][0][0]), "CUST_ID": "*****@*****.**", "INDUSTRY_TYPE_ID": "Retail", "WEBSITE": "WEBSTAGING", "CHANNEL_ID": "WEB", "CALLBACK_URL": "http://127.0.0.1:8000/payment/pay/", } print(paytmParams["ORDER_ID"]) paytmParams["CHECKSUMHASH"] = checksum.generate_checksum( paytmParams, "kbzk1DSbJiV_O3p5") # sqlite.execute(f'SELECT price FROM PRODUCT WHERE id="{productId}"')[0][0][0] return render(request, "payment/index.html", paytmParams)
def youtube(self, query, openLink=True, rand=False): host, searchMethod, playMethod = sqlite.execute( databPath=dbServices, command= f"SELECT host, searchMethod, playMethod FROM VIDEO_SERVICES WHERE name='YouTube'", )[0][0] link = f"{host}{searchMethod}{query}" res = requests.get(f"{host}{searchMethod}{query}").text soup = bs4.BeautifulSoup(res, "lxml") links = [] for link in soup.find_all("a", href=True): links.append(link["href"]) vids = [] for link in links: if playMethod in link: vids.append(link) if not rand: break try: if rand: link = f"{host}{random.choice(vids)}" else: link = f"{host}{vids[0]}" if openLink: webbrowser.open_new_tab(link) return link except Exception: pass
def getSearchMethod(self, engine=""): """ Returns the search method of the specified search engine from the database. """ # Get methods from sql database and map them to dicts. try: return sqlite.execute( databPath=dbServices, command= f"SELECT METHOD FROM ENGINES WHERE NAME='{engine.capitalize()}'", matrix=False, )[0][0][0] except Exception: return sqlite.execute( databPath=dbServices, command=f"SELECT METHOD FROM ENGINES WHERE NAME='Google'", matrix=False, )[0][0][0]
def checkQuestion(self, query=""): """ Checks whether the provided query is a question or not. """ __temp = False qWords = (sqlite.execute(databPath=dbAttributes, command="SELECT * FROM KEYWORDS;", matrix=False)[0][0][1].replace( "(", "", 1).replace(")", "", 1).split(", ")) for word in qWords: if Tools().reOperation(query.upper(), word, "at start"): __temp = True self.quesType = word break self.quesType = self.quesType.lower() __temp = ( False # TODO Remove this line for searching questions related to assistant ) return __temp
def gaana(self, query, openLink=True): host, searchMethod = sqlite.execute( databPath=dbServices, command= f"SELECT host, searchMethod FROM MUSIC_SERVICES WHERE RANK=1", )[0][0] res = requests.get(f"{host}{searchMethod}{query}").text try: link = res[res.index('<h3 class="item-heading"><a href="') + len('<h3 class="item-heading"><a href="' ):res.index(' class="rt_arw " ') - 1] except Exception: try: res.index(" No results found for “") raise QueryError except Exception: raise QueryError if openLink: webbrowser.open_new_tab(link) return link
def getUsers(self): return sqlite.execute("SELECT * FROM USER")[0]
def fetchDatabase(kind="Product"): sqlite.constants.__databPath__ = [] sqlite.connect("database/data/products.sqlite3") return sqlite.execute(f"SELECT * FROM {kind.upper()}")
from sql_tools import sqlite # sqlite.connect(r"data/database/services.db") # sqlite.connect(r"data/database/history.db") sqlite.connect(r"data/database/programInstallData.db") # result = sqlite.getTableNames() # result = sqlite.execute("SELECT * FROM engines") # result = sqlite.getColumnNames("MUSIC_SERVICES") # result = sqlite.execute("SELECT * FROM MUSIC_SERVICES") # result = sqlite.execute("UPDATE MUSIC_SERVICES SET scrapMethod='requests' WHERE rank=1") # result = sqlite.execute("SELECT * FROM MUSIC_SERVICES") # result = sqlite.execute("INSERT INTO MUSIC_SERVICES VALUES ('YouTube music', 'https://music.youtube.com', '/search?q=', '/watch?v=', '3', 'bs4', 'RUN')") # result = sqlite.getColumnNames("engines") # result = sqlite.execute("SELECT * FROM PROGRAMS_DATA_WIN32") result = sqlite.execute("SELECT * FROM history") # result = sqlite.execute("SELECT * FROM history WHERE solved='false'") # result = sqlite.getNoOfRecords(["history", "history"]) print(result)
from tools_lib import bprint databases = [ "services.db", "attributes.db", "programInstallData.db", # "history.db" ] query = [ "services.sql", "attributes.sql", "programInstallData.sql", # "history.sql" ] for i in range(len(databases)): sqlite.connect(fr"data/database/{databases[i]}") with open(f"data/query/{query[i]}") as f: read = f.readlines() for command in read: sqlite.execute(command) bprint(f"Done for {databases[i]}", bg="red") sqlite.disconnect(fr"data/database/{databases[i]}") print() bprint("---> Databases updated successfully ✅ <---", bg="red")
def playClassify(query): """ Classifies the query containing "play" keyword. """ wordList = query.split(" ") service = None query = " ".join(wordList) try: query = query.replace("youtube music", "youtubeMusic") except Exception: pass wordList = query.split(" ") for i in [" on", " in", " at", " with"]: if Tools().reOperation(" ".join(wordList[:len(wordList) - 1]), i, "at end"): service = wordList[-1] query = query.replace(i, "", -1).replace(service, "", -1) break services = { # Video services "youtube": apiVideo().youtube, # Music services "gaana": apiMusic().gaana, "spotify": apiMusic().spotify, "youtubeMusic": apiMusic().youtubeMusic, } # Redirecting to service if Web().checkConnection(): try: services[service](query) except QueryError: if service is not None: syn.speak( f"No result found for your query so I am opening it on YouTube" ) services["youtube"](query, openLink=True) syn.speak(random.choice(greetKeywords)) except Exception: if service is not None: syn.speak( f"{service} is not supported yet so I am opening it on YouTube" ) services["youtube"](query, openLink=True) syn.speak(random.choice(greetKeywords)) else: videoDir, musicDir = sqlite.execute( "SELECT value FROM USER_ATTRIBUTES WHERE name IN ('musicDirectory', 'videoDirectory')", databPath=dbAttributes, splitByColumns=True, )[0][0] videoFiles = os.listdir(videoDir) musicFiles = os.listdir(musicDir) # TODO SEARCH HERE FOR MORE RELEVANT RESULTS os.startfile(os.path.join(videoDir, random.choice(videoFiles)))
def openClassify(self, query): """ Classifies the query containing "open" keyword. """ if self.platform == "windows": # Try whether the application is present on machine or not. try: query = query.lower().strip().capitalize() # Getting the location of the program ls = ( "name", "shortName1", "shortName2", "shortName3", "shortName4", "shortName5", "shortName6", "shortName7", "shortName8", "shortName9", ) opened = False for count, i in enumerate(ls): try: ( applicationName, location, locationMethod, openMethod, ) = sqlite.execute( databPath=dbProgramInstallData, command= f'SELECT fileName, location, locationMethod, openMethod FROM PROGRAMS_DATA_WIN32 WHERE {i}="{query}"', raiseError=False, matrix=False, )[0][0] if (not applicationName or not location or not locationMethod or not openMethod): continue if locationMethod == "user": # Application is dependent of user home path if openMethod == "exe": # Application is executable os.startfile( f"{Tools().getUserPath}\\{location}\\{applicationName}" ) syn.speak(random.choice(greetKeywords)) else: # Application will open with system command os.system(applicationName) else: # Application is independent of user home path if openMethod == "exe": # Application is executable os.startfile(f"{location}\\{applicationName}") syn.speak(random.choice(greetKeywords)) else: # Application will open with system command os.system(applicationName) opened = True break except Exception: if count == len(ls) - 1: if (str( e ) != "index 0 is out of bounds for axis 0 with size 0" ): raise FileNotFoundError( "Application doesn't exists") if not opened: raise FileNotFoundError # Checking for webpage except Exception: if Tools().reOperation(query, "Webpage", "at start"): if Web(query).checkConnection(): if Web(query).checkWebExists(): print("Open webpage") else: print("Webpage does not exists") else: query = (query.replace("go to", "", 1).replace( "https://", "", 1).replace("http://", "", 1).replace(" ", "")) domain = Web().findDomain(query) for i in webDomains: query = query.replace(i, "") if domain: webbrowser.open_new_tab(f"https://{query}{domain}") else: syn.speak("You don't have internet connection") elif self.platform == "linux": query = query.lower().strip().capitalize() ls = ( "name", "shortName1", "shortName2", "shortName3", "shortName4", "shortName5", ) data = None for i in ls: result = sqlite.execute( f"SELECT command FROM PROGRAMS_DATA_LINUX WHERE {i}='{query.capitalize()}'", databPath="data/database/programInstallData.db", raiseError=False, matrix=True, ) if result: data = result del result break if data: command = data[0][0][0] os.system(command) else: syn.speak( "The program you have demanded is not found on your device" ) else: syn.speak( "The operating system is not supported for such type of operations" )
def classify(self, webDomains=webDomains): """ Classifies the string provided to different categories. """ query = self.query # Open program if Tools().reOperation(query, "open", "at start"): self.openClassify(query.replace("open ", "", 1)) # Play content elif Tools().reOperation(query, "play", "at start"): self.playClassify(query.replace("play ", "")) # Search content elif Tools().reOperation(query, "search", "at start"): var = Search() var.classify(query) # Open web elif Tools().reOperation(query, "go to", "at start"): query = (query.replace("go to", "", 1).replace("https://", "", 1).replace("http://", "", 1).replace(" ", "")) domain = Web().findDomain(query) if domain != "err_no_connection": if domain != "Webpage does not exists": webbrowser.open_new_tab("https://" + query + domain) else: syn.speak("You don't have internet connection") # Other search for questions on Google elif query.split(" ")[0].upper() in Tools.strTolst( sqlite.execute(databPath=dbAttributes, command="SELECT * FROM KEYWORDS;", matrix=False)[0][0][1]): # SCRAP GOOGLE TO GET RESULTS result = Question().checkQuestion(query) syn.speak(result) if result else syn.speak( search.Web().google(query)) # Game elif "game" in query: games.init() # Exiting elif query == "exit": terminate() # Terminating tracking session syn.speak("See you again.") quit(1) # Testing query elif "test" in query: query = query.replace("test", "", 1).lower().strip() self.playClassify(query.replace("open", "", 1)) else: # Not understood syn.speak( "I am not able to understand your query at the moment. Please try after future updates." )
def classify(self, query=""): """ Classfies the type of search query provided. """ engines = sqlite.execute( "SELECT name FROM ENGINES", databPath=dbServices, matrix=False, inlineData=True, splitByColumns=True, )[0][0] query = query.lower().replace("search", "", 1).strip() wordList = query.split(" ") engine = None for i in range(len(wordList)): try: if wordList[0] in ["for", "at", "on"]: wordList.pop(0) except Exception: pass for __engine in engines: if (wordList[0].capitalize() == __engine ): # Check if the search engine is at the start of the query. queryType = "Search" for __engine in engines: if ( wordList[-1].capitalize() == __engine ): # Checking if there is more than one engines present in the query, at start & at end. if wordList[-2] in [ "on", "at", ]: # Check if it contains the keywords that signifies that the word is the engine. engine = wordList[-1].capitalize() break else: engine = wordList[0].capitalize( ) # The search engine is at the start break else: engine = wordList[0].capitalize( ) # The search engine is at the start elif ( wordList[-1].capitalize() == __engine ): # Checking if the searching engine is not at start but at the last. for __engine in engines: if wordList[-2] in [ "on", "at", ]: # Check if it contains the keywords that signifies that the word is the engine. engine = wordList[-1].capitalize() break else: engine = (wordList[0].capitalize() if engine in engines else "Google" ) # The search engine is at the start if engine in engines: break queryType = "search" break else: queryType = "not_search" if queryType == "Search": try: wordList.remove(engine.lower()) except Exception: pass if wordList[0] in ["for", "at", "on"]: wordList.pop(0) if wordList[-1] in ["for", "at", "on"]: wordList.pop(-1) searchQuery = " ".join(wordList) if engine != None: self.searchEngine(query=searchQuery, engine=engine) else: syn.speak("I am unable to understand the query.")
from sql_tools import sqlite sqlite.connect("sample.db") sqlite.execute("CREATE TABLE TEST1 (C1 TEXT);") sqlite.execute("CREATE TABLE TEST2 (C2 TEXT);") sqlite.execute("CREATE TABLE TEST3 (C3 TEXT);") sqlite.execute("CREATE TABLE TEST4 (C4 TEXT);")