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 796d229..115b6e0 100644
Binary files a/db.sql and b/db.sql differ
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