Compare commits

..

26 Commits

Author SHA1 Message Date
justuser31 bda4452390 Мелкие правки, добавление источников локализации и рецептов 2024-05-07 22:04:02 +03:00
justuser31 53d540c841 Добавлена функция получения предрасчётов 2024-05-07 20:37:54 +03:00
justuser31 320a7204e3 Обновление update_db и мелкие изменения 2024-05-04 18:53:45 +03:00
justuser31 0ef9fc1de9 Сохранение рецептов, изменение структуры класса reag__ 2024-05-04 14:20:09 +03:00
justuser31 5cce77aa10 Загрузка списком локализаций и рецептов 2024-05-04 14:00:31 +03:00
justuser31 0a98ef930b up 2024-05-04 13:20:24 +03:00
justuser31 45ec9a1157 Исправил баг, немного модифицировал. 2024-05-04 13:18:41 +03:00
justuser31 5deaa5823e up 2024-05-04 12:46:21 +03:00
justuser31 170dc0517a Оптимизация функции локализации 2024-05-03 18:08:26 +03:00
justuser31 63af9c4eaa Оптимизация функции локализации 2024-05-03 18:04:09 +03:00
wadehusky a54a1b3d61 Исправление табуляции 2024-05-03 17:58:37 +03:00
wadehusky 3d6074260a Добавление функции localize() в parse.py 2024-05-02 19:07:06 +03:00
justuser31 32527fe39e Домножение рецепта и мелкие доработки 2024-05-02 17:46:32 +03:00
justuser31 22b2a0ec27 Мелкие поправки, комментарии. 2024-05-01 15:14:33 +03:00
justuser31 eb13e945b9 Merge branch 'main' of github.com:Justuser3310/ss14_chemistry_site 2024-05-01 15:11:19 +03:00
justuser31 0d3bd86b2c Новый алгоритм, ура. 2024-05-01 15:07:43 +03:00
dttric 609c21245f + примерная реализация "получения рецепта" через POST
+ реформат таблицы для демо потому что удобно (я копировать буду👿👿)
2024-04-30 21:56:33 +07:00
dttric d7296528b2 Просто сделай 2 вкладки под это. 2024-04-30 20:52:52 +07:00
dttric 398796e892 justuser — Сегодня, в 20:45
Рецепт составляющего не нужен, много мороки будет.
2024-04-30 20:49:03 +07:00
dttric 21a77c1372 Совмещение изменений. 2024-04-30 20:44:53 +07:00
dttric ad8819dbd7 + demo.html
# показывает примерный вид сайта
2024-04-30 20:44:31 +07:00
justuser31 0afa599408 Пробелы на табы, мелкие поправки. 2024-04-30 16:09:46 +03:00
dttric ed661f01f1 - дропдауны
+ радиальные кнопки для количества
+ <select /> для реакций
2024-04-30 20:01:03 +07:00
wadehusky bdc90b42d0 Добавление функции load_recipe() в parse.py
Добавление функции get_all() для класса reag__
2024-04-30 15:34:26 +03:00
wadehusky fb9254844e Merge remote-tracking branch 'origin/main' 2024-04-30 15:31:13 +03:00
wadehusky e5c7c65816 Добавление функции load_recipe() в parse.py
Добавление функции get_all() для класса reag__
2024-04-30 15:29:00 +03:00
10 changed files with 354 additions and 39 deletions
Binary file not shown.

After

Width:  |  Height:  |  Size: 149 KiB

