From e7a2be67ffd834f2406102ceffaffd87e7e9e81b Mon Sep 17 00:00:00 2001 From: dmitrium12 Date: Thu, 27 Apr 2023 16:27:23 +0700 Subject: [PATCH] =?UTF-8?q?=D0=B1=D1=8D=D1=82=D0=B0=20=D1=81=D0=B0=D0=B9?= =?UTF-8?q?=D1=82=D0=B0,=20=D1=83=D0=B1=D1=80=D0=B0=D0=BB=20=D0=BC=D1=83?= =?UTF-8?q?=D1=81=D0=BE=D1=80,=20=D1=87=D1=83=D1=82=D1=8C-=D1=87=D1=83?= =?UTF-8?q?=D1=82=D1=8C=20=D0=B4=D0=BE=D0=BF=D0=B8=D0=BB=D0=B8=D0=BB=20?= =?UTF-8?q?=D0=BA=D0=BE=D0=B4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .gitignore | 4 +- Bot.py | 2 +- db.sql | Bin 65536 -> 65536 bytes functions/loging.py | 12 +- resource_ru_not_translate.txt | 3 - response_ru.txt | 3 - static/audio-player/css/player.css | 20 +++ static/audio-player/js/player.js | 64 ++++++++ static/templates/index.html | 16 ++ static/templates/log.html | 39 +++++ static/templates/logs.html | 31 ++++ test.py | 241 +++++++---------------------- 12 files changed, 237 insertions(+), 198 deletions(-) delete mode 100644 resource_ru_not_translate.txt delete mode 100644 response_ru.txt create mode 100644 static/audio-player/css/player.css create mode 100644 static/audio-player/js/player.js create mode 100644 static/templates/index.html create mode 100644 static/templates/log.html create mode 100644 static/templates/logs.html diff --git a/.gitignore b/.gitignore index 091dfa8..cd9a238 100644 --- a/.gitignore +++ b/.gitignore @@ -29,7 +29,7 @@ share/python-wheels/ *.egg MANIFEST .idea/ -logs/ +static/logs/ config # PyInstaller # Usually these files are written by a python script from a template @@ -132,4 +132,4 @@ dmypy.json # Pyre type checker .pyre/ -/logs/ +/static/logs/ diff --git a/Bot.py b/Bot.py index cba61cc..7c9d0f7 100755 --- a/Bot.py +++ b/Bot.py @@ -7,7 +7,7 @@ import json bot = Bot(token="5941118321:AAG0g0keLrlnuH_9U9X6ehpFFAdOX38qeXI") # создаю объект бота dp = Dispatcher(bot) # создаю объект слушателя logger.remove() # удаляю стандартный логер -logger.add("logs/logging_log.log", level="INFO") # создаю логер +logger.add("static/logs/logging_log.log", level="INFO") # создаю логер @dp.message_handler(commands=['start']) # обрабатываю команду start diff --git a/db.sql b/db.sql index 796d2299742c9f2880d83206e708625055e8b711..115b6e0eb90d34f05a305a757958a2e27a378009 100644 GIT binary patch delta 159 zcmZo@U}|AjrnW00eOECWHU{!mPYNAy&R8 z4E*Q#7x26Di|{?!EU0ja&p?lrgMo!bQdCh<zSIlmFDCq1eYWx pXCqjXMf^YTvGM~A`osT?{{#Okey~COY^=m_UXO$uGfpl$mC}o!y>WSS^S#Y0m*2k)}J>X;R;>Xw= z@~I=+p;d8VH*}(}bFk_{j)Nn<4&!zh#D>hfaAe*_yi{Y8JzsHXprxRnS8j>B<+Ud9*ZK+#z5-o#uNWK*Bz5 z`$h7x8Agtz`-U0muRFd2!2z}`Lmabx91fi&+K-LBt~l&mf>7z# z2}9Uf+*T6;WFt{%^90Qan4Q?PAoo(8Xw2&ffz2w
kQ zn&!M0o0aQtt*w-v{r1%lH{bn$?;-&ignjBkB?MH@QcZS@$gzQOm0y?)A=ti^s^vlM zw!%s178M1q|3v3YF5JO{XiS1Co(fC8i3pY}tFk{fUSnV6qW*L2vRbeSJt-fEs?<$9 zytYU%(MkIGPS1(hrw(D2L}=_I-;^Z=hk$el&zc5P5rnUSOJP>w9T=9t%(KayMKLI8 zmwZfUi#pqI$3M7Vt2bS^iS3c1zhv*6l#B@k(GFc~6r7bDdY)AXWYSh02a*GMZ z27AJ421Pc3{8UjAXvf0Yc8O!)@-?oJzXkD-UMVhdtgYG^eD&x#EwzhoE&C;Y6R#?t z1j|Zd?*hou+@d&?4jGV()Ta4i?NAILS~6D4K;+gB@#A3>eyD<)g+4+$&5s(TI^q*X z_yG*83NWKaJwga}(|4(urKK}0Fw46lWUI>4Zk^^G8`Y@u%5jQJRY~)ov;Rt% zLJ-86h6iCwN7f|Aw8vZ#iTEO^-0Ca$gERujX>x3F-1_OHm#I@KJ&LdkJT+MQ<}G!K z`L+lGU;;cUhxn9&WAsg1)5xnb#^u<6KtHk{;8gC^fOPTEZbpS>ffayzhU6?%YlPiS zD9DJRZ7_>bbOlw*R;>@H)o2Ep^3>Hj!RKlpip`cWs7YAp@a(lnLjiuLsbAc57S5f; zMK_;^p@IGojEF%y1b{nupI%TXP0>S;9?%qXdSe0_r-5qWIyQSHIeQ&6D=$s?;4QGn zT(_*l9>R2KWu#UipLYLBZAjDjr&Nt}nbM_2SG@%OBq7%3XE;jp*4%Vq{C}@nlos|E z*YVV^nPez@?!xs7IYEFVlSkjUo+_0}=duT-?9c2$_rf#3XXjUzmzMai1OKkAbzc5E xyHI|bJ>_h*l>MCD&0fz|*;mePtiE~gd^tNQWq)OVWcRWYR)5L5CvQJ@_aA1!Mv(vj diff --git a/functions/loging.py b/functions/loging.py index e415d20..29aadce 100644 --- a/functions/loging.py +++ b/functions/loging.py @@ -15,15 +15,17 @@ def loging(message: types.Message, service: str, file_path: str, text: str, f: f :param f: float - длинна аудиофайла :return: None """ - if not os.path.isdir(f"logs/{message.chat.id}"): # если папки нет - os.makedirs(f"logs/{message.chat.id}") # создаю папку + if not os.path.isdir(f"static/logs/{message.chat.id}"): # если папки нет + os.makedirs(f"static/logs/{message.chat.id}") # создаю папку file_name = file_path.split("/")[-1].split(".") # достаю имя файла try: # защита - os.makedirs(f"logs/{message.chat.id}/{file_name[0]}") # создание папки + os.makedirs(f"static/logs/{message.chat.id}/{file_name[0]}") # создание папки except FileExistsError: pass - shutil.copy(file_path, f"logs/{message.chat.id}/{file_name[0]}/audio.{file_name[1]}") # копирование файла - with open(f'logs/{message.chat.id}/{file_name[0]}/{service}-text.txt', 'w+') as the_file: # открываю файл в запись + shutil.copy(file_path, f"static/logs/{message.chat.id}/{file_name[0]}/audio.{file_name[1]}") + # копирование файла + with open(f'static/logs/{message.chat.id}/{file_name[0]}/{service}-text.txt', 'w+') as the_file: + # открываю файл в запись the_file.write(text) # записываю user_id = message.from_user.id group_id = message.chat.id diff --git a/resource_ru_not_translate.txt b/resource_ru_not_translate.txt deleted file mode 100644 index 7484c95..0000000 --- a/resource_ru_not_translate.txt +++ /dev/null @@ -1,3 +0,0 @@ - - -Привет! \ No newline at end of file diff --git a/response_ru.txt b/response_ru.txt deleted file mode 100644 index 4c78461..0000000 --- a/response_ru.txt +++ /dev/null @@ -1,3 +0,0 @@ -, ты тот, кто сказал, что я должен идти - -Да, я говорил это! Я думаю, что было бы здорово, если бы ты вышел и исследовал мир. Это откроет ваш разум и даст вам новые впечатления. \ No newline at end of file diff --git a/static/audio-player/css/player.css b/static/audio-player/css/player.css new file mode 100644 index 0000000..f440d3c --- /dev/null +++ b/static/audio-player/css/player.css @@ -0,0 +1,20 @@ +.player-container { + width: 100%; + height: 50px; + background-color: #d54242; + display: flex; + align-items: center; + justify-content: center; +} + +#audio-player { + width: 80%; +} + +#audio-controls { + display: flex; +} + +#audio-controls button { + margin-right: 10px; +} \ No newline at end of file diff --git a/static/audio-player/js/player.js b/static/audio-player/js/player.js new file mode 100644 index 0000000..e478094 --- /dev/null +++ b/static/audio-player/js/player.js @@ -0,0 +1,64 @@ +class AudioPlayer { + constructor(options) { + this.container = options.container; + this.audioFile = options.audioFile; + this.audio = new Audio(this.audioFile); + this.isPlaying = false; + + this.playButton = null; + this.pauseButton = null; + + this.render(); + } + + render() { + const containerElement = document.querySelector(this.container); + + const audioPlayerElement = document.createElement('div'); + audioPlayerElement.id = 'audio-player'; + + const audioControlsElement = document.createElement('div'); + audioControlsElement.id = 'audio-controls'; + + this.playButton = document.createElement('button'); + this.playButton.innerHTML = ''; + this.playButton.addEventListener('click', () => { + if (!this.isPlaying) { + this.play(); + } + }); + + this.pauseButton = document.createElement('button'); + this.pauseButton.innerHTML = ''; + this.pauseButton.addEventListener('click', () => { + if (this.isPlaying) { + this.pause(); + } + }); + + audioControlsElement.appendChild(this.playButton); + audioControlsElement.appendChild(this.pauseButton); + + audioPlayerElement.appendChild(audioControlsElement); + + containerElement.appendChild(audioPlayerElement); + } + + play() { + if (!this.isPlaying) { + this.audio.play(); + this.isPlaying = true; + this.playButton.style.display = 'none'; + this.pauseButton.style.display = 'inline-block'; + } + } + + pause() { + if (this.isPlaying) { + this.audio.pause(); + this.isPlaying = false; + this.playButton.style.display = 'inline-block'; + this.pauseButton.style.display = 'none'; + } + } +} \ No newline at end of file diff --git a/static/templates/index.html b/static/templates/index.html new file mode 100644 index 0000000..e2ea3ba --- /dev/null +++ b/static/templates/index.html @@ -0,0 +1,16 @@ + + + + Login + + +
+

Login

+
+ + + +
+
+ + \ No newline at end of file diff --git a/static/templates/log.html b/static/templates/log.html new file mode 100644 index 0000000..f8b8468 --- /dev/null +++ b/static/templates/log.html @@ -0,0 +1,39 @@ + + + + + + + + + + + + +
+
+ {% for lo in log %} +
+
+ + {% if lo.text %} + {% for line in lo.text %} + {{ line }}
+ {% endfor %} + {% else %} + No text file found. + {% endif %} +
+ + {% endfor %} +
+ +
+ + + \ No newline at end of file diff --git a/static/templates/logs.html b/static/templates/logs.html new file mode 100644 index 0000000..371877c --- /dev/null +++ b/static/templates/logs.html @@ -0,0 +1,31 @@ + + + + Logs + + +
+

Logs

+ + {% if logs %} + + + {% else %} + No logs found. + {% endif %} + + {% if logged_in %} + Logged in as admin. + {% else %} + You need to be logged in to view this page. + {% endif %} + +
+ + + + \ No newline at end of file diff --git a/test.py b/test.py index f430d51..6047bd2 100644 --- a/test.py +++ b/test.py @@ -1,198 +1,71 @@ -from flask import Flask, request, jsonify -import logging -import random +from typing import Dict, Any, List, Tuple, Optional +import os +from fastapi import FastAPI, Request, Form, Depends, Cookie, responses, templating, HTTPException +from starlette.staticfiles import StaticFiles -app = Flask(__name__) - -logging.basicConfig(level=logging.INFO) - -cities = { - 'москва': [['1540737/daa6e420d33102bf6947', '213044/7df73ae4cc715175059e'], "Россия"], - 'нью-йорк': [['1652229/728d5c86707054d4745f', '1030494/aca7ed7acefde2606bdc']], - 'париж': [["1652229/f77136c2364eb90a3ea8", '123494/aca7ed7acefd12e606bdc']] -} - -sessionStorage = {} +app = FastAPI() +templates = templating.Jinja2Templates(directory="static/templates") +app.mount("/static", StaticFiles(directory="static"), name="static") -@app.route('/post', methods=['POST']) -def main(): - logging.info('Request: %r', request.json) - response = { - 'session': request.json['session'], - 'version': request.json['version'], - 'response': { - 'end_session': False - } - } - handle_dialog(response, request.json) - logging.info('Response: %r', response) - return jsonify(response) +def is_logged_in(logged_in: Optional[str] = Cookie(None)): + return bool(logged_in) -def handle_dialog(res, req): - user_id = req['session']['user_id'] - if req['session']['new']: - res['response']['text'] = 'Привет! Назови своё имя!' - sessionStorage[user_id] = { - 'first_name': None, - 'game_started': False - } - return +@app.get("/", response_class=responses.HTMLResponse) +def index(request: Request): + return templates.TemplateResponse("index.html", {"request": request}) - if sessionStorage[user_id]['first_name'] is None: - first_name = get_first_name(req) - if first_name is None: - res['response']['text'] = 'Не расслышала имя. Повтори, пожалуйста!' - else: - sessionStorage[user_id]['first_name'] = first_name - sessionStorage[user_id]['guessed_cities'] = [] - res['response']['text'] = f'Приятно познакомиться, {first_name.title()}. Я Алиса. Отгадаешь город по фото?' - res['response']['buttons'] = [ - { - 'title': 'Да', - 'hide': True - }, - { - 'title': 'Нет', - 'hide': True - } - ] + +@app.post("/login") +async def login(password: str = Form(...)): + if password == "password": + response = responses.RedirectResponse(url="/logs", status_code=303) + response.set_cookie(key="logged_in", value="true") + return response + return {"message": "Invalid password"} + + +@app.get("/logs", response_class=responses.HTMLResponse) +async def logs(request: Request, logged_in: bool = Depends(is_logged_in)): + if logged_in: + return templates.TemplateResponse("logs.html", {"request": request, "logs": get_logs()}) else: - if not sessionStorage[user_id]['game_started']: - if 'да' in req['request']['nlu']['tokens']: - if len(sessionStorage[user_id]['guessed_cities']) == 3: - res['response']['text'] = 'Ты отгадал все города!' - res['end_session'] = True - else: - sessionStorage[user_id]['game_started'] = True - sessionStorage[user_id]['attempt'] = 1 - play_game(res, req) - elif 'нет' in req['request']['nlu']['tokens']: - res['response']['text'] = 'Ну и ладно!' - res['end_session'] = True - else: - res['response']['text'] = 'Не поняла ответа! Так да или нет?' - res['response']['buttons'] = [ - { - 'title': 'Да', - 'hide': True - }, - { - 'title': 'Нет', - 'hide': True - } - ] - else: - play_game(res, req) + responses.RedirectResponse(url="/login", status_code=303) -def play_game(res, req): - user_id = req['session']['user_id'] - city = random.choice(list(cities.keys())) - while city in sessionStorage[user_id]['guessed_cities']: - city = random.choice(list(cities.keys())) - sessionStorage[user_id]['city'] = city - sessionStorage[user_id]['country'] = cities[city][1] - sessionStorage[user_id]['guessed_cities'].append(city) - images = cities[city][0] - res['response']['card'] = {} - res['response']['card']['type'] = 'BigImage' - res['response']['card']['title'] = 'Что это за город?' - res['response']['card']['image_id'] = random.choice(images) - res['response']['text'] = 'Тогда сыграем! Как называется этот город?' - - -def check_city(res, req): - user_id = req['session']['user_id'] - if req['request']['original_utterance'].lower() == sessionStorage[user_id]['city']: - if len(sessionStorage[user_id]['guessed_cities']) == 3: - res['response']['text'] = f'Правильно! Ты отгадал все города!' - res['end_session'] = True - else: - res['response']['text'] = f'Правильно! Следующий город - {play_game(res, req)}' - sessionStorage[user_id]['game_started'] = False - del sessionStorage[user_id]['attempt'] - - # Добавляем вопрос о стране - res['response']['buttons'] = [ - { - 'title': 'Да', - 'hide': True, - }, - { - 'title': 'Нет', - 'hide': True, - } - ] +@app.get("/logs/{log_id}", response_class=responses.HTMLResponse) +async def log(request: Request, log_id: int, logged_in: bool = Depends(is_logged_in)): + if logged_in: + if not get_log(log_id): + raise HTTPException(status_code=400) + return templates.TemplateResponse("log.html", {"request": request, + "log": get_log(log_id)}) else: - if sessionStorage[user_id]['attempt'] == 3: - res['response'][ - 'text'] = f'Вы проиграли! Правильный ответ - {sessionStorage[user_id]["city"]}. Сыграем еще?' - del sessionStorage[user_id]['attempt'] - sessionStorage[user_id]['game_started'] = False - res['response']['buttons'] = [ - { - 'title': 'Да', - 'hide': True, - }, - { - 'title': 'Нет', - 'hide': True, - } - ] - else: - sessionStorage[user_id]['attempt'] += 1 - res['response']['text'] = f'Неправильно. Попробуй еще раз!' + responses.RedirectResponse(url="/login", status_code=303) -def check_country(res, req): - user_id = req['session']['user_id'] - if req['request']['original_utterance'].lower() == sessionStorage[user_id]['country']: - res['response']['text'] = f'Правильно! Следующий город - {play_game(res, req)}' - del sessionStorage[user_id]['attempt'] - res['response']['buttons'] = [ - { - 'title': 'Да', - 'hide': True, - }, - { - 'title': 'Нет', - 'hide': True, - } - ] - else: - if sessionStorage[user_id]['attempt'] == 3: - res['response'][ - 'text'] = f'Вы проиграли! Правильный ответ - {sessionStorage[user_id]["country"]}. Сыграем еще?' - del sessionStorage[user_id]['attempt'] - sessionStorage[user_id]['game_started'] = False - res['response']['buttons'] = [ - { - 'title': 'Да', - 'hide': True, - }, - { - 'title': 'Нет', - 'hide': True, - } - ] - else: - sessionStorage[user_id]['attempt'] += 1 - res['response']['text'] = f'Неправильно. Попробуй еще раз!' + +def get_logs() -> List[Tuple[int, str]]: + return [(int(os.path.basename(dir_path)), dir_path.split("/")[2].strip()) + for dir_path, _, filenames in os.walk("static/logs") + if dir_path != "static/logs" and len(dir_path.split("/")) == 3] -def get_city(req): - for entity in req['request']['nlu']['entities']: - if entity['type'] == 'YANDEX.GEO': - return entity['value'].get('city', None) - - -def get_first_name(req): - for entity in req['request']['nlu']['entities']: - if entity['type'] == 'YANDEX.FIO': - return entity['value'].get('first_name', None) - - -if __name__ == '__main__': - app.run(port=52520) +def get_log(log_id: int) -> List[Dict[str, Any]]: + log_dir = os.path.join("static/logs", str(log_id)) + return_dir = [] + for dir_path, _, filenames in os.walk(log_dir): + if dir_path != log_dir: + audio_file = os.path.join(dir_path, "audio.ogg") + if not os.path.exists(audio_file): + audio_file = os.path.join(dir_path, "audio.wav") + text_file = os.path.join(dir_path, "yandex-text.txt") + if not os.path.exists(text_file): + text_file = os.path.join(dir_path, "google-text.txt") + try: + return_dir.append({"id": log_id, "audio_file": f"/{audio_file}", + "text": open(text_file).read().split("\n")}) + except UnicodeDecodeError: + pass + return return_dir