async def get_audio_from_speech(speech, query_table, query_col): conn = Connection() query = Query(conn) if speech: transcription = speech.split(' ') for idx, word in enumerate(transcription): # Not enough words to sentence if len(transcription) - idx < 3: break sentence = word + ' ' + transcription[ idx + 1] + ' ' + transcription[idx + 2] query_result = query.query_all(table=query_table, column=query_col, where_col='validation', value=sentence) if query_result: conn.close() return randomize_query_result(query_result) conn.close() # Nothing found in database or speech not recognized return False
def get_posts(post_id=None): if post_id is None: procedure_name = "get_all_posts()" else: procedure_name = "get_post({0})".format(post_id) conn = None posts = [] try: conn = Connection().get_connection() with conn.cursor() as cursor: sql = "call " + procedure_name cursor.execute(sql) for row in cursor.fetchall(): posts.append(Post().dictionary_mapper(row)) except Error as e: print("There was a database error.") for arg in e.args: print(arg) finally: conn.close() return posts
async def get_audio_from_tag(query_table, query_col, tag): conn = Connection() query = Query(conn) query_result = query.query_all(table=query_table, column=query_col, where_col='tag', value=tag) if query_result: conn.close() return randomize_query_result(query_result) conn.close() return False
class DatabaseAdapter: def __init__( self, *args, **kwargs, ): super().__init__(*args, **kwargs) self.conn = Connection() self.query = Query(self.conn) self.persistence = Persistence(self.conn) def select_all(self, table, *columns): return self.query.select_all(table, columns) def select_all_joined(self, from_table, join_table, on, columns, how='INNER'): return self.query.select_all_joined(from_table, join_table, on, columns, how) def select_custom_sql(self, which_query, where_value=False, replace_pattern='%value%'): return self.query.select_custom_sql(which_query, where_value, replace_pattern) def close(self): return self.conn.close()
def edit_post(post_id, title, content): conn = None result = False try: conn = Connection().get_connection() with conn.cursor() as cursor: sql = "call edit_post({0}, '{1}', '{2}')".format(post_id, title, content) cursor.execute(sql) conn.commit() result = True except Error as e: print("There was a database error.") for arg in e.args: print(arg) conn.rollback() finally: conn.close() return result
def run(configuration_hash: str, configuration_key: str, module: str, module_namespace: str): with open(Path.var_folder_path() + '/' + configuration_hash + '.pickle', 'rb') as handle: configuration = pickle.load(handle) if type(configuration) is not Configuration: raise ExitError('Could not unserialize configuration') custommodule = importlib.import_module('.' + module, package=module_namespace) connection = Connection(configuration) for customattribute in dir(custommodule): if customattribute == tocamelcase.convert(module): customclass = getattr(custommodule, customattribute) customclass(configuration, configuration_key, connection).run() connection.close()
def add_post(title, content): conn = None result = False try: conn = Connection().get_connection() with conn.cursor() as cursor: sql = "call add_post('{0}', '{1}')".format(title, content) cursor.execute(sql) conn.commit() result = True except Error as e: print("There was a database error.") for arg in e.args: print(arg) conn.rollback() finally: conn.close() return result
class SplitWords(BaseCommand): def __init__(self): super().__init__() self.db = None self.stopped = False self.cached_words: Dict[str, int] = {} self.cached_sentences: Dict[str, int] = {} def connect(self) -> None: """Connects to database and rabbitmq (optionally)""" self.db = Connection() def signal_handler(self, signal, frame) -> None: self.logger.info("received signal, exiting...") self.stopped = True def add_options(self, parser) -> None: super().add_options(parser) def run(self, args: list, opts: list) -> None: self.set_logger("SPLIT_WORDS", self.settings.get("LOG_LEVEL")) configure_logging() self.connect() signal.signal(signal.SIGINT, self.signal_handler) signal.signal(signal.SIGTERM, self.signal_handler) # your code here for filename in args: filename = filename.replace("\\", "/") if path.exists(filename): self.db.insert({"title": filename}, Files) time.sleep(1) file_id = self.get_id(filename, Files) self.logger.info(file_id) with open(filename, "r") as opened_file: for sentence_count, sentence in enumerate(opened_file): sentence = sentence.replace('"', "'") sentence = sentence.replace("'", '"') # add sentence if sentence not in self.cached_sentences: self.db.insert({"title": sentence}, Sentences) sentence_id = self.get_id(sentence, Sentences) self.cached_sentences[sentence] = sentence_id else: sentence_id = self.cached_sentences[sentence] # add link to file item = { "sentence_id": sentence_id, "file_id": file_id, "position": sentence_count, } self.db.insert(item, SentencesInFiles) # create same structure for each sentence for word_count, word in enumerate(sentence.split(" ")): if word not in self.cached_words: self.db.insert({"title": word}, Words) word_id = self.get_id(word, Words) self.cached_words[word] = word_id else: word_id = self.cached_words[word] temp = { "sentence_id": sentence_id, "word_id": word_id, "position": word_count, } self.db.insert(temp, WordsInSentences) self.db.close() def get_id(self, title: str, model: Base) -> int: q = """ SELECT id from {model_table} where title='{title}' limit 1 """ for r in self.db.session.execute( q.format(title=title, model_table=model.__tablename__)): return r[0] return 0