کد منبع بخش لاغری
این صفحه همین الان فایلهای اجراشده روی سرور را میخواند و بدون کامنت نشان میدهد. اثر انگشت SHA-256 هر فایل هم کنارش است.
چه چیزی را بررسی کنید؟
- در هیچکدام از این فایلها نوشتن روی دیسک، پایگاهداده یا کش برای عکس/نتیجه وجود ندارد؛ تنها نوشتنهای پایگاهداده در
routes/body.pyکسر/بازگشت اعتبار، ثبت رخداد سادهی «موفق/ناموفق»، ثبت تأیید اطلاعیه و قفل ضد دوبار-کلیک است (reserve_credit،refund_credit،audit،record_acceptance،try_acquire_generation_lock/release_generation_lock)؛ هیچکدام عکس، نتیجه، قد یا وزن نمیگیرند. memory_upload.py: فایلهای بارگذاریشده برای مسیرهای/body/فقط در حافظه (BytesIO) نگه داشته میشوند، نه فایل موقتِ دیسک.body_preview.py: عکس پس از پاکشدن متادیتا فقط به آدرس HTTPS سرویس هوش مصنوعی فرستاده میشود؛ نتیجه بهصورت متن base64 در همان پاسخ برمیگردد.body.js: نتیجه فقط داخل صفحه نمایش داده میشود و با «پاکسازی» یا بستن صفحه از بین میرود.
محدودیت صادقانه: نمایش کد، اثبات ریاضی اجرای همین کد نیست و زیرساخت (سیستمعامل، پروکسی، سرویس هوش مصنوعی) خارج از این فایلهاست؛ اما هر کسی میتواند رفتار کد را مستقل بررسی کند.
app/memory_upload.py
۱۰ خطsha256(file) = 674ec81de1eaeae19e742522748360732b8c3b2e725607e817a3514ca3015555
sha256(shown) = 674ec81de1eaeae19e742522748360732b8c3b2e725607e817a3514ca3015555
import io
from flask import Request
class MemoryUploadRequest(Request):
def _get_file_stream(self, total_content_length, content_type, filename=None, content_length=None):
if self.path.startswith("/body/"):
return io.BytesIO()
return super()._get_file_stream(total_content_length, content_type, filename, content_length)
app/services/body_preview.py
۳۴۳ خطsha256(file) = 51f5da50c284a15577869cbef73089a4ad64a7f7ca40a1f807fe5dff09b6daa0
sha256(shown) = 51f5da50c284a15577869cbef73089a4ad64a7f7ca40a1f807fe5dff09b6daa0
from __future__ import annotations
import base64
import json
import logging
import threading
import time
from urllib.parse import urlsplit
import httpx
import config
from app.services import ai, imaging
log = logging.getLogger(__name__)
MESSAGES = {
"format": "فایل ارسالی یک عکس معتبر (JPG، PNG یا WEBP) نیست.",
"heic": "فرمت HEIC روی این سرور پشتیبانی نمیشود؛ عکس را JPG کنید.",
"too_small": "عکس خیلی کوچک است؛ عکسی با کیفیت بالاتر انتخاب کنید.",
"too_large": "ابعاد عکس بیش از حد بزرگ است.",
"broken": "فایل عکس خراب است یا کامل آپلود نشده؛ دوباره تلاش کنید.",
"shape": "عکس باید عمودی و تمامقد (روبهرو، از سر تا حداقل زانو) باشد.",
"height": "قد باید بین ۱۴۰ تا ۲۲۰ سانتیمتر باشد.",
"weight": "وزن باید بین ۴۰ تا ۲۵۰ کیلوگرم باشد.",
"loss": "مقدار کاهش وزن انتخابشده معتبر نیست.",
"bmi_low": "با توجه به قد و وزن واردشده نیازی به کاهش وزن دیده نمیشود؛ برای حفظ سلامت، پیشنمایش لاغری ارائه نمیشود.",
"no_choice": "با قد و وزن واردشده هیچکدام از گزینههای کاهش وزن ایمن نیست؛ پیشنمایش ساخته نمیشود.",
"unusable": "این عکس برای تحلیل مناسب نیست؛ یک عکس روبهرو و تمامقد از یک بزرگسال با لباس زیر یا لباس ورزشی چسبان بگیرید.",
"refused": "تحلیل این عکس انجام نشد؛ یک عکس روبهرو و تمامقد با لباس زیر یا لباس ورزشی چسبان امتحان کنید.",
"timeout": "پاسخ سرویس هوش مصنوعی طول کشید؛ اعتبار شما برگشت داده شد. دوباره تلاش کنید.",
"rate_limit": "سرویس هوش مصنوعی شلوغ است؛ اعتبار شما برگشت داده شد. کمی بعد تلاش کنید.",
"auth": "سرویس هوش مصنوعی بهدرستی پیکربندی نشده است. با پشتیبانی تماس بگیرید.",
"content_policy": "سرویس هوش مصنوعی این عکس را نپذیرفت؛ عکسی با لباس زیر یا لباس ورزشی چسبان و نور یکنواخت امتحان کنید.",
"api_quota": "اعتبار سرویس هوش مصنوعی به پایان رسیده است. با پشتیبانی تماس بگیرید.",
"network": "اتصال به سرویس هوش مصنوعی برقرار نشد؛ اعتبار شما برگشت داده شد.",
"model": "مدل هوش مصنوعی این بخش در دسترس نیست. با پشتیبانی تماس بگیرید.",
"insecure": "آدرس سرویس هوش مصنوعی امن (HTTPS) نیست؛ برای حفاظت از عکس، ارسال انجام نشد.",
"busy": "سرور در حال پردازش چند درخواست دیگر است؛ چند لحظه بعد دوباره تلاش کنید.",
"cancelled": "درخواست لغو شد.",
"unknown": "ساخت پیشنمایش ناموفق بود؛ اعتبار شما برگشت داده شد. دوباره تلاش کنید.",
}
BMI_LABELS = (
(18.5, "کموزن"),
(25.0, "محدودهی نرمال"),
(30.0, "اضافهوزن"),
(999.0, "چاقی"),
)
SYSTEM_PROMPT = (
"You assess body shape for a weight-management clinic. You receive one front-view photo of an adult "
"in underwear or sportswear, with height and weight. "
"First decide if the photo is usable. Set usable=false and give a short Persian reason if: it is not a single "
"standing person shown from the front, head to at least the knees; the person looks under 18; "
"the person is fully nude; or it is not a real photo of a person. "
"If usable, write a respectful, professional assessment in Persian based only on what is visible. "
"Never shame, never diagnose diseases, never comment on sexual features. "
"Answer ONLY with JSON: "
'{"usable":true,"reason":"","body_type":"","summary":"","areas":[{"region":"","finding":"","level":1}],'
'"posture":"","tips":[""]}. '
"areas: at most 6 regions with notable excess weight or shape imbalance "
"(shoulders and upper back, arms, chest line, waist and abdomen, flanks, hips, thighs, knees); "
"level 1 mild, 2 moderate, 3 marked. "
"body_type: one Persian label (apple, pear, rectangle, hourglass or inverted triangle) plus a short note. "
"posture: shoulders, spine, pelvis and symmetry as visible. tips: at most 4 short practical lifestyle tips."
)
LEVEL_WORDS = {1: "slightly slimmer", 2: "noticeably slimmer", 3: "clearly slimmer", 4: "much slimmer"}
_slots = threading.BoundedSemaphore(max(1, int(config.BODY_MAX_PARALLEL)))
class BodyError(Exception):
def __init__(self, key: str, message: str | None = None, status: int = 400, charge: bool = False):
self.key = key
self.message = message or MESSAGES.get(key, MESSAGES["unknown"])
self.status = status
self.charge = charge
super().__init__(self.message)
def acquire_slot() -> bool:
return _slots.acquire(blocking=False)
def release_slot() -> None:
try:
_slots.release()
except ValueError:
pass
def bmi(height_cm: float, weight_kg: float) -> float:
meters = height_cm / 100.0
return weight_kg / (meters * meters)
def bmi_label(value: float) -> str:
for limit, label in BMI_LABELS:
if value < limit:
return label
return BMI_LABELS[-1][1]
def parse_measurements(height_raw, weight_raw) -> tuple[float, float]:
try:
height = float(str(height_raw).replace(",", ".").strip())
except (TypeError, ValueError):
raise BodyError("height")
try:
weight = float(str(weight_raw).replace(",", ".").strip())
except (TypeError, ValueError):
raise BodyError("weight")
if not 140 <= height <= 220:
raise BodyError("height")
if not 40 <= weight <= 250:
raise BodyError("weight")
return height, weight
def allowed_losses(height: float, weight: float) -> list[int]:
result = []
for kg in config.BODY_LOSS_CHOICES:
if kg > weight * float(config.BODY_MAX_LOSS_PERCENT) / 100.0:
continue
if bmi(height, weight - kg) < float(config.BODY_MIN_RESULT_BMI):
continue
result.append(int(kg))
return result
def check_eligibility(height: float, weight: float, kg: int) -> None:
if bmi(height, weight) < float(config.BODY_MIN_BMI):
raise BodyError("bmi_low")
choices = allowed_losses(height, weight)
if not choices:
raise BodyError("no_choice")
if kg not in choices:
raise BodyError("loss")
def load_photo(data: bytes):
if not data:
raise BodyError("broken")
if len(data) > int(config.BODY_MAX_UPLOAD_MB) * 1024 * 1024:
raise BodyError("too_large", f"حجم عکس بیشتر از {config.BODY_MAX_UPLOAD_MB} مگابایت است.")
try:
img = imaging.load_upload(data)
except imaging.UploadError as err:
raise BodyError(err.reason if err.reason in MESSAGES else "broken")
width, height = img.size
if height < 640:
raise BodyError("too_small")
if height < width * 1.2:
raise BodyError("shape")
return img
def _require_secure_endpoint() -> None:
base = str(config.AI_BASE_URL or "")
host = urlsplit(base).hostname or ""
if base.startswith("https://") or host in ("127.0.0.1", "localhost"):
return
raise BodyError("insecure")
def _clean(value, limit: int) -> str:
return " ".join(str(value or "").split())[:limit]
def _extract_json(text: str) -> dict:
text = (text or "").strip()
start, end = text.find("{"), text.rfind("}")
if start == -1 or end <= start:
raise BodyError("refused")
try:
data = json.loads(text[start:end + 1])
except ValueError:
raise BodyError("refused")
if not isinstance(data, dict):
raise BodyError("refused")
return data
def sanitize_analysis(data: dict) -> dict:
usable = data.get("usable")
if isinstance(usable, str):
usable = usable.strip().lower() == "true"
if usable is not True:
reason = _clean(data.get("reason"), 200)
raise BodyError("unusable", reason or None)
areas = []
for item in (data.get("areas") or [])[:6]:
if not isinstance(item, dict):
continue
region, finding = _clean(item.get("region"), 40), _clean(item.get("finding"), 200)
try:
level = int(item.get("level") or 1)
except (TypeError, ValueError):
level = 1
if region and finding:
areas.append({"region": region, "finding": finding, "level": min(3, max(1, level))})
tips = [_clean(t, 160) for t in (data.get("tips") or [])[:4] if _clean(t, 160)]
result = {
"body_type": _clean(data.get("body_type"), 120),
"summary": _clean(data.get("summary"), 500),
"areas": areas,
"posture": _clean(data.get("posture"), 300),
"tips": tips,
}
if not result["summary"] and not result["areas"]:
raise BodyError("refused")
return result
def _post_chat(payload: dict, timeout: float) -> dict:
http, _ = ai._get_http_client()
try:
resp = http.post(
ai._api_url("chat/completions"),
headers={"Authorization": f"Bearer {config.AI_API_KEY}", "Accept": "application/json"},
json=payload,
timeout=httpx.Timeout(timeout, connect=min(5.0, timeout), pool=min(5.0, timeout)),
)
except httpx.TimeoutException as exc:
raise TimeoutError("timeout") from exc
finally:
try:
http.close()
except Exception:
pass
if resp.status_code >= 400:
try:
body = resp.json()
detail = body.get("error", body)
except Exception:
detail = resp.text[:300]
exc = RuntimeError(f"AI HTTP {resp.status_code}: {detail}")
setattr(exc, "status_code", resp.status_code)
raise exc
return resp.json()
def _map_ai_error(exc: Exception) -> BodyError:
key = ai.classify_error(exc)
return BodyError(key if key in MESSAGES else "unknown")
def analyze(photo_jpeg: bytes, height: float, weight: float) -> dict:
_require_secure_endpoint()
if not config.AI_API_KEY:
raise BodyError("auth")
value = bmi(height, weight)
text = f"Height {height:.0f} cm, weight {weight:.0f} kg, BMI {value:.1f}. Analyze this photo."
url = "data:image/jpeg;base64," + base64.b64encode(photo_jpeg).decode("ascii")
payload = {
"model": config.BODY_ANALYSIS_MODEL,
"messages": [
{"role": "system", "content": SYSTEM_PROMPT},
{"role": "user", "content": [
{"type": "text", "text": text},
{"type": "image_url", "image_url": {"url": url, "detail": "high"}},
]},
],
"response_format": {"type": "json_object"},
}
timeout = float(config.BODY_ANALYSIS_TIMEOUT)
try:
try:
reply = _post_chat(payload, timeout)
except RuntimeError as exc:
status = getattr(exc, "status_code", 0)
if status in (400, 422) and "response_format" in str(exc):
payload.pop("response_format", None)
reply = _post_chat(payload, timeout)
else:
raise
choices = reply.get("choices") or []
content = ((choices[0] or {}).get("message") or {}).get("content") if choices else ""
except BodyError:
raise
except Exception as exc:
raise _map_ai_error(exc)
return sanitize_analysis(_extract_json(content if isinstance(content, str) else ""))
def edit_prompt(kg: int) -> str:
level = LEVEL_WORDS[1] if kg < 4 else LEVEL_WORDS[2] if kg < 7 else LEVEL_WORDS[3] if kg < 10 else LEVEL_WORDS[4]
return (
f"Edit this photo to show how this same person would look after losing about {kg} kg: "
f"{level} waist, abdomen, hips, thighs and arms, in natural proportion, with smoother body contours. "
"Realistic, natural result. Keep the face, identity, skin tone, hair, underwear or clothing, pose, "
"lighting and background exactly the same. Do not add or remove clothing. Change nothing else."
)
def render_after(img, kg: int) -> bytes:
_require_secure_endpoint()
if getattr(config, "AI_SQUARE_PAD", True):
model_input, box = imaging.square_pad(img)
else:
model_input, box = img, (0, 0, img.width, img.height)
payload = imaging.encode_jpeg(model_input, 90)
deadline = time.monotonic() + float(config.AI_TIMEOUT_SECONDS)
try:
raw = ai._call_edit_sync([payload], edit_prompt(kg), config.AI_IMAGE_QUALITY, config.AI_IMAGE_SIZE, deadline)
except Exception as exc:
raise _map_ai_error(exc)
try:
out = imaging.open_bytes(raw)
if getattr(config, "AI_SQUARE_PAD", True):
out = imaging.unpad_result(out, box, model_input.width, img.size)
elif out.size != img.size:
out = out.resize(img.size)
return imaging.encode_jpeg(out, 88)
except Exception:
raise BodyError("unknown")
def run(img, height: float, weight: float, kg: int, cancel: threading.Event, state: dict) -> dict:
check_eligibility(height, weight, kg)
analysis = analyze(imaging.encode_jpeg(img, 88), height, weight)
if cancel.is_set():
raise BodyError("cancelled")
state["edit_started"] = True
after = render_after(img, kg)
current = bmi(height, weight)
target = bmi(height, weight - kg)
return {
"analysis": analysis,
"after": base64.b64encode(after).decode("ascii"),
"mime": "image/jpeg",
"stats": {
"kg": int(kg),
"weight": round(weight, 1),
"target_weight": round(weight - kg, 1),
"bmi": round(current, 1),
"bmi_label": bmi_label(current),
"target_bmi": round(target, 1),
"target_bmi_label": bmi_label(target),
},
}
app/routes/body.py
۲۱۹ خطsha256(file) = 2b7feed06fd8b84c55f947fbc2ca954f9640dd52a253e76adeb17fe53392b502
sha256(shown) = 2b7feed06fd8b84c55f947fbc2ca954f9640dd52a253e76adeb17fe53392b502
from __future__ import annotations
import json
import logging
import threading
from flask import (Blueprint, Response, abort, flash, jsonify, make_response, redirect, render_template, request,
stream_with_context, url_for)
import config
from app import auth, repo
from app.services import body_preview, ratelimit, source_view
bp = Blueprint("body", __name__, url_prefix="/body")
log = logging.getLogger(__name__)
NO_STORE = "no-store, private, max-age=0"
ALLOWED_EXT = {".jpg", ".jpeg", ".png", ".webp", ".heic", ".heif"}
def _enabled() -> bool:
return bool(config.BODY_FEATURE_ENABLED)
def _accepted(user) -> bool:
return repo.has_accepted(user["id"], "body", config.BODY_NOTICE_VERSION, auth.client_ip())
def _error(message: str, status: int, key: str = "error"):
response = jsonify({"ok": False, "error": message, "key": key})
response.status_code = status
response.headers["Cache-Control"] = NO_STORE
return response
def _preflight(user):
if repo.is_expired(user):
return "اشتراک حساب شما به پایان رسیده است.", 403
if not config.AI_API_KEY:
return "سرویس هوش مصنوعی هنوز پیکربندی نشده است.", 503
cost = int(config.BODY_CREDIT_COST)
if not repo.is_unlimited(user) and cost > 0 and repo.credits_left(user) < cost:
return "اعتبار شما برای این بخش کافی نیست. برای شارژ حساب با پشتیبانی تماس بگیرید.", 402
return None
@bp.get("/")
@auth.login_required
def index():
if not _enabled():
abort(404)
user = auth.current_user()
if not _accepted(user):
return redirect(url_for("body.notice"))
response = make_response(render_template(
"body/index.html",
credits_left=repo.credits_left(user),
unlimited=repo.is_unlimited(user),
cost=int(config.BODY_CREDIT_COST),
loss_choices=list(config.BODY_LOSS_CHOICES),
min_bmi=float(config.BODY_MIN_BMI),
min_result_bmi=float(config.BODY_MIN_RESULT_BMI),
max_loss_percent=int(config.BODY_MAX_LOSS_PERCENT),
max_mb=int(config.BODY_MAX_UPLOAD_MB),
))
response.headers["Cache-Control"] = NO_STORE
return response
@bp.get("/notice")
def notice():
if not _enabled():
abort(404)
user = auth.current_user()
can_accept = bool(user) and not _accepted(user)
return render_template("body/notice.html", can_accept=can_accept, logged_in=bool(user),
version=config.BODY_NOTICE_VERSION, updated=config.PRIVACY_UPDATED_FA,
cost=int(config.BODY_CREDIT_COST), min_bmi=float(config.BODY_MIN_BMI),
min_result_bmi=float(config.BODY_MIN_RESULT_BMI),
max_loss_percent=int(config.BODY_MAX_LOSS_PERCENT))
@bp.post("/notice")
@auth.login_required
def notice_accept():
if not _enabled():
abort(404)
user = auth.current_user()
if request.form.get("agree") != "1":
flash("برای ادامه باید اطلاعیه را بخوانید و تأیید کنید.", "error")
return redirect(url_for("body.notice"))
ip = auth.client_ip()
repo.record_acceptance(user["id"], "body", config.BODY_NOTICE_VERSION, ip)
repo.audit(user["id"], user["username"], "body_notice_accept", config.BODY_NOTICE_VERSION, ip)
return redirect(url_for("body.index"))
@bp.get("/source")
def source():
if not _enabled():
abort(404)
return render_template("body/source.html", files=source_view.published_files(),
version=config.BODY_NOTICE_VERSION)
@bp.post("/preview")
@auth.login_required
def preview():
if not _enabled():
return _error("این بخش غیرفعال است.", 404)
user = auth.current_user()
ip = auth.client_ip()
if not _accepted(user):
return _error("ابتدا اطلاعیهی حریم خصوصی این بخش را بپذیرید.", 403, "notice")
problem = _preflight(user)
if problem:
return _error(problem[0], problem[1])
if not ratelimit.check_upload(user["id"]).allowed:
return _error("تعداد درخواستهای شما در این بازه زیاد است؛ کمی صبر کنید و دوباره تلاش کنید.", 429)
if not (request.form.get("confirm_adult") == "1" and request.form.get("confirm_consent") == "1"
and request.form.get("confirm_clothing") == "1"):
return _error("هر سه تأییدیهی زیر فرم باید انتخاب شود.", 400)
try:
height, weight = body_preview.parse_measurements(request.form.get("height"), request.form.get("weight"))
try:
kg = int(request.form.get("kg", ""))
except ValueError:
raise body_preview.BodyError("loss")
body_preview.check_eligibility(height, weight, kg)
photo = request.files.get("photo")
if not photo or not photo.filename:
return _error("لطفاً یک عکس انتخاب کنید.", 400)
name = photo.filename.lower()
if "." not in name or "." + name.rsplit(".", 1)[-1] not in ALLOWED_EXT:
raise body_preview.BodyError("format")
limit = int(config.BODY_MAX_UPLOAD_MB) * 1024 * 1024
data = photo.stream.read(limit + 1)
image = body_preview.load_photo(data)
del data
except body_preview.BodyError as exc:
return _error(exc.message, exc.status, exc.key)
if not ratelimit.check_body(user["id"]).allowed:
return _error("سقف تعداد پیشنمایشهای این بخش در هر ساعت پر شده است؛ کمی بعد دوباره تلاش کنید.", 429)
if not repo.try_acquire_generation_lock(user["id"], stale_after_seconds=int(config.AI_TOTAL_BUDGET_SECONDS) + 60):
return _error("یک پیشنمایش دیگر برای شما در حال ساخت است؛ چند لحظه صبر کنید.", 409)
uid, username = user["id"], user["username"]
charged = 0
if not repo.is_unlimited(user):
charged = int(config.BODY_CREDIT_COST)
if charged and not repo.reserve_credit(uid, charged):
repo.release_generation_lock(uid)
return _error("اعتبار شما برای این بخش کافی نیست.", 402)
if not body_preview.acquire_slot():
if charged:
repo.refund_credit(uid, charged)
repo.release_generation_lock(uid)
return _error(body_preview.MESSAGES["busy"], 503, "busy")
holder = {"image": image}
del image
state = {"edit_started": False}
outcome = {}
cancel = threading.Event()
done = threading.Event()
settled = {"value": False}
def worker():
try:
outcome["data"] = body_preview.run(holder.pop("image"), height, weight, kg, cancel, state)
except body_preview.BodyError as exc:
outcome["error"] = exc
except Exception as exc:
log.warning("body preview failed type=%s", type(exc).__name__)
outcome["error"] = body_preview.BodyError("unknown")
finally:
holder.clear()
body_preview.release_slot()
done.set()
def settle(ok: bool, key: str, keep_charge: bool) -> None:
if settled["value"]:
return
settled["value"] = True
if not ok and not keep_charge and charged:
repo.refund_credit(uid, charged)
repo.release_generation_lock(uid)
repo.audit(uid, username, "body_preview", "ok" if ok else "fail:" + key, ip)
threading.Thread(target=worker, daemon=True).start()
def generate():
try:
while not done.wait(4.0):
yield b" "
error = outcome.get("error")
ok = error is None
settle(ok, "" if ok else error.key, bool(error and error.charge))
fresh = repo.get_user(uid)
left = None if repo.is_unlimited(fresh) else repo.credits_left(fresh)
if ok:
payload = {"ok": True, "credits_left": left, **outcome["data"]}
else:
payload = {"ok": False, "error": error.message, "key": error.key, "credits_left": left}
outcome.clear()
yield json.dumps(payload, ensure_ascii=False).encode("utf-8")
finally:
if not settled["value"]:
cancel.set()
settle(False, "cancelled", bool(state["edit_started"]))
return Response(stream_with_context(generate()), mimetype="application/json",
headers={"Cache-Control": NO_STORE, "X-Accel-Buffering": "no"})
app/services/source_view.py
۱۰۱ خطsha256(file) = 8908c223392048787233f883c67b5b1974d952514bdcc90daa2d099e9bc2cb7b
sha256(shown) = 8908c223392048787233f883c67b5b1974d952514bdcc90daa2d099e9bc2cb7b
import ast
import hashlib
import io
import tokenize
from pathlib import Path
ROOT = Path(__file__).resolve().parents[2]
PUBLISHED = (
"app/memory_upload.py",
"app/services/body_preview.py",
"app/routes/body.py",
"app/services/source_view.py",
"app/static/js/body.js",
)
def _docstring_spans(tree):
spans = []
for node in ast.walk(tree):
if isinstance(node, (ast.Module, ast.ClassDef, ast.FunctionDef, ast.AsyncFunctionDef)):
body = getattr(node, "body", [])
first = body[0] if body else None
if isinstance(first, ast.Expr) and isinstance(first.value, ast.Constant) and isinstance(first.value.value, str):
spans.append((first.lineno, first.end_lineno))
return spans
def _collapse(lines):
out, blank = [], 0
for line in lines:
if line.strip():
out.append(line.rstrip())
blank = 0
else:
blank += 1
if blank <= 2:
out.append("")
return "\n".join(out).strip("\n") + "\n"
def strip_python(source):
lines = source.splitlines()
for start, end in _docstring_spans(ast.parse(source)):
for index in range(start - 1, end):
lines[index] = ""
for token in tokenize.generate_tokens(io.StringIO(source).readline):
if token.type == tokenize.COMMENT:
row, col = token.start
lines[row - 1] = lines[row - 1][:col].rstrip()
return _collapse(lines)
def strip_js(source):
out = []
index, size, quote = 0, len(source), None
while index < size:
char = source[index]
following = source[index + 1] if index + 1 < size else ""
if quote:
out.append(char)
if char == "\\" and index + 1 < size:
out.append(source[index + 1])
index += 2
continue
if char == quote:
quote = None
index += 1
continue
if char in "\"'`":
quote = char
out.append(char)
index += 1
continue
if char == "/" and following == "/":
while index < size and source[index] != "\n":
index += 1
continue
if char == "/" and following == "*":
end = source.find("*/", index + 2)
index = size if end == -1 else end + 2
continue
out.append(char)
index += 1
return _collapse("".join(out).splitlines())
def published_files():
items = []
for relative in PUBLISHED:
raw = (ROOT / relative).read_bytes()
text = raw.decode("utf-8")
shown = strip_python(text) if relative.endswith(".py") else strip_js(text)
items.append({
"path": relative,
"code": shown,
"lines": shown.count("\n"),
"sha256_file": hashlib.sha256(raw).hexdigest(),
"sha256_shown": hashlib.sha256(shown.encode("utf-8")).hexdigest(),
})
return items
app/static/js/body.js
۲۶۱ خطsha256(file) = 961f91703d11a5e5b8da8ab92b924ab80bc9a65ed6a85a0828a137241382dc3b
sha256(shown) = 961f91703d11a5e5b8da8ab92b924ab80bc9a65ed6a85a0828a137241382dc3b
(function () {
"use strict";
var form = document.getElementById("bodyForm");
if (!form) return;
var resultBox = document.getElementById("bodyResult");
var errorBox = document.getElementById("bodyError");
var hint = document.getElementById("bodyHint");
var kgSelect = document.getElementById("kgSelect");
var photoInput = document.getElementById("photoInput");
var submitButton = document.getElementById("bodySubmit");
var heightInput = form.elements.height;
var weightInput = form.elements.weight;
var choices = (form.getAttribute("data-loss-choices") || "").split(",").map(Number).filter(Boolean);
var minBmi = parseFloat(form.getAttribute("data-min-bmi"));
var minResultBmi = parseFloat(form.getAttribute("data-min-result-bmi"));
var maxPercent = parseFloat(form.getAttribute("data-max-loss-percent"));
var digits = "۰۱۲۳۴۵۶۷۸۹";
var beforeUrl = null;
var busy = false;
function fa(value) {
return String(value).replace(/[0-9]/g, function (d) { return digits.charAt(Number(d)); });
}
function bmi(height, weight) {
var m = height / 100;
return weight / (m * m);
}
function node(tag, className, text) {
var el = document.createElement(tag);
if (className) el.className = className;
if (text !== undefined && text !== null) el.textContent = text;
return el;
}
function setOptions(items, disabled) {
while (kgSelect.firstChild) kgSelect.removeChild(kgSelect.firstChild);
items.forEach(function (item) {
var option = document.createElement("option");
option.value = item.value;
option.textContent = item.label;
kgSelect.appendChild(option);
});
kgSelect.disabled = disabled;
}
function refreshChoices() {
var height = parseFloat(heightInput.value);
var weight = parseFloat(weightInput.value);
if (!(height >= 140 && height <= 220 && weight >= 40 && weight <= 250)) {
setOptions([{ value: "", label: "ابتدا قد و وزن را وارد کنید" }], true);
hint.textContent = "";
return;
}
var current = bmi(height, weight);
if (current < minBmi) {
setOptions([{ value: "", label: "پیشنمایش لاغری لازم نیست" }], true);
hint.textContent = "شاخص تودهی بدنی: " + fa(current.toFixed(1)) + " — با این قد و وزن نیازی به کاهش وزن دیده نمیشود و برای حفظ سلامت پیشنمایش لاغری ساخته نمیشود.";
return;
}
var allowed = choices.filter(function (kg) {
return kg <= weight * maxPercent / 100 && bmi(height, weight - kg) >= minResultBmi;
});
if (!allowed.length) {
setOptions([{ value: "", label: "گزینهی ایمن وجود ندارد" }], true);
hint.textContent = "با قد و وزن واردشده هیچکدام از گزینههای کاهش وزن ایمن نیست.";
return;
}
var previous = kgSelect.value;
setOptions(allowed.map(function (kg) { return { value: String(kg), label: fa(kg) + " کیلوگرم" }; }), false);
if (previous && allowed.indexOf(Number(previous)) !== -1) kgSelect.value = previous;
hint.textContent = "شاخص تودهی بدنی فعلی: " + fa(current.toFixed(1)) + " — گزینهها بر اساس ایمنی محدود شدهاند.";
}
function showError(message) {
errorBox.textContent = message;
errorBox.classList.remove("hidden");
}
function clearError() {
errorBox.textContent = "";
errorBox.classList.add("hidden");
}
function clearResult() {
while (resultBox.firstChild) resultBox.removeChild(resultBox.firstChild);
resultBox.classList.add("hidden");
if (beforeUrl) {
URL.revokeObjectURL(beforeUrl);
beforeUrl = null;
}
}
function figure(src, caption, after) {
var fig = node("figure", "ba-item" + (after ? " is-after" : ""));
var img = document.createElement("img");
img.src = src;
img.alt = caption;
fig.appendChild(img);
fig.appendChild(node("figcaption", "", caption));
return fig;
}
function stat(label, value) {
var box = node("div", "stat");
box.appendChild(node("small", "", label));
box.appendChild(node("b", "", value));
return box;
}
function section(title) {
var card = node("div", "card");
card.appendChild(node("h2", "mt-0", title));
return card;
}
function render(data, file) {
clearResult();
beforeUrl = URL.createObjectURL(file);
var stats = data.stats || {};
var analysis = data.analysis || {};
var compare = section("پیشنمایش پس از حدود " + fa(stats.kg) + " کیلوگرم کاهش وزن");
var grid = node("div", "ba-grid");
grid.appendChild(figure(beforeUrl, "قبل", false));
grid.appendChild(figure("data:" + (data.mime || "image/jpeg") + ";base64," + data.after, "بعد (شبیهسازی)", true));
compare.appendChild(grid);
var row = node("div", "stat-row mt-2");
row.appendChild(stat("وزن فعلی", fa(stats.weight) + " کیلوگرم"));
row.appendChild(stat("وزن هدف", fa(stats.target_weight) + " کیلوگرم"));
row.appendChild(stat("شاخص تودهی بدنی فعلی", fa(stats.bmi) + " — " + (stats.bmi_label || "")));
row.appendChild(stat("شاخص پس از کاهش", fa(stats.target_bmi) + " — " + (stats.target_bmi_label || "")));
compare.appendChild(row);
compare.appendChild(node("p", "result-note mb-0 mt-2", "این تصویر فقط یک شبیهسازی هوش مصنوعی است و تضمین نتیجهی واقعی نیست؛ نتیجهی واقعی به شرایط بدنی، رژیم، فعالیت و تجویز پزشک بستگی دارد."));
resultBox.appendChild(compare);
var report = section("تحلیل شکل بدن");
if (analysis.body_type) {
var type = node("p", "mb-1");
type.appendChild(node("b", "", "تیپ بدنی: "));
type.appendChild(document.createTextNode(analysis.body_type));
report.appendChild(type);
}
if (analysis.summary) report.appendChild(node("p", "", analysis.summary));
if (analysis.areas && analysis.areas.length) {
report.appendChild(node("h3", "mb-0", "نواحی نیازمند توجه"));
var list = node("ul", "area-list");
var levels = { 1: "خفیف", 2: "متوسط", 3: "قابل توجه" };
analysis.areas.forEach(function (area) {
var li = node("li");
li.appendChild(node("span", "lv lv-" + area.level, levels[area.level] || "خفیف"));
var body = node("div");
body.appendChild(node("b", "", area.region));
body.appendChild(node("span", "txt", area.finding));
li.appendChild(body);
list.appendChild(li);
});
report.appendChild(list);
}
if (analysis.posture) {
var posture = node("p", "mt-2");
posture.appendChild(node("b", "", "قامت و تقارن: "));
posture.appendChild(document.createTextNode(analysis.posture));
report.appendChild(posture);
}
if (analysis.tips && analysis.tips.length) {
report.appendChild(node("h3", "mb-0", "توصیههای سبک زندگی"));
var tips = node("ul", "tip-list");
analysis.tips.forEach(function (tip) { tips.appendChild(node("li", "", tip)); });
report.appendChild(tips);
}
report.appendChild(node("p", "result-note mb-0 mt-2", "این تحلیل جایگزین معاینهی پزشک نیست. مصرف هر دارو از جمله آمپول لاغری باید تحت نظر پزشک باشد."));
resultBox.appendChild(report);
var footer = node("div", "card");
footer.appendChild(node("p", "result-note", "هیچ نسخهای از عکس و نتیجه روی سرور نمانده است. با پاکسازی یا بستن این صفحه، نتیجه برای همیشه از بین میرود. هر اسکرینشات یا ذخیرهی تصویر، با مسئولیت کلینیک است."));
var clear = node("button", "btn btn-outline", "پاکسازی نتیجه از این صفحه");
clear.type = "button";
clear.addEventListener("click", function () {
clearResult();
window.scrollTo(0, 0);
});
footer.appendChild(clear);
resultBox.appendChild(footer);
resultBox.classList.remove("hidden");
if (typeof data.credits_left === "number") {
var credits = document.getElementById("bodyCredits");
if (credits) credits.textContent = fa(data.credits_left);
}
resultBox.scrollIntoView({ behavior: "smooth", block: "start" });
}
function onSubmit(event) {
event.preventDefault();
if (busy) return;
clearError();
var file = photoInput.files && photoInput.files[0];
if (!file) {
showError("لطفاً یک عکس انتخاب کنید.");
return;
}
if (!form.reportValidity()) return;
busy = true;
submitButton.disabled = true;
clearResult();
var stop = window.bsShowLoading
? window.bsShowLoading("در حال تحلیل بدن و ساخت پیشنمایش", ["بررسی عکس…", "تحلیل شکل و نواحی بدن…", "ساخت پیشنمایش لاغری…", "نهاییسازی نتیجه…"])
: null;
fetch(form.getAttribute("action"), {
method: "POST",
body: new FormData(form),
credentials: "same-origin",
cache: "no-store",
headers: { "Accept": "application/json" }
})
.then(function (response) {
return response.text().then(function (text) { return { status: response.status, text: text }; });
})
.then(function (result) {
var data = null;
try { data = JSON.parse(result.text.trim()); } catch (parseError) { data = null; }
if (!data) throw new Error("پاسخ نامعتبر از سرور دریافت شد (کد " + fa(result.status) + ")؛ دوباره تلاش کنید.");
if (!data.ok) {
if (typeof data.credits_left === "number") {
var left = document.getElementById("bodyCredits");
if (left) left.textContent = fa(data.credits_left);
}
throw new Error(data.error || "ساخت پیشنمایش ناموفق بود.");
}
render(data, file);
})
.catch(function (error) {
showError(error && error.message ? error.message : "ارتباط با سرور قطع شد؛ دوباره تلاش کنید.");
})
.then(function () {
busy = false;
submitButton.disabled = false;
if (stop) stop();
});
}
heightInput.addEventListener("input", refreshChoices);
weightInput.addEventListener("input", refreshChoices);
form.addEventListener("submit", onSubmit);
window.addEventListener("pagehide", clearResult);
window.addEventListener("beforeunload", function (event) {
if (busy) {
event.preventDefault();
event.returnValue = "";
}
});
refreshChoices();
})();