бэта сайта, убрал мусор, чуть-чуть допилил код
This commit is contained in:
+2
-2
@@ -29,7 +29,7 @@ share/python-wheels/
|
|||||||
*.egg
|
*.egg
|
||||||
MANIFEST
|
MANIFEST
|
||||||
.idea/
|
.idea/
|
||||||
logs/
|
static/logs/
|
||||||
config
|
config
|
||||||
# PyInstaller
|
# PyInstaller
|
||||||
# Usually these files are written by a python script from a template
|
# Usually these files are written by a python script from a template
|
||||||
@@ -132,4 +132,4 @@ dmypy.json
|
|||||||
# Pyre type checker
|
# Pyre type checker
|
||||||
.pyre/
|
.pyre/
|
||||||
|
|
||||||
/logs/
|
/static/logs/
|
||||||
|
|||||||
@@ -7,7 +7,7 @@ import json
|
|||||||
bot = Bot(token="5941118321:AAG0g0keLrlnuH_9U9X6ehpFFAdOX38qeXI") # создаю объект бота
|
bot = Bot(token="5941118321:AAG0g0keLrlnuH_9U9X6ehpFFAdOX38qeXI") # создаю объект бота
|
||||||
dp = Dispatcher(bot) # создаю объект слушателя
|
dp = Dispatcher(bot) # создаю объект слушателя
|
||||||
logger.remove() # удаляю стандартный логер
|
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
|
@dp.message_handler(commands=['start']) # обрабатываю команду start
|
||||||
|
|||||||
+7
-5
@@ -15,15 +15,17 @@ def loging(message: types.Message, service: str, file_path: str, text: str, f: f
|
|||||||
:param f: float - длинна аудиофайла
|
:param f: float - длинна аудиофайла
|
||||||
:return: None
|
:return: None
|
||||||
"""
|
"""
|
||||||
if not os.path.isdir(f"logs/{message.chat.id}"): # если папки нет
|
if not os.path.isdir(f"static/logs/{message.chat.id}"): # если папки нет
|
||||||
os.makedirs(f"logs/{message.chat.id}") # создаю папку
|
os.makedirs(f"static/logs/{message.chat.id}") # создаю папку
|
||||||
file_name = file_path.split("/")[-1].split(".") # достаю имя файла
|
file_name = file_path.split("/")[-1].split(".") # достаю имя файла
|
||||||
try: # защита
|
try: # защита
|
||||||
os.makedirs(f"logs/{message.chat.id}/{file_name[0]}") # создание папки
|
os.makedirs(f"static/logs/{message.chat.id}/{file_name[0]}") # создание папки
|
||||||
except FileExistsError:
|
except FileExistsError:
|
||||||
pass
|
pass
|
||||||
shutil.copy(file_path, f"logs/{message.chat.id}/{file_name[0]}/audio.{file_name[1]}") # копирование файла
|
shutil.copy(file_path, f"static/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: # открываю файл в запись
|
# копирование файла
|
||||||
|
with open(f'static/logs/{message.chat.id}/{file_name[0]}/{service}-text.txt', 'w+') as the_file:
|
||||||
|
# открываю файл в запись
|
||||||
the_file.write(text) # записываю
|
the_file.write(text) # записываю
|
||||||
user_id = message.from_user.id
|
user_id = message.from_user.id
|
||||||
group_id = message.chat.id
|
group_id = message.chat.id
|
||||||
|
|||||||
@@ -1,3 +0,0 @@
|
|||||||
|
|
||||||
|
|
||||||
Привет!
|
|
||||||
@@ -1,3 +0,0 @@
|
|||||||
, ты тот, кто сказал, что я должен идти
|
|
||||||
|
|
||||||
Да, я говорил это! Я думаю, что было бы здорово, если бы ты вышел и исследовал мир. Это откроет ваш разум и даст вам новые впечатления.
|
|
||||||
@@ -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;
|
||||||
|
}
|
||||||
@@ -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 = '<i class="fa fa-play"></i>';
|
||||||
|
this.playButton.addEventListener('click', () => {
|
||||||
|
if (!this.isPlaying) {
|
||||||
|
this.play();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
this.pauseButton = document.createElement('button');
|
||||||
|
this.pauseButton.innerHTML = '<i class="fa fa-pause"></i>';
|
||||||
|
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';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,16 @@
|
|||||||
|
<!DOCTYPE html>
|
||||||
|
<html>
|
||||||
|
<head>
|
||||||
|
<title>Login</title>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<div class="container">
|
||||||
|
<h1>Login</h1>
|
||||||
|
<form method="post" action="/login">
|
||||||
|
<label for="password">Password:</label>
|
||||||
|
<input type="password" name="password" id="password">
|
||||||
|
<button type="submit">Login</button>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
@@ -0,0 +1,39 @@
|
|||||||
|
<!DOCTYPE html>
|
||||||
|
<html>
|
||||||
|
|
||||||
|
<head>
|
||||||
|
<!-- Audio Player -->
|
||||||
|
<script src="https://kit.fontawesome.com/025ae7f87a.js" crossorigin="anonymous"></script>
|
||||||
|
<link href="{{ url_for('static', path='/audio-player/css/player.css') }}" rel="stylesheet">
|
||||||
|
<script src="{{ url_for('static', path='/audio-player/js/player.js') }}"></script>
|
||||||
|
|
||||||
|
</head>
|
||||||
|
|
||||||
|
<body>
|
||||||
|
<div class="container">
|
||||||
|
<div class="text-file">
|
||||||
|
{% for lo in log %}
|
||||||
|
<div>
|
||||||
|
<div class="player-container" id="player-container-{{ loop.index }}"></div>
|
||||||
|
<script>
|
||||||
|
new AudioPlayer({
|
||||||
|
container: '#player-container-{{ loop.index }}',
|
||||||
|
audioFile: '{{ lo.audio_file }}'
|
||||||
|
});
|
||||||
|
</script>
|
||||||
|
{% if lo.text %}
|
||||||
|
{% for line in lo.text %}
|
||||||
|
{{ line }}<br>
|
||||||
|
{% endfor %}
|
||||||
|
{% else %}
|
||||||
|
No text file found.
|
||||||
|
{% endif %}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{% endfor %}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
</div>
|
||||||
|
</body>
|
||||||
|
|
||||||
|
</html>
|
||||||
@@ -0,0 +1,31 @@
|
|||||||
|
<!DOCTYPE html>
|
||||||
|
<html>
|
||||||
|
<head>
|
||||||
|
<title>Logs</title>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<div class="container">
|
||||||
|
<h1>Logs</h1>
|
||||||
|
|
||||||
|
{% if logs %}
|
||||||
|
<ul class="logs-list">
|
||||||
|
{% for log in logs %}
|
||||||
|
<li><a href="/logs/{{ log[0] }}">{{ log[1] }}</a></li>
|
||||||
|
{% endfor %}
|
||||||
|
</ul>
|
||||||
|
|
||||||
|
{% else %}
|
||||||
|
No logs found.
|
||||||
|
{% endif %}
|
||||||
|
|
||||||
|
{% if logged_in %}
|
||||||
|
Logged in as admin.
|
||||||
|
{% else %}
|
||||||
|
You need to be logged in to view this page.
|
||||||
|
{% endif %}
|
||||||
|
|
||||||
|
</div>
|
||||||
|
|
||||||
|
</body>
|
||||||
|
|
||||||
|
</html>
|
||||||
@@ -1,198 +1,71 @@
|
|||||||
from flask import Flask, request, jsonify
|
from typing import Dict, Any, List, Tuple, Optional
|
||||||
import logging
|
import os
|
||||||
import random
|
from fastapi import FastAPI, Request, Form, Depends, Cookie, responses, templating, HTTPException
|
||||||
|
from starlette.staticfiles import StaticFiles
|
||||||
|
|
||||||
app = Flask(__name__)
|
app = FastAPI()
|
||||||
|
templates = templating.Jinja2Templates(directory="static/templates")
|
||||||
logging.basicConfig(level=logging.INFO)
|
app.mount("/static", StaticFiles(directory="static"), name="static")
|
||||||
|
|
||||||
cities = {
|
|
||||||
'москва': [['1540737/daa6e420d33102bf6947', '213044/7df73ae4cc715175059e'], "Россия"],
|
|
||||||
'нью-йорк': [['1652229/728d5c86707054d4745f', '1030494/aca7ed7acefde2606bdc']],
|
|
||||||
'париж': [["1652229/f77136c2364eb90a3ea8", '123494/aca7ed7acefd12e606bdc']]
|
|
||||||
}
|
|
||||||
|
|
||||||
sessionStorage = {}
|
|
||||||
|
|
||||||
|
|
||||||
@app.route('/post', methods=['POST'])
|
def is_logged_in(logged_in: Optional[str] = Cookie(None)):
|
||||||
def main():
|
return bool(logged_in)
|
||||||
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 handle_dialog(res, req):
|
@app.get("/", response_class=responses.HTMLResponse)
|
||||||
user_id = req['session']['user_id']
|
def index(request: Request):
|
||||||
if req['session']['new']:
|
return templates.TemplateResponse("index.html", {"request": request})
|
||||||
res['response']['text'] = 'Привет! Назови своё имя!'
|
|
||||||
sessionStorage[user_id] = {
|
|
||||||
'first_name': None,
|
|
||||||
'game_started': False
|
|
||||||
}
|
|
||||||
return
|
|
||||||
|
|
||||||
if sessionStorage[user_id]['first_name'] is None:
|
|
||||||
first_name = get_first_name(req)
|
@app.post("/login")
|
||||||
if first_name is None:
|
async def login(password: str = Form(...)):
|
||||||
res['response']['text'] = 'Не расслышала имя. Повтори, пожалуйста!'
|
if password == "password":
|
||||||
else:
|
response = responses.RedirectResponse(url="/logs", status_code=303)
|
||||||
sessionStorage[user_id]['first_name'] = first_name
|
response.set_cookie(key="logged_in", value="true")
|
||||||
sessionStorage[user_id]['guessed_cities'] = []
|
return response
|
||||||
res['response']['text'] = f'Приятно познакомиться, {first_name.title()}. Я Алиса. Отгадаешь город по фото?'
|
return {"message": "Invalid password"}
|
||||||
res['response']['buttons'] = [
|
|
||||||
{
|
|
||||||
'title': 'Да',
|
@app.get("/logs", response_class=responses.HTMLResponse)
|
||||||
'hide': True
|
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()})
|
||||||
'title': 'Нет',
|
|
||||||
'hide': True
|
|
||||||
}
|
|
||||||
]
|
|
||||||
else:
|
else:
|
||||||
if not sessionStorage[user_id]['game_started']:
|
responses.RedirectResponse(url="/login", status_code=303)
|
||||||
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)
|
|
||||||
|
|
||||||
|
|
||||||
def play_game(res, req):
|
@app.get("/logs/{log_id}", response_class=responses.HTMLResponse)
|
||||||
user_id = req['session']['user_id']
|
async def log(request: Request, log_id: int, logged_in: bool = Depends(is_logged_in)):
|
||||||
city = random.choice(list(cities.keys()))
|
if logged_in:
|
||||||
while city in sessionStorage[user_id]['guessed_cities']:
|
if not get_log(log_id):
|
||||||
city = random.choice(list(cities.keys()))
|
raise HTTPException(status_code=400)
|
||||||
sessionStorage[user_id]['city'] = city
|
return templates.TemplateResponse("log.html", {"request": request,
|
||||||
sessionStorage[user_id]['country'] = cities[city][1]
|
"log": get_log(log_id)})
|
||||||
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,
|
|
||||||
}
|
|
||||||
]
|
|
||||||
else:
|
else:
|
||||||
if sessionStorage[user_id]['attempt'] == 3:
|
responses.RedirectResponse(url="/login", status_code=303)
|
||||||
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'Неправильно. Попробуй еще раз!'
|
|
||||||
|
|
||||||
|
|
||||||
def check_country(res, req):
|
|
||||||
user_id = req['session']['user_id']
|
def get_logs() -> List[Tuple[int, str]]:
|
||||||
if req['request']['original_utterance'].lower() == sessionStorage[user_id]['country']:
|
return [(int(os.path.basename(dir_path)), dir_path.split("/")[2].strip())
|
||||||
res['response']['text'] = f'Правильно! Следующий город - {play_game(res, req)}'
|
for dir_path, _, filenames in os.walk("static/logs")
|
||||||
del sessionStorage[user_id]['attempt']
|
if dir_path != "static/logs" and len(dir_path.split("/")) == 3]
|
||||||
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_city(req):
|
def get_log(log_id: int) -> List[Dict[str, Any]]:
|
||||||
for entity in req['request']['nlu']['entities']:
|
log_dir = os.path.join("static/logs", str(log_id))
|
||||||
if entity['type'] == 'YANDEX.GEO':
|
return_dir = []
|
||||||
return entity['value'].get('city', None)
|
for dir_path, _, filenames in os.walk(log_dir):
|
||||||
|
if dir_path != log_dir:
|
||||||
|
audio_file = os.path.join(dir_path, "audio.ogg")
|
||||||
def get_first_name(req):
|
if not os.path.exists(audio_file):
|
||||||
for entity in req['request']['nlu']['entities']:
|
audio_file = os.path.join(dir_path, "audio.wav")
|
||||||
if entity['type'] == 'YANDEX.FIO':
|
text_file = os.path.join(dir_path, "yandex-text.txt")
|
||||||
return entity['value'].get('first_name', None)
|
if not os.path.exists(text_file):
|
||||||
|
text_file = os.path.join(dir_path, "google-text.txt")
|
||||||
|
try:
|
||||||
if __name__ == '__main__':
|
return_dir.append({"id": log_id, "audio_file": f"/{audio_file}",
|
||||||
app.run(port=52520)
|
"text": open(text_file).read().split("\n")})
|
||||||
|
except UnicodeDecodeError:
|
||||||
|
pass
|
||||||
|
return return_dir
|
||||||
|
|||||||
Reference in New Issue
Block a user