teste upload
This commit is contained in:
1 parent
60f64fb996
commit
c850ab1ef1
14 files changed
+174161
-169852
No files matched your search
Binary file not shown.
@@ -1,6 +1,7 @@
|
||||
# main.py
|
||||
|
||||
import os
|
||||
import json
|
||||
import shutil
|
||||
import subprocess
|
||||
import multiprocessing
|
||||
@@ -274,5 +275,43 @@ def main_parallel():
|
||||
pass # Erro já logado na função ou irrelevante se arquivos não existirem
|
||||
|
||||
|
||||
def rebuild_indexes():
|
||||
"""
|
||||
Função auxiliar para regerar all.json e all.yml baseada nos arquivos processados.
|
||||
Pode ser chamada pela API após um upload.
|
||||
"""
|
||||
logging.info("Regerando índices globais (all.json / all.yml)...")
|
||||
|
||||
# Lista todos os JSONs individuais na pasta metadata (exceto os manifestos e o all.json)
|
||||
all_data = []
|
||||
ignored_files = [
|
||||
"all.json",
|
||||
"samples-manifest.json",
|
||||
"mmp-manifest.json",
|
||||
"dependency_report.json",
|
||||
]
|
||||
|
||||
if os.path.exists(METADATA_FOLDER):
|
||||
for f in os.listdir(METADATA_FOLDER):
|
||||
if f.endswith(".json") and f not in ignored_files:
|
||||
try:
|
||||
with open(
|
||||
os.path.join(METADATA_FOLDER, f), "r", encoding="utf-8"
|
||||
) as json_file:
|
||||
data = json.load(
|
||||
json_file
|
||||
) # Precisa importar json no topo se não tiver
|
||||
all_data.append(data)
|
||||
except Exception as e:
|
||||
logging.error(f"Erro ao ler {f} para índice global: {e}")
|
||||
|
||||
if all_data:
|
||||
save_to_json(all_data, os.path.join(METADATA_FOLDER, "all.json"))
|
||||
save_to_yaml(all_data, os.path.join(DATA_FOLDER, "all.yml"))
|
||||
logging.info("Índices globais atualizados com sucesso.")
|
||||
|
||||
return len(all_data)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main_parallel()
|
||||
@@ -0,0 +1,94 @@
|
||||
import os
|
||||
from flask import Flask, request, jsonify
|
||||
from flask_cors import CORS
|
||||
from werkzeug.utils import secure_filename
|
||||
|
||||
# Importa suas funções e configurações existentes
|
||||
from main import process_single_file, rebuild_indexes
|
||||
from utils import MMP_FOLDER, MMPZ_FOLDER
|
||||
|
||||
app = Flask(__name__)
|
||||
CORS(app) # Permite que o HTML converse com o servidor
|
||||
|
||||
# Configurações de extensão
|
||||
ALLOWED_EXTENSIONS = {"mmp", "mmpz"}
|
||||
|
||||
|
||||
def allowed_file(filename):
|
||||
return "." in filename and filename.rsplit(".", 1)[1].lower() in ALLOWED_EXTENSIONS
|
||||
|
||||
|
||||
@app.route("/api/upload", methods=["POST"])
|
||||
def upload_file():
|
||||
# 1. Verificações Básicas
|
||||
if "project_file" not in request.files:
|
||||
return jsonify({"error": "Nenhum arquivo enviado"}), 400
|
||||
|
||||
file = request.files["project_file"]
|
||||
|
||||
if file.filename == "":
|
||||
return jsonify({"error": "Nome do arquivo vazio"}), 400
|
||||
|
||||
if file and allowed_file(file.filename):
|
||||
filename = secure_filename(file.filename)
|
||||
|
||||
# 2. Define onde salvar (MMP ou MMPZ)
|
||||
if filename.endswith(".mmpz"):
|
||||
save_path = os.path.join(MMPZ_FOLDER, filename)
|
||||
else:
|
||||
save_path = os.path.join(MMP_FOLDER, filename)
|
||||
|
||||
# Salva o arquivo físico
|
||||
try:
|
||||
file.save(save_path)
|
||||
print(f"Arquivo salvo em: {save_path}")
|
||||
except Exception as e:
|
||||
return jsonify({"error": f"Falha ao salvar disco: {str(e)}"}), 500
|
||||
|
||||
# 3. DISPARA SEU PIPELINE (Processamento)
|
||||
# Chama a função do seu main.py para gerar WAV e extrair dados
|
||||
result = process_single_file(filename)
|
||||
|
||||
if result["success"]:
|
||||
# 4. Atualiza o site.data.all (all.json)
|
||||
rebuild_indexes()
|
||||
|
||||
return jsonify(
|
||||
{"message": "Projeto processado com sucesso!", "data": result["data"]}
|
||||
), 200
|
||||
else:
|
||||
return jsonify({"error": f"Erro no processamento: {result['error']}"}), 500
|
||||
|
||||
return jsonify({"error": "Tipo de arquivo não permitido"}), 400
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
print("Iniciando Servidor de Upload MMP...")
|
||||
|
||||
# Tenta localizar os certificados reais do servidor (Comum em servidores Linux/Apache/Nginx)
|
||||
# Ajuste esses caminhos se souber onde os certificados do alice.ufsj.edu.br estão
|
||||
cert_path = "/etc/letsencrypt/live/alice.ufsj.edu.br/fullchain.pem"
|
||||
key_path = "/etc/letsencrypt/live/alice.ufsj.edu.br/privkey.pem"
|
||||
|
||||
# Opção 1: Usar certificado real (O ideal - Navegador aceita de primeira)
|
||||
if os.path.exists(cert_path) and os.path.exists(key_path):
|
||||
print("Certificados encontrados! Rodando HTTPS seguro na porta 33002.")
|
||||
context = (cert_path, key_path)
|
||||
# Use host='0.0.0.0' para garantir que escute externamente
|
||||
app.run(host="0.0.0.0", port=33002, ssl_context=context, debug=True)
|
||||
|
||||
# Opção 2: Modo 'adhoc' (Certificado temporário gerado na hora)
|
||||
else:
|
||||
print(
|
||||
"Certificados reais não encontrados. Usando modo 'adhoc' (Auto-assinado)."
|
||||
)
|
||||
print(
|
||||
"ATENÇÃO: O navegador vai avisar que 'Não é seguro'. Você precisará autorizar."
|
||||
)
|
||||
# Requer: pip install pyopenssl
|
||||
try:
|
||||
app.run(host="0.0.0.0", port=33002, ssl_context="adhoc", debug=True)
|
||||
except Exception as e:
|
||||
print(f"Erro ao iniciar SSL adhoc: {e}")
|
||||
print("Tentando rodar em HTTP simples (pode dar erro de Mixed Content)...")
|
||||
app.run(host="0.0.0.0", port=33002, debug=True)
|
||||
Reference in new issue
Block a user