+67
View File
@@ -0,0 +1,67 @@
from precalc__ import precalc__
from db import load
global expanded
def expand_recipe(recipe, recipes, main = False):
global expanded
if main:
expanded = {}
ok = False
part = 1 # Одна часть
while not ok:
ok = True
vol_in = 0 # Объём мин. рецепта (вход)
# Перебираем элементы
for el in recipe:
# Если составное
if el in recipes:
# Одна часть должна делиться без остатка!
if part % recipes[el].out != 0:
ok = False
part += 1
expanded = {}
break
else:
vol_in += expand_recipe(recipes[el].comps, recipes)
else:
if el in expanded:
expanded[el] += recipe[el]*part
else:
expanded[el] = recipe[el]*part
vol_in += recipe[el]*part
if main:
return expanded, vol_in, part
else:
return vol_in
def calc(element, amount, recipes):
# Получаем характеристику элемента
recipe, vol_out = recipes[element].comps, recipes[element].out
# Расчитываем минимальный рецепт
expanded, vol_in, part = expand_recipe(recipe, recipes, True)
need = amount//vol_in
for i in expanded:
expanded[i] = expanded[i]*need
vol_in *= need
vol_out *= part*need
return expanded, vol_in, vol_out
def calc_all(recipes, amount):
precalc = {}
for el in recipes:
precalc[el] = precalc__(calc(el, amount, recipes))
return precalc
def precalc(element, amount):
try:
# Загружаем рецепты с нужным количеством
recipes = load(f'{amount}_calc.json', 'precalc')
except:
return 'Нету такого файла или вещества'
return recipes[element]
+35 -7
View File
@@ -1,20 +1,48 @@
import os import os
import json import json
from reag__ import reag__
from precalc__ import precalc__
if not os.path.exists('db.json'): if not os.path.exists('precalc.json'):
db = {} db = {}
js = json.dumps(db, indent=2) js = json.dumps(db, indent=2)
with open("db.json", "w") as outfile: with open('precalc.json', 'w') as outfile:
outfile.write(js) outfile.write(js)
print('Created new db.json') print('Created new precalc.json')
if not os.path.exists('raw_db.json'):
db = {}
js = json.dumps(db, indent=2)
with open('raw_db.json', 'w') as outfile:
outfile.write(js)
print('Created new raw_db.json')
def read_db(file = 'db.json'): def read_db(file):
with open(file, "r", encoding="utf-8") as openfile: with open(file, 'r', encoding='utf-8') as openfile:
db = json.load(openfile) db = json.load(openfile)
return db return db
def write_db(db, file = 'db.json'): def write_db(db, file):
js = json.dumps(db, indent=2, ensure_ascii=False) js = json.dumps(db, indent=2, ensure_ascii=False)
with open(file, "w", encoding="utf-8") as outfile: with open(file, 'w', encoding='utf-8') as outfile:
outfile.write(js) outfile.write(js)
def save(db, file):
raw = {}
for el in db:
class_data = db[el].get_all()
raw[el] = class_data
write_db(raw, file)
def load(file, type = 'raw'):
raw = read_db(file)
db = {}
if type == 'raw':
for el in raw:
db[el] = reag__(raw[el][0], raw[el][1], raw[el][2])
elif type == 'precalc':
for el in raw:
db[el] = precalc__(raw[el])
return db
+88
View File
@@ -0,0 +1,88 @@
<!doctype html>
<html lang="ru" data-bs-theme="dark">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>SS14Tools</title>
<link rel="icon" type="image/x-icon" href="./assets/favicon.ico">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.8.1/font/bootstrap-icons.css">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" integrity="sha384-9ndCyUaIbzAi2FUVXJi0CjmCapSmO7SnpJef0486qhLnuZ2cdeRhO02iuK6FUUVM" crossorigin="anonymous">
</head>
<body>
<style>
.mx-10 {
margin-left: 10rem;
margin-right: 10rem;
}
.gxr-- {
margin-right: 18rem;
}
.gxl-- {
margin-left: 18rem;
}
</style>
<nav class="navbar bg-body-tertiary">
<div class="container-fluid">
<a class="navbar-brand" href="#"><i class="bi bi-tools"></i> SS14Tools</a>
<div class="btn-group" role="group" aria-label="Простой пример">
<button type="button" class="btn btn-primary"><i class="bi bi-discord"></i></button>
<button type="button" class="btn btn-primary"><i class="bi bi-telegram"></i></button>
<button type="button" class="btn btn-primary"><i class="bi bi-github"></i></button>
</div>
</div>
</nav>
<center>
<div class="container">
<div class="row py-5">
<div class="col-xl-9">
<select class="form-select" aria-label="Реакция">
<option selected><p class="gx-5">💊 Дермалин</p></option>
</select>
</div>
<div class="container-fluid col">
<div class="btn-group" role="group" aria-label="Базовая группа переключателей радио">
<input type="radio" class="btn-check" name="btnradio" id="30" autocomplete="off">
<label class="btn btn-outline-primary" for="30">30</label>
<input type="radio" class="btn-check" name="btnradio" id="50" autocomplete="off">
<label class="btn btn-outline-primary" for="50">50</label>
<input type="radio" class="btn-check" name="btnradio" id="100" autocomplete="off" checked>
<label class="btn btn-outline-primary" for="100">100</label>
<input type="radio" class="btn-check" name="btnradio" id="300" autocomplete="off">
<label class="btn btn-outline-primary" for="300">300</label>
<input type="radio" class="btn-check" name="btnradio" id="1000" autocomplete="off">
<label class="btn btn-outline-primary" for="1000">1000</label>
</div>
</div>
</div>
<div class="row">
<ul class="nav nav-tabs">
<li class="nav-item">
<a class="nav-link active" aria-current="page" href="#">Рецепт</a>
</li>
<li class="nav-item">
<a class="nav-link disabled">Эффекты и дебафы</a>
</li>
</ul>
<table class="table">
<thead>
<tr>
<th scope="col">Составляющее</th>
<th scope="col">Количество</th>
</tr>
</thead>
<tbody>
<tr><td>Кислород</td><td>100</td></tr>
<tr><td>Фосфор</td><td>100</td></tr>
<tr><td>Келотан</td><td>100</td></tr>
</tbody>
</table>
</div>
</div>
</center>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js" integrity="sha384-geWF76RCwLtnZ8qwWowPQNguL3RmwHVBC9FhGdlKrxdiJJigb/j/68SIy3Te4Bkz" crossorigin="anonymous"></script>
</body>
</html>
+70 -4
View File
@@ -1,11 +1,14 @@
from requests import get from requests import get
from yaml import load, SafeLoader from yaml import load, SafeLoader
from reag__ import reag__
from tqdm import tqdm
def parse_yml(url = 'https://raw.githubusercontent.com/SerbiaStrong-220/space-station-14/master/Resources/Prototypes/Recipes/Reactions/medicine.yml'): #### Локализация ####
yml = load(get(url).content.decode('utf-8'), Loader=SafeLoader)
return yml
def parse_ftl(url = 'https://raw.githubusercontent.com/SerbiaStrong-220/space-station-14/master/Resources/Locale/ru-RU/reagents/meta/medicine.ftl'): def parse_ftl(el, prefix = 'https://raw.githubusercontent.com/SerbiaStrong-220/space-station-14/master/Resources/Locale/ru-RU/reagents/meta'):
if '.ftl' not in el:
el += '.ftl'
url = f'{prefix}/{el}'
raw = get(url).content.decode('utf-8') raw = get(url).content.decode('utf-8')
locales = {} locales = {}
for i in raw.splitlines(): for i in raw.splitlines():
@@ -15,3 +18,66 @@ def parse_ftl(url = 'https://raw.githubusercontent.com/SerbiaStrong-220/space-st
locale = splitted[2] locale = splitted[2]
locales[name] = locale locales[name] = locale
return locales return locales
def load_locales(locales_url):
locales = {}
for el in tqdm(locales_url):
locales = locales | parse_ftl(el)
return locales
#### Рецепты ####
SafeLoader.add_multi_constructor('', lambda loader, tag_suffix, node: None)
def parse_yml(el, prefix = 'https://raw.githubusercontent.com/SerbiaStrong-220/space-station-14/master/Resources/Prototypes/Recipes/Reactions'):
if '.yml' not in el:
el += '.yml'
url = f'{prefix}/{el}'
yml = load(get(url).content.decode('utf-8'), Loader=SafeLoader)
return yml
def load_recipes(recipes_url, prefix = 'https://raw.githubusercontent.com/SerbiaStrong-220/space-station-14/master/Resources/Prototypes/Recipes/Reactions'):
recipes = {}
for el in tqdm(recipes_url):
yml = parse_yml(el, prefix)
for element in yml:
if 'products' not in element or 'reactants' not in element:
continue
product = element['id']
comps = {}
for elem in element['reactants']:
comps[elem] = element['reactants'][elem]['amount']
for id, value in element['products'].items():
out = value
recipes[product] = reag__(comps=comps, out=out, category=el)
return recipes
#### Локализируем ####
def localize(recipes, locale):
loc_recipes = {}
# Итерируем элементы
for element in recipes:
# Итерируем составные
el = recipes[element]
# Локализованные составные
loc_comps = {}
for comp in el.comps:
# Ищем перевод
if comp.lower() in locale:
loc = locale[comp.lower()].capitalize()
loc_comps[loc] = el.comps[comp]
else:
loc_comps[comp] = el.comps[comp]
# Заменяем на локализованное
el.comps = loc_comps
# Локализуем ключ
if element.lower() in locale:
loc = locale[element.lower()].capitalize()
loc_recipes[loc] = recipes[element]
else:
loc_recipes[element] = recipes[element]
return loc_recipes
+7
View File
@@ -0,0 +1,7 @@
class precalc__:
def __init__(self, els):
self.recipe = els[0]
self.vol_in = els[1]
self.vol_out = els[2]
def get_all(self):
return [self.recipe, self.vol_in, self.vol_out]
+6 -3
View File
@@ -1,8 +1,11 @@
class reag__: class reag__:
def __init__(category = '-', comps, out): def __init__(self, comps, out, category = '-'):
# medicine
self.category = category
# {'инапровалин': 1, 'углерод': 1} # {'инапровалин': 1, 'углерод': 1}
self.comps = comps self.comps = comps
# 2 # 2
self.out = out self.out = out
# medicine
self.category = category
def get_all(self):
return [self.comps, self.out, self.category]
+6 -1
View File
@@ -1,4 +1,4 @@
from flask import Flask, render_template from flask import Flask, render_template, request
app = Flask(__name__) app = Flask(__name__)
@app.route("/") @app.route("/")
@@ -7,3 +7,8 @@ def main():
if __name__ == '__main__': if __name__ == '__main__':
app.run(debug=False, port = 5001) app.run(debug=False, port = 5001)
@app.route("/submit", methods=['POST'])
def calculate():
selectedval = request.form["getrecept"]
return f"{selectedval}"
+28 -24
View File
@@ -4,6 +4,7 @@
<meta charset="utf-8"> <meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="viewport" content="width=device-width, initial-scale=1">
<title>SS14Tools</title> <title>SS14Tools</title>
<link rel="icon" type="image/x-icon" href="../assets/favicon.ico">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.8.1/font/bootstrap-icons.css"> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.8.1/font/bootstrap-icons.css">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" integrity="sha384-9ndCyUaIbzAi2FUVXJi0CjmCapSmO7SnpJef0486qhLnuZ2cdeRhO02iuK6FUUVM" crossorigin="anonymous"> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" integrity="sha384-9ndCyUaIbzAi2FUVXJi0CjmCapSmO7SnpJef0486qhLnuZ2cdeRhO02iuK6FUUVM" crossorigin="anonymous">
</head> </head>
@@ -32,31 +33,34 @@
</nav> </nav>
<center> <center>
<div class="container"> <div class="container">
<div class="row"> <div class="row py-5">
<div class="col p-5 gxl--"> <div class="col-xl-9">
<div class="dropdown"> <form action="/submit" method="post">
<button class="btn btn-secondary dropdown-toggle" type="button" data-bs-toggle="dropdown" aria-expanded="false" py-5> <select class="form-select" name="getrecept" aria-label="Реакция">
<span class="mx-10">Реакция</span> <option selected><p class="gx-5">Выберите (бля а что мы конкретно выбираем)</p></option>
</button> <option value="1">Пример 1</option>
<ul class="dropdown-menu"> <option value="2">Пример 2</option>
<li><a class="dropdown-item" href="#">Пример 1</a></li> <option value="3">Пример 3</option>
<li><a class="dropdown-item" href="#">Пример 2</a></li> </select>
<li><a class="dropdown-item" href="#">Пример 3</a></li> <input type="submit" value="Submit">
</ul> </form>
</div>
</div> </div>
<div class="col p-5 gxr--"> <div class="container-fluid col">
<div class="dropdown"> <div class="btn-group" role="group" aria-label="Базовая группа переключателей радио">
<button class="btn btn-secondary dropdown-toggle" type="button" data-bs-toggle="dropdown" aria-expanded="false"> <input type="radio" class="btn-check" name="btnradio" id="30" autocomplete="off">
Сколько? <label class="btn btn-outline-primary" for="30">30</label>
</button>
<ul class="dropdown-menu"> <input type="radio" class="btn-check" name="btnradio" id="50" autocomplete="off">
<li><a class="dropdown-item" href="#">30</a></li> <label class="btn btn-outline-primary" for="50">50</label>
<li><a class="dropdown-item" href="#">50</a></li>
<li><a class="dropdown-item" href="#">100</a></li> <input type="radio" class="btn-check" name="btnradio" id="100" autocomplete="off" checked>
<li><a class="dropdown-item" href="#">300</a></li> <label class="btn btn-outline-primary" for="100">100</label>
<li><a class="dropdown-item" href="#">1000</a></li>
</ul> <input type="radio" class="btn-check" name="btnradio" id="300" autocomplete="off">
<label class="btn btn-outline-primary" for="300">300</label>
<input type="radio" class="btn-check" name="btnradio" id="1000" autocomplete="off">
<label class="btn btn-outline-primary" for="1000">1000</label>
</div> </div>
</div> </div>
</div> </div>
+47
View File
@@ -0,0 +1,47 @@
from parse import *
from calc import *
from db import *
print('''1. Обновить всё.
2. Пересчитать рецепты.
''')
inp = input(">> ")
print('\n')
vols = [30, 50, 100]
if inp == '1':
print('Парсим и обрабатываем данные...')
# Загружаем локализацию
locales_url = ['biological', 'botany', 'chemicals', 'cleaning', 'elements', 'fun',
'gases', 'medicine', 'narcotics', 'physical-desc', 'pyrotechnic', 'toxins',
'consumable/drink/alcohol', 'consumable/drink/drinks', 'consumable/drink/juice', 'consumable/drink/soda',
'consumable/food/condiments', 'consumable/food/food', 'consumable/food/ingredients']
locales = load_locales(locales_url)
# Загружаем сырые рецепты
recipes_url = ['biological', 'botany', 'chemicals', 'cleaning', 'drinks', 'food',
'fun', 'gas', 'medicine', 'pyrotechnic']
raw_recipes = load_recipes(recipes_url)
# Локализируем
recipes = localize(raw_recipes, locales)
save(recipes, 'raw_db.json')
print('Сохранены минимальные рецепты в raw_db.json')
print('Выполняем предрасчёты...')
for i in vols:
precalc = calc_all(recipes, i)
save(precalc, f'{i}_calc.json')
print(f'Данные сохранены в {i}_calc.json')
elif inp == '2':
print('Выполняем расчёты...')
recipes = load('raw_db.json')
for i in vols:
precalc = calc_all(recipes, i)
save(precalc, f'{i}_calc.json')
print(f'Данные сохранены в {i}_calc.json')
else:
exit()
print("ГОТОВО.")