Repository navigation
Expand file tree
/
Copy pathapp.py
More file actions
240 lines (196 loc) · 6.56 KB
/
Copy pathapp.py
File metadata and controls
240 lines (196 loc) · 6.56 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
"""
MarketVision — Flask-приложение для генерации карточек маркетплейса.
Фото → Vision (ProxyAPI) → GigaChat (текст) → GPT-Image (ProxyAPI).
"""
import os
import threading
import time
import uuid
from pathlib import Path
from dotenv import load_dotenv
from flask import Flask, jsonify, render_template, request, send_from_directory, send_file
from werkzeug.utils import secure_filename
from core.config import (
MARKETPLACES,
OUTPUTS_DIR,
TONES,
VISUAL_STYLES,
new_task_dir,
refresh_env,
telegram_configured,
)
from core.pipeline import run_marketvision_pipeline
from core.telegram_send import send_card_json, send_result_to_telegram
load_dotenv()
refresh_env()
app = Flask(__name__)
app.config["SECRET_KEY"] = os.getenv("FLASK_SECRET_KEY", os.urandom(24).hex())
app.config["MAX_CONTENT_LENGTH"] = 8 * 1024 * 1024 # 8 MB
ALLOWED_EXTENSIONS = {".jpg", ".jpeg", ".png", ".webp"}
tasks_status: dict[str, dict] = {}
tasks_lock = threading.Lock()
def allowed_file(filename: str) -> bool:
return Path(filename).suffix.lower() in ALLOWED_EXTENSIONS
def update_task(task_id: str, **fields) -> None:
with tasks_lock:
tasks_status.setdefault(task_id, {})
tasks_status[task_id].update(fields)
def process_task(
task_id: str,
image_path: Path,
category: str,
tone: str,
marketplace: str,
visual_style: str,
extra_notes: str,
) -> None:
try:
refresh_env()
update_task(
task_id,
status="processing",
progress=5,
message="Старт пайплайна…",
)
def on_progress(percent: int, message: str) -> None:
update_task(
task_id,
status="processing",
progress=percent,
message=message,
)
result = run_marketvision_pipeline(
task_id=task_id,
image_path=image_path,
category=category,
tone=tone,
marketplace=marketplace,
visual_style=visual_style,
extra_notes=extra_notes,
on_progress=on_progress,
)
update_task(
task_id,
status="completed",
progress=100,
message="Готово!",
result=result,
)
except Exception as exc:
update_task(
task_id,
status="error",
progress=0,
message=str(exc),
)
@app.route("/")
def index():
refresh_env()
return render_template(
"index.html",
visual_styles=VISUAL_STYLES,
marketplaces=MARKETPLACES,
tones=TONES,
telegram_enabled=telegram_configured(),
)
@app.route("/api/generate", methods=["POST"])
def api_generate():
if "image" not in request.files:
return jsonify({"error": "Загрузите фото товара"}), 400
file = request.files["image"]
if not file.filename:
return jsonify({"error": "Файл не выбран"}), 400
if not allowed_file(file.filename):
return jsonify({"error": "Допустимы JPG, PNG, WEBP"}), 400
category = request.form.get("category", "").strip()
tone = request.form.get("tone", "business")
marketplace = request.form.get("marketplace", "universal")
visual_style = request.form.get("visual_style", "lifestyle")
extra_notes = request.form.get("extra_notes", "").strip()
task_id = f"{int(time.time() * 1000)}_{uuid.uuid4().hex[:8]}"
task_dir = new_task_dir(task_id)
ext = Path(secure_filename(file.filename)).suffix.lower() or ".jpg"
input_path = task_dir / f"input{ext}"
file.save(input_path)
update_task(
task_id,
status="queued",
progress=0,
message="Задача в очереди…",
)
thread = threading.Thread(
target=process_task,
args=(
task_id,
input_path,
category,
tone,
marketplace,
visual_style,
extra_notes,
),
daemon=True,
)
thread.start()
return jsonify({"task_id": task_id})
@app.route("/api/status/<task_id>")
def api_status(task_id: str):
with tasks_lock:
task = tasks_status.get(task_id)
if not task:
return jsonify({"error": "Задача не найдена"}), 404
return jsonify(task)
@app.route("/api/telegram/<task_id>", methods=["POST"])
def api_telegram(task_id: str):
with tasks_lock:
task = tasks_status.get(task_id)
if not task or task.get("status") != "completed":
return jsonify({"error": "Сначала дождитесь завершения генерации"}), 400
if not telegram_configured():
return jsonify(
{
"error": "Добавьте TELEGRAM_BOT_TOKEN и TELEGRAM_CHAT_ID в .env",
}
), 400
task_dir = OUTPUTS_DIR / task_id
card = task.get("result", {}).get("card", {})
if not card and (task_dir / "card.json").exists():
import json
card = json.loads((task_dir / "card.json").read_text(encoding="utf-8"))
try:
tg_response = send_result_to_telegram(task_dir, card)
send_card_json(task_dir)
return jsonify({"ok": True, "telegram": tg_response})
except Exception as exc:
return jsonify({"error": str(exc)}), 500
@app.route("/outputs/<task_id>/<path:filename>")
def serve_output(task_id: str, filename: str):
directory = OUTPUTS_DIR / task_id
if not directory.exists():
return jsonify({"error": "Не найдено"}), 404
return send_from_directory(directory, filename)
@app.route("/api/download/<task_id>/card")
def download_card(task_id: str):
path = OUTPUTS_DIR / task_id / "card.md"
if not path.is_file():
return jsonify({"error": "card.md не найден"}), 404
return send_file(
path,
as_attachment=True,
download_name=f"marketvision_{task_id}_card.md",
mimetype="text/markdown; charset=utf-8",
)
@app.route("/api/download/<task_id>/image")
def download_image(task_id: str):
path = OUTPUTS_DIR / task_id / "generated.png"
if not path.is_file():
return jsonify({"error": "Изображение не найдено"}), 404
return send_file(
path,
as_attachment=True,
download_name=f"marketvision_{task_id}_visual.png",
mimetype="image/png",
)
if __name__ == "__main__":
port = int(os.getenv("FLASK_PORT", "5000"))
app.run(debug=True, host="0.0.0.0", port=port)