LitePrinter / app.py
JustKozrhik's picture
Update app.py
3792d71 verified
Raw History Blame Contribute Delete
15.5 kB
from litemapy import Schematic
import io
import json
from flask import Flask, request, jsonify
import requests
import zlib
import base64
from time import time
from random import choice, randint
import threading
import time
app = Flask(__name__)
# AAXXYYZZ@XXYYZZ!ABXXYYZZ@XXYYZZ@XXYYZZ!
# ["AAXXYYZZ", "@XXYYZZ!", "ABXXYYZZ", "@XXYYZZ@", "XXYYZZ!"] (ПРИМЕР по 8 символов)
BASE32_CHARS = list("0123456789ABCDEFGHIJKLMNOPQRSTUV")
OPERATIONS_CHARS = {
"close": "|", # Закрывает блок, означает начать установку блоков
"separator": "/", # Разделяет позиции
"key_separator": ":", # Разделяет ключ и значение
}
LOAD_REQUESTS = {}
LOAD_ANSWERS = {}
PROCESSING = {}
PROCESSING_LOCK = threading.Lock()
MAX_FILE_SIZE = 10_485_760 # 10 МБ
def chunk_block_entities(entities_dict, limit=20000):
"""
Чанкует словарь блоков-сущностей. Если JSON-представление чанка
превышает limit, создает новый чанк. Слишком большие элементы обрезаются.
"""
chunks = []
current_chunk = {}
current_len = 2 # Длина пустых скобок "{}"
for key, val in entities_dict.items():
# Используем separators без пробелов для точного подсчета длины
entry_str = json.dumps({key: val}, ensure_ascii=False, separators=(',', ':'))
entry_len = len(entry_str) - 2 # Длина содержимого внутри скобок
# Если элемент сам по себе больше лимита
if entry_len > limit - 2:
val = f"error: {entry_len}"
entry_str = json.dumps({key: val}, ensure_ascii=False, separators=(',', ':'))
entry_len = len(entry_str) - 2
# +1 символ для запятой, если чанк уже содержит элементы
added_len = entry_len if not current_chunk else entry_len + 1
if current_len + added_len > limit:
# Лимит превышен: сохраняем текущий чанк и начинаем новый
if current_chunk:
chunks.append(current_chunk)
current_chunk = {key: val}
current_len = 2 + entry_len
else:
# Добавляем в текущий чанк
current_chunk[key] = val
current_len += added_len
# Добавляем последний чанк, если он не пуст (или чтобы вернуть хотя бы [{}] для пустого словаря)
if current_chunk or not chunks:
chunks.append(current_chunk)
return chunks
def process_schematic(uuid, url):
try:
response = requests.get(url, timeout=30, stream=True)
response.raise_for_status()
content_length = response.headers.get('Content-Length')
if content_length and int(content_length) > MAX_FILE_SIZE:
raise ValueError("File size exceeds the maximum limit of 10 MB")
file_bytes = bytearray()
for chunk in response.iter_content(chunk_size=8192):
file_bytes.extend(chunk)
if len(file_bytes) > MAX_FILE_SIZE:
raise ValueError("File size exceeds the maximum limit of 10 MB")
schematic_file_obj = io.BytesIO(file_bytes)
try:
schem = Schematic.load(schematic_file_obj)
except Exception:
raise ValueError("Downloaded file is not a valid .litematic schematic")
schem_data = gdata(schem)
conv_data = cdata(schem_data["data"])
# --- Обработка блоков-сущностей ---
region = list(schem.regions.values())[0]
be_dict = {}
if hasattr(region, 'block_entities'):
for be in region.block_entities:
try:
x, y, z = int(be['x']), int(be['y']), int(be['z'])
pos_key = f"[{x}, {y}, {z}]"
nbt_data = {}
for k, v in be.items():
if k not in ('x', 'y', 'z'):
nbt_data[k] = str(v)
be_dict[pos_key] = nbt_data
except Exception:
continue
be_chunks = chunk_block_entities(be_dict, limit=20000)
# ----------------------------------
# Теперь data состоит из 3 элементов: conv_data, block_palette, и be_chunks
LOAD_ANSWERS[uuid] = {
"data": [conv_data, schem_data["block_palette"], be_chunks],
"timestamp": time.time()
}
except Exception as e:
LOAD_ANSWERS[uuid] = {"error": str(e), "timestamp": time.time()}
finally:
with PROCESSING_LOCK:
PROCESSING.pop(uuid, None)
def cleanup_worker():
"""Удаляет записи старше 12 часов (43200 секунд)"""
while True:
time.sleep(60) # Проверка раз в минуту
current_time = time.time()
with PROCESSING_LOCK:
to_delete = [
uid for uid, val in LOAD_ANSWERS.items()
if current_time - val["timestamp"] > 43200
]
for uid in to_delete:
del LOAD_ANSWERS[uid]
def request_worker():
while True:
with PROCESSING_LOCK:
uuids = list(LOAD_REQUESTS.keys())
for uuid in uuids:
with PROCESSING_LOCK:
if uuid in LOAD_REQUESTS:
url = LOAD_REQUESTS.pop(uuid)
PROCESSING[uuid] = url
else:
continue
thread = threading.Thread(
target=process_schematic,
args=(uuid, url),
daemon=True
)
thread.start()
time.sleep(0.5)
worker_thread = threading.Thread(target=request_worker, daemon=True)
worker_thread.start()
cleanup_thread = threading.Thread(target=cleanup_worker, daemon=True)
cleanup_thread.start()
def gchar(index: int):
return BASE32_CHARS[index]
def generate_dynamic_key(index, base=32):
if index == 0:
return gchar(0)
chars = []
temp = index
while temp > 0:
chars.append(gchar(temp % base))
temp //= base
return ''.join(reversed(chars))
def gdata(schem):
block_palette = {}
data = {}
region = list(schem.regions.values())[0]
pos_x = region._Region__x
pos_y = region._Region__y
pos_z = region._Region__z
IGNORE_BLOCKS = [
"minecraft:air", "minecraft:cave_air", "minecraft:void_air"
]
FIX_BLOCKS = {
"minecraft:chain": "minecraft:iron_chain"
}
for x, y, z in region.block_positions():
block = region[x, y, z]
block_id = block.id
if block_id in IGNORE_BLOCKS:
continue
if block_id in FIX_BLOCKS.keys():
block_id = FIX_BLOCKS[block_id]
props = block.properties()
if props:
props_str = ",".join(f"{k}={v}" for k, v in sorted(props))
block_id = f"{block_id}[{props_str}]"
else:
block_id = f"{block_id}"
if block_id not in block_palette:
index = len(block_palette)
block_key = generate_dynamic_key(index)
block_palette[block_id] = block_key
else:
block_key = block_palette[block_id]
# x_chunk = gchar(((x + 512 + pos_x) % 1024) // 32)
# x_in_chunk = gchar(((x + 512 + pos_x) % 1024) % 32)
# y_chunk = gchar(((y + 512 + pos_y) % 1024) // 32)
# y_in_chunk = gchar(((y + 512 + pos_y) % 1024) % 32)
# z_chunk = gchar(((z + 512 + pos_z) % 1024) // 32)
# z_in_chunk = gchar(((z + 512 + pos_z) % 1024) % 32)
x_chunk = gchar(((x + 512) % 1024) // 32)
x_in_chunk = gchar(((x + 512) % 1024) % 32)
y_chunk = gchar(((y + 512) % 1024) // 32)
y_in_chunk = gchar(((y + 512) % 1024) % 32)
z_chunk = gchar(((z + 512) % 1024) // 32)
z_in_chunk = gchar(((z + 512) % 1024) % 32)
pos = f"{x_chunk}{x_in_chunk}{y_chunk}{y_in_chunk}{z_chunk}{z_in_chunk}"
if block_key not in data:
data[block_key] = []
data[block_key].append(pos)
block_palette = {v: k for k, v in block_palette.items()}
return {"data": data, "block_palette": block_palette}
def cdata(data):
def cut_list(lst, min_index, max_index):
cut_part = lst[min_index:max_index + 1]
remaining = lst[:min_index] + lst[max_index + 1:]
return [cut_part, remaining]
new_data = [[]]
for k, v in data.items():
while True:
need = (19_950-len("".join(new_data[-1])))//7
cut, v = cut_list(v, 0, need)
poses = "/".join(cut) + "/"
new_data[-1].append(k + ":" + poses + "|")
if 19_950-len("".join(new_data[-1])) < 7:
new_data.append([])
if not(v):
break
for i, v in enumerate(new_data):
data = new_data[i].copy()
new_data[i] = "".join(data)
return new_data
def zdata(cdata):
if isinstance(cdata, str):
cdata = cdata.encode('utf-8')
compressed = zlib.compress(cdata)
return base64.b64encode(compressed).decode('utf-8')
@app.route('/load', methods=['POST'])
def load_schematic():
try:
data = request.get_json()
if "url" not in data.keys():
return jsonify({"error": "need url"}), 400
url = data.get("url")
if not url.startswith(('http://', 'https://')):
return jsonify({"error": "invalid URL scheme"}), 400
uuid_str = base64.urlsafe_b64encode(url.encode('utf-8')).decode('utf-8')
if not(uuid_str in LOAD_REQUESTS or uuid_str in LOAD_ANSWERS or uuid_str in PROCESSING):
LOAD_REQUESTS[uuid_str] = url
return jsonify({"uuid": uuid_str})
except Exception as e:
return jsonify({"error": str(e)}), 500
@app.route('/get/<uuid>/<int:index>', methods=['GET'])
def get_result(uuid, index):
try:
if not uuid:
return jsonify({"error": "need uuid"}), 400
if uuid in LOAD_REQUESTS or uuid in PROCESSING:
return jsonify({"status": "processing"})
elif uuid in LOAD_ANSWERS:
entry = LOAD_ANSWERS[uuid]
if "error" in entry:
return jsonify({"error": entry["error"]}), 500
result = entry["data"][0]
if index is not None:
try:
index = int(index)
max_index = len(result)-1
part = result[index]
compressed_part = zdata(part)
return jsonify({"p": max_index, "d": compressed_part})
except ValueError:
return jsonify({"error": "index must be integer"}), 400
except Exception as e:
return jsonify({"error": f"Slice error: {str(e)}"}), 500
else:
return jsonify({"error": "uuid not found"}), 404
except Exception as e:
return jsonify({"error": f"Server error: {str(e)}"}), 500
@app.route('/get_palette/<uuid>/<int:index>', methods=['GET'])
def get_palette(uuid, index=None):
try:
if not uuid:
return jsonify({"error": "need uuid"}), 400
if uuid in LOAD_REQUESTS or uuid in PROCESSING:
return jsonify({"status": "processing"})
elif uuid in LOAD_ANSWERS:
entry = LOAD_ANSWERS[uuid]
if "error" in entry:
return jsonify({"error": entry["error"]}), 500
result = entry["data"][1]
if index is not None:
try:
items = list(result.items())
max_index = (len(items) - 1) // 200
start = 200 * index
end = 200 * (index + 1)
sliced = dict(items[start:end])
return jsonify({"p": max_index, "d": sliced})
except Exception as e:
return jsonify({"error": f"Slice error: {str(e)}"}), 500
else:
return jsonify({"error": "uuid not found"}), 404
except Exception as e:
return jsonify({"error": f"Server error: {str(e)}"}), 500
@app.route('/entity_block/<uuid>/<int:index>', methods=['GET'])
def get_entity_block(uuid, index):
try:
if not uuid:
return jsonify({"error": "need uuid"}), 400
if uuid in LOAD_REQUESTS or uuid in PROCESSING:
return jsonify({"status": "processing"})
elif uuid in LOAD_ANSWERS:
entry = LOAD_ANSWERS[uuid]
if "error" in entry:
return jsonify({"error": entry["error"]}), 500
# Блоки-сущности сохранены под третьим индексом в массиве data
be_chunks = entry["data"][2]
if index is not None:
try:
index = int(index)
max_index = len(be_chunks) - 1
if index < 0 or index > max_index:
return jsonify({"error": "index out of range"}), 400
part = be_chunks[index]
part_bytes = json.dumps(part, ensure_ascii=False, separators=(',', ':')).encode('utf-8')
compressed_part = base64.b64encode(zlib.compress(part_bytes)).decode('utf-8')
return jsonify({"p": max_index, "d": compressed_part})
except ValueError:
return jsonify({"error": "index must be integer"}), 400
except Exception as e:
return jsonify({"error": f"Slice error: {str(e)}"}), 500
else:
return jsonify({"error": "uuid not found"}), 404
except Exception as e:
return jsonify({"error": f"Server error: {str(e)}"}), 500
@app.route('/del/<uuid>', methods=['DELETE'])
def delete(uuid):
try:
if not uuid:
return jsonify({"error": "need uuid"}), 400
deleted = False
with PROCESSING_LOCK:
if uuid in LOAD_REQUESTS:
del LOAD_REQUESTS[uuid]
deleted = True
if uuid in PROCESSING:
del PROCESSING[uuid]
deleted = True
if uuid in LOAD_ANSWERS:
del LOAD_ANSWERS[uuid]
deleted = True
if deleted:
return jsonify({"status": "deleted", "uuid": uuid})
else:
return jsonify({"error": "uuid not found"}), 404
except Exception as e:
return jsonify({"error": f"Server error: {str(e)}"}), 500
if __name__ == "__main__":
app.run(host="0.0.0.0", port=7860)