Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,152 +1,489 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
import gradio as gr
|
| 2 |
import spaces
|
| 3 |
import torch
|
| 4 |
-
|
| 5 |
from transformers import (
|
| 6 |
AutoTokenizer,
|
| 7 |
AutoModelForCausalLM,
|
| 8 |
-
BitsAndBytesConfig
|
|
|
|
| 9 |
)
|
| 10 |
|
| 11 |
|
|
|
|
|
|
|
|
|
|
| 12 |
MODEL_ID = "ddfws/Rezaeian-StatsAI"
|
|
|
|
| 13 |
|
| 14 |
-
|
| 15 |
-
print("Loading tokenizer...")
|
| 16 |
-
|
| 17 |
-
|
| 18 |
tokenizer = AutoTokenizer.from_pretrained(
|
| 19 |
MODEL_ID,
|
| 20 |
-
trust_remote_code=True
|
| 21 |
)
|
| 22 |
|
|
|
|
|
|
|
| 23 |
|
| 24 |
-
print("Loading model...")
|
| 25 |
-
|
| 26 |
-
|
| 27 |
bnb_config = BitsAndBytesConfig(
|
| 28 |
load_in_4bit=True,
|
| 29 |
bnb_4bit_quant_type="nf4",
|
| 30 |
-
bnb_4bit_compute_dtype=torch.float16
|
|
|
|
| 31 |
)
|
| 32 |
|
| 33 |
-
|
| 34 |
model = AutoModelForCausalLM.from_pretrained(
|
| 35 |
MODEL_ID,
|
| 36 |
device_map="auto",
|
| 37 |
quantization_config=bnb_config,
|
| 38 |
-
|
|
|
|
| 39 |
)
|
| 40 |
-
|
| 41 |
-
|
| 42 |
model.eval()
|
| 43 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 44 |
|
| 45 |
-
print("MODEL READY")
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
SYSTEM = """
|
| 50 |
-
تو یک استاد دانشگاه تهران در درس آمار و احتمال مهندسی هستی.
|
| 51 |
-
|
| 52 |
-
پاسخها:
|
| 53 |
-
- کامل و آموزشی باشند.
|
| 54 |
-
- مرحله به مرحله حل کن.
|
| 55 |
-
- فرمولها را بنویس.
|
| 56 |
-
- مثال مشابه بده.
|
| 57 |
-
- نتیجه گیری کن.
|
| 58 |
|
| 59 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 60 |
"""
|
| 61 |
|
| 62 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 63 |
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
"content":SYSTEM
|
| 72 |
-
}
|
| 73 |
-
]
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
for q,a in history:
|
| 77 |
-
|
| 78 |
-
messages.append(
|
| 79 |
-
{
|
| 80 |
-
"role":"user",
|
| 81 |
-
"content":q
|
| 82 |
-
}
|
| 83 |
-
)
|
| 84 |
-
|
| 85 |
-
messages.append(
|
| 86 |
-
{
|
| 87 |
-
"role":"assistant",
|
| 88 |
-
"content":a
|
| 89 |
-
}
|
| 90 |
-
)
|
| 91 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 92 |
|
| 93 |
-
|
| 94 |
-
{
|
| 95 |
-
"role":"user",
|
| 96 |
-
"content":message
|
| 97 |
-
}
|
| 98 |
-
)
|
| 99 |
|
| 100 |
|
| 101 |
-
|
|
|
|
| 102 |
messages,
|
| 103 |
tokenize=False,
|
| 104 |
-
add_generation_prompt=True
|
| 105 |
)
|
| 106 |
|
| 107 |
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
|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
|
|
|
|
|
|
|
|
|
|
| 130 |
|
| 131 |
-
|
| 132 |
-
|
| 133 |
-
|
| 134 |
-
|
| 135 |
-
|
| 136 |
-
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
title="🤖 Rezaeian StatsAI",
|
| 140 |
-
|
| 141 |
-
description="""
|
| 142 |
-
دستیار هوشمند آمار و احتمال مهندسی
|
| 143 |
-
|
| 144 |
-
""",
|
| 145 |
-
|
| 146 |
-
)
|
| 147 |
-
|
| 148 |
|
| 149 |
|
| 150 |
-
|
| 151 |
-
|
| 152 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import threading
|
| 3 |
+
import traceback
|
| 4 |
+
|
| 5 |
import gradio as gr
|
| 6 |
import spaces
|
| 7 |
import torch
|
|
|
|
| 8 |
from transformers import (
|
| 9 |
AutoTokenizer,
|
| 10 |
AutoModelForCausalLM,
|
| 11 |
+
BitsAndBytesConfig,
|
| 12 |
+
TextIteratorStreamer,
|
| 13 |
)
|
| 14 |
|
| 15 |
|
| 16 |
+
# -----------------------------------------------------------------------------
|
| 17 |
+
# Model configuration
|
| 18 |
+
# -----------------------------------------------------------------------------
|
| 19 |
MODEL_ID = "ddfws/Rezaeian-StatsAI"
|
| 20 |
+
REQUESTED_MAX_NEW_TOKENS = int(os.getenv("MAX_NEW_TOKENS", "4096"))
|
| 21 |
|
| 22 |
+
print(f"Loading tokenizer: {MODEL_ID}")
|
|
|
|
|
|
|
|
|
|
| 23 |
tokenizer = AutoTokenizer.from_pretrained(
|
| 24 |
MODEL_ID,
|
| 25 |
+
trust_remote_code=True,
|
| 26 |
)
|
| 27 |
|
| 28 |
+
if tokenizer.pad_token_id is None and tokenizer.eos_token_id is not None:
|
| 29 |
+
tokenizer.pad_token = tokenizer.eos_token
|
| 30 |
|
| 31 |
+
print("Loading model in 4-bit mode...")
|
|
|
|
|
|
|
| 32 |
bnb_config = BitsAndBytesConfig(
|
| 33 |
load_in_4bit=True,
|
| 34 |
bnb_4bit_quant_type="nf4",
|
| 35 |
+
bnb_4bit_compute_dtype=torch.float16,
|
| 36 |
+
bnb_4bit_use_double_quant=True,
|
| 37 |
)
|
| 38 |
|
|
|
|
| 39 |
model = AutoModelForCausalLM.from_pretrained(
|
| 40 |
MODEL_ID,
|
| 41 |
device_map="auto",
|
| 42 |
quantization_config=bnb_config,
|
| 43 |
+
torch_dtype=torch.float16,
|
| 44 |
+
trust_remote_code=True,
|
| 45 |
)
|
|
|
|
|
|
|
| 46 |
model.eval()
|
| 47 |
|
| 48 |
+
# Keep a reserve for the prompt and avoid requesting more tokens than the
|
| 49 |
+
# model's advertised context window can reasonably support.
|
| 50 |
+
model_context = getattr(model.config, "max_position_embeddings", None)
|
| 51 |
+
if not isinstance(model_context, int) or model_context < 1024:
|
| 52 |
+
model_context = getattr(model.config, "seq_length", 8192)
|
| 53 |
+
if not isinstance(model_context, int) or model_context < 1024:
|
| 54 |
+
model_context = 8192
|
| 55 |
+
|
| 56 |
+
MAX_NEW_TOKENS = max(256, min(REQUESTED_MAX_NEW_TOKENS, model_context // 2))
|
| 57 |
+
MAX_INPUT_TOKENS = max(512, min(8192, model_context - MAX_NEW_TOKENS))
|
| 58 |
+
|
| 59 |
+
print(
|
| 60 |
+
"MODEL READY | "
|
| 61 |
+
f"context={model_context}, input_limit={MAX_INPUT_TOKENS}, "
|
| 62 |
+
f"output_limit={MAX_NEW_TOKENS}"
|
| 63 |
+
)
|
| 64 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 65 |
|
| 66 |
+
# -----------------------------------------------------------------------------
|
| 67 |
+
# Assistant instructions
|
| 68 |
+
# -----------------------------------------------------------------------------
|
| 69 |
+
SYSTEM = r"""
|
| 70 |
+
تو دستیار آموزشی درس «آمار و احتمال مهندسی» برای دانشجویان رشتههای مهندسی هستی.
|
| 71 |
+
به زبان فارسی روان، دقیق و آموزشی پاسخ بده؛ مگر اینکه کاربر زبان دیگری بخواهد.
|
| 72 |
+
|
| 73 |
+
موضوعات قابل پوشش شامل این موارد و موضوعات مرتبط است:
|
| 74 |
+
احتمال و احتمال شرطی، قضیه بیز، استقلال رویدادها، شمارش و ترکیبیات، متغیرهای تصادفی
|
| 75 |
+
گسسته و پیوسته، تابع جرم/چگالی/توزیع تجمعی، امید ریاضی و واریانس، توزیعهای برنولی،
|
| 76 |
+
دوجملهای، هندسی، پواسون، یکنواخت، نمایی، نرمال، گاما و کایدو، توزیعهای مشترک،
|
| 77 |
+
همبستگی و کوواریانس، تبدیل متغیرهای تصادفی، قانون اعداد بزرگ و قضیه حد مرکزی، نمونهگیری،
|
| 78 |
+
توزیعهای نمونهای، برآورد نقطهای و بازهای، آزمون فرض، مقدار p، خطاهای نوع اول و دوم،
|
| 79 |
+
توان آزمون، آزمونهای z و t و کایدو، تحلیل واریانس، رگرسیون و همبستگی، کنترل کیفیت آماری،
|
| 80 |
+
پایایی و مثالهای کاربردی مهندسی.
|
| 81 |
+
|
| 82 |
+
روش پاسخگویی:
|
| 83 |
+
- اگر مسئله محاسباتی است، دادهها و خواسته را مشخص کن و راهحل را مرحلهبهمرحله پیش ببر.
|
| 84 |
+
- فرمول مناسب را معرفی کن، مقادیر را جایگذاری کن و محاسبات را تا حد امکان روشن بنویس.
|
| 85 |
+
- در پایان، نتیجه را به زبان ساده و در بافت مسئله تفسیر کن؛ واحدها و فرضهای مهم را فراموش نکن.
|
| 86 |
+
- برای پرسش مفهومی، تعریف دقیق، شهود ساده و در صورت مفید بودن یک مثال کوتاه ارائه کن.
|
| 87 |
+
- فرمولهای درون متن را با $...$ و فرمولهای مستقل را با $$...$$ بنویس.
|
| 88 |
+
- از جدول فقط وقتی استفاده کن که خوانایی را بهتر میک��د. پاسخ را بیدلیل طولانی نکن؛ اگر کاربر حل کامل خواست، جزئیات کافی بده.
|
| 89 |
+
- اگر دادهای کم است یا صورت سؤال مبهم است، فرض پنهانی نساز؛ ابهام را مشخص کن یا سؤال روشنکننده بپرس.
|
| 90 |
+
- نتیجه عددی را حدس نزن. محاسبات را بررسی کن و اگر اطمینان نداری، صادقانه بیان کن.
|
| 91 |
+
- اگر درخواست خارج از آمار و احتمال بود، تا جای ممکن کمک کن و مرز تخصص را روشن نگه دار.
|
| 92 |
"""
|
| 93 |
|
| 94 |
|
| 95 |
+
# -----------------------------------------------------------------------------
|
| 96 |
+
# Conversation helpers
|
| 97 |
+
# -----------------------------------------------------------------------------
|
| 98 |
+
def normalize_history(history):
|
| 99 |
+
"""Convert Gradio history into the role/content format used by chat templates."""
|
| 100 |
+
normalized = []
|
| 101 |
|
| 102 |
+
for item in history or []:
|
| 103 |
+
# Current Gradio message format: {"role": "user", "content": "..."}
|
| 104 |
+
if isinstance(item, dict):
|
| 105 |
+
role = item.get("role")
|
| 106 |
+
content = item.get("content")
|
| 107 |
+
if role in ("user", "assistant") and isinstance(content, str) and content.strip():
|
| 108 |
+
normalized.append({"role": role, "content": content})
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 109 |
|
| 110 |
+
# Compatibility with older tuple-style Gradio history: (question, answer)
|
| 111 |
+
elif isinstance(item, (list, tuple)) and len(item) == 2:
|
| 112 |
+
question, response = item
|
| 113 |
+
if isinstance(question, str) and question.strip():
|
| 114 |
+
normalized.append({"role": "user", "content": question})
|
| 115 |
+
if isinstance(response, str) and response.strip():
|
| 116 |
+
normalized.append({"role": "assistant", "content": response})
|
| 117 |
|
| 118 |
+
return normalized
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 119 |
|
| 120 |
|
| 121 |
+
def make_prompt(messages):
|
| 122 |
+
return tokenizer.apply_chat_template(
|
| 123 |
messages,
|
| 124 |
tokenize=False,
|
| 125 |
+
add_generation_prompt=True,
|
| 126 |
)
|
| 127 |
|
| 128 |
|
| 129 |
+
@spaces.GPU
|
| 130 |
+
def answer(message, history):
|
| 131 |
+
question = str(message or "").strip()
|
| 132 |
+
if not question:
|
| 133 |
+
yield "لطفاً سؤال خود را بنویسید."
|
| 134 |
+
return
|
| 135 |
+
|
| 136 |
+
messages = [{"role": "system", "content": SYSTEM}]
|
| 137 |
+
messages.extend(normalize_history(history))
|
| 138 |
+
messages.append({"role": "user", "content": question})
|
| 139 |
+
|
| 140 |
+
# If the conversation gets too long, remove the oldest history first while
|
| 141 |
+
# preserving the newest user question. The UI still displays the full chat.
|
| 142 |
+
while True:
|
| 143 |
+
prompt = make_prompt(messages)
|
| 144 |
+
encoded = tokenizer(prompt, return_tensors="pt")
|
| 145 |
+
input_length = encoded["input_ids"].shape[-1]
|
| 146 |
+
|
| 147 |
+
if input_length <= MAX_INPUT_TOKENS:
|
| 148 |
+
break
|
| 149 |
+
|
| 150 |
+
# Remove the oldest user/assistant exchange where possible.
|
| 151 |
+
if len(messages) > 3 and messages[1]["role"] == "user" and messages[2]["role"] == "assistant":
|
| 152 |
+
del messages[1:3]
|
| 153 |
+
elif len(messages) > 2:
|
| 154 |
+
del messages[1]
|
| 155 |
+
else:
|
| 156 |
+
yield (
|
| 157 |
+
"متن سؤال از ظرفیت ورودی مدل طولانیتر است. لطفاً سؤال را کوتاهتر کنید "
|
| 158 |
+
"یا آن را در چند پیام جداگانه بفرستید."
|
| 159 |
+
)
|
| 160 |
+
return
|
| 161 |
+
|
| 162 |
+
input_device = model.get_input_embeddings().weight.device
|
| 163 |
+
inputs = {key: value.to(input_device) for key, value in encoded.items()}
|
| 164 |
+
|
| 165 |
+
streamer = TextIteratorStreamer(
|
| 166 |
+
tokenizer,
|
| 167 |
+
skip_prompt=True,
|
| 168 |
+
skip_special_tokens=True,
|
| 169 |
+
)
|
| 170 |
+
generation_errors = []
|
| 171 |
+
|
| 172 |
+
def run_generation():
|
| 173 |
+
try:
|
| 174 |
+
generation_kwargs = {
|
| 175 |
+
**inputs,
|
| 176 |
+
"streamer": streamer,
|
| 177 |
+
"max_new_tokens": MAX_NEW_TOKENS,
|
| 178 |
+
"do_sample": True,
|
| 179 |
+
"temperature": 0.3,
|
| 180 |
+
"top_p": 0.9,
|
| 181 |
+
"repetition_penalty": 1.05,
|
| 182 |
+
"use_cache": True,
|
| 183 |
+
}
|
| 184 |
+
if tokenizer.pad_token_id is not None:
|
| 185 |
+
generation_kwargs["pad_token_id"] = tokenizer.pad_token_id
|
| 186 |
+
if tokenizer.eos_token_id is not None:
|
| 187 |
+
generation_kwargs["eos_token_id"] = tokenizer.eos_token_id
|
| 188 |
+
|
| 189 |
+
with torch.inference_mode():
|
| 190 |
+
model.generate(**generation_kwargs)
|
| 191 |
+
except Exception as exc:
|
| 192 |
+
generation_errors.append(exc)
|
| 193 |
+
traceback.print_exc()
|
| 194 |
+
# Ensure the UI's streamer loop can finish if generation failed.
|
| 195 |
+
try:
|
| 196 |
+
streamer.end()
|
| 197 |
+
except Exception:
|
| 198 |
+
pass
|
| 199 |
+
|
| 200 |
+
worker = threading.Thread(target=run_generation, daemon=True)
|
| 201 |
+
worker.start()
|
| 202 |
+
|
| 203 |
+
full_response = ""
|
| 204 |
+
for new_text in streamer:
|
| 205 |
+
if new_text:
|
| 206 |
+
full_response += new_text
|
| 207 |
+
# Gradio updates the same assistant message incrementally.
|
| 208 |
+
yield full_response
|
| 209 |
+
|
| 210 |
+
worker.join()
|
| 211 |
+
|
| 212 |
+
if generation_errors and not full_response.strip():
|
| 213 |
+
yield (
|
| 214 |
+
"هنگام تولید پاسخ خطایی رخ داد. لطفاً یک بار دیگر تلاش کنید. "
|
| 215 |
+
"اگر مشکل ادامه داشت، گزارش اجرای Space را بررسی کنید."
|
| 216 |
)
|
| 217 |
+
elif not full_response.strip():
|
| 218 |
+
yield "پاسخی تولید نشد؛ لطفاً سؤال را با بیان دیگری مطرح کنید."
|
| 219 |
+
|
| 220 |
+
|
| 221 |
+
# -----------------------------------------------------------------------------
|
| 222 |
+
# Visual design
|
| 223 |
+
# -----------------------------------------------------------------------------
|
| 224 |
+
CUSTOM_CSS = r"""
|
| 225 |
+
:root {
|
| 226 |
+
color-scheme: dark;
|
| 227 |
+
--ink: #eef2ff;
|
| 228 |
+
--muted: #a5b4cf;
|
| 229 |
+
--panel: rgba(16, 25, 47, 0.82);
|
| 230 |
+
--line: rgba(148, 163, 184, 0.18);
|
| 231 |
+
}
|
| 232 |
+
|
| 233 |
+
html, body {
|
| 234 |
+
margin: 0 !important;
|
| 235 |
+
background: #080d1a !important;
|
| 236 |
+
}
|
| 237 |
+
body {
|
| 238 |
+
background-image:
|
| 239 |
+
radial-gradient(ellipse at 12% 0%, rgba(45, 91, 190, .22), transparent 36%),
|
| 240 |
+
radial-gradient(ellipse at 90% 12%, rgba(107, 57, 190, .18), transparent 32%),
|
| 241 |
+
linear-gradient(180deg, #080d1a 0%, #0a1222 100%) !important;
|
| 242 |
+
color: var(--ink) !important;
|
| 243 |
+
}
|
| 244 |
+
.gradio-container {
|
| 245 |
+
max-width: 1320px !important;
|
| 246 |
+
margin: 0 auto !important;
|
| 247 |
+
padding: 14px 20px 22px !important;
|
| 248 |
+
background: transparent !important;
|
| 249 |
+
color: var(--ink) !important;
|
| 250 |
+
font-family: Vazirmatn, IRANSans, Tahoma, Arial, sans-serif !important;
|
| 251 |
+
}
|
| 252 |
+
.gradio-container * {
|
| 253 |
+
font-family: Vazirmatn, IRANSans, Tahoma, Arial, sans-serif;
|
| 254 |
+
}
|
| 255 |
+
|
| 256 |
+
#stats-header {
|
| 257 |
+
direction: rtl;
|
| 258 |
+
position: relative;
|
| 259 |
+
overflow: hidden;
|
| 260 |
+
display: flex;
|
| 261 |
+
align-items: center;
|
| 262 |
+
justify-content: space-between;
|
| 263 |
+
gap: 22px;
|
| 264 |
+
padding: 26px 30px;
|
| 265 |
+
margin: 2px 0 16px;
|
| 266 |
+
border-radius: 26px;
|
| 267 |
+
border: 1px solid rgba(148, 163, 184, .22);
|
| 268 |
+
background: linear-gradient(120deg, rgba(20, 35, 67, .96), rgba(27, 25, 62, .94) 58%, rgba(17, 47, 68, .92));
|
| 269 |
+
box-shadow: 0 22px 70px rgba(0, 0, 0, .24), inset 0 1px 0 rgba(255,255,255,.06);
|
| 270 |
+
}
|
| 271 |
+
#stats-header:after {
|
| 272 |
+
content: "";
|
| 273 |
+
position: absolute;
|
| 274 |
+
left: -70px;
|
| 275 |
+
bottom: -130px;
|
| 276 |
+
width: 310px;
|
| 277 |
+
height: 310px;
|
| 278 |
+
border-radius: 50%;
|
| 279 |
+
border: 1px solid rgba(103, 232, 249, .14);
|
| 280 |
+
box-shadow: 0 0 0 28px rgba(103, 232, 249, .025), 0 0 0 58px rgba(129, 140, 248, .025);
|
| 281 |
+
pointer-events: none;
|
| 282 |
+
}
|
| 283 |
+
.brand-lockup { display:flex; align-items:center; gap:18px; z-index:1; }
|
| 284 |
+
.brand-symbol {
|
| 285 |
+
width:66px; height:66px; flex:0 0 66px; border-radius:21px;
|
| 286 |
+
display:flex; align-items:center; justify-content:center;
|
| 287 |
+
font-size:32px; font-weight:800; color:#f8fafc;
|
| 288 |
+
background:linear-gradient(145deg, #4f46e5, #0891b2);
|
| 289 |
+
box-shadow:0 10px 32px rgba(59,130,246,.28), inset 0 1px 0 rgba(255,255,255,.35);
|
| 290 |
+
}
|
| 291 |
+
.brand-eyebrow {
|
| 292 |
+
direction:ltr; text-align:right; color:#93c5fd; font-size:11px;
|
| 293 |
+
font-weight:800; letter-spacing:2px; margin-bottom:7px;
|
| 294 |
+
}
|
| 295 |
+
#stats-header h1 { margin:0 0 8px; color:#fff; font-size:clamp(21px, 3vw, 31px); font-weight:850; line-height:1.6; }
|
| 296 |
+
#stats-header p { margin:0; color:#c4cee3; font-size:14px; line-height:1.9; }
|
| 297 |
+
.status-pill {
|
| 298 |
+
z-index:1; display:flex; align-items:center; gap:9px; white-space:nowrap;
|
| 299 |
+
padding:10px 14px; border:1px solid rgba(110,231,183,.22); border-radius:999px;
|
| 300 |
+
background:rgba(6, 78, 59, .24); color:#a7f3d0; font-size:12px; font-weight:700;
|
| 301 |
+
}
|
| 302 |
+
.status-dot { width:8px; height:8px; display:inline-block; border-radius:50%; background:#34d399; box-shadow:0 0 12px rgba(52,211,153,.8); }
|
| 303 |
+
|
| 304 |
+
#stats-features { direction:rtl; display:flex; flex-wrap:wrap; gap:9px; margin:0 2px 14px; }
|
| 305 |
+
.feature-chip {
|
| 306 |
+
border:1px solid var(--line); background:rgba(15,23,42,.55); color:#cbd5e1;
|
| 307 |
+
border-radius:999px; padding:7px 12px; font-size:12px; line-height:1.6;
|
| 308 |
+
}
|
| 309 |
+
#chat-shell {
|
| 310 |
+
padding:10px;
|
| 311 |
+
border-radius:26px;
|
| 312 |
+
border:1px solid rgba(148,163,184,.17);
|
| 313 |
+
background:linear-gradient(145deg, rgba(13,21,39,.94), rgba(10,17,32,.92));
|
| 314 |
+
box-shadow:0 24px 70px rgba(0,0,0,.22), inset 0 1px 0 rgba(255,255,255,.025);
|
| 315 |
+
}
|
| 316 |
+
#stats-chatbot {
|
| 317 |
+
border:0 !important;
|
| 318 |
+
background:transparent !important;
|
| 319 |
+
}
|
| 320 |
+
#stats-chatbot .message {
|
| 321 |
+
font-size:15px !important;
|
| 322 |
+
line-height:2.05 !important;
|
| 323 |
+
overflow-wrap:anywhere !important;
|
| 324 |
+
word-break:normal !important;
|
| 325 |
+
}
|
| 326 |
+
#stats-chatbot .message-wrap { gap:12px !important; }
|
| 327 |
+
#stats-chatbot .message-bubble {
|
| 328 |
+
border-radius:18px !important;
|
| 329 |
+
padding:15px 18px !important;
|
| 330 |
+
border:1px solid rgba(148,163,184,.14) !important;
|
| 331 |
+
box-shadow:0 6px 24px rgba(0,0,0,.10) !important;
|
| 332 |
+
}
|
| 333 |
+
#stats-chatbot p { line-height:2.0 !important; margin: .48em 0 !important; }
|
| 334 |
+
#stats-chatbot ul, #stats-chatbot ol { padding-right:1.7em !important; padding-left:0 !important; }
|
| 335 |
+
#stats-chatbot pre, #stats-chatbot code {
|
| 336 |
+
direction:ltr !important; text-align:left !important;
|
| 337 |
+
font-family:Consolas, "Courier New", monospace !important;
|
| 338 |
+
}
|
| 339 |
+
#stats-chatbot pre { overflow-x:auto !important; border-radius:12px !important; }
|
| 340 |
+
#stats-chatbot table { display:block; max-width:100%; overflow-x:auto; border-collapse:collapse; }
|
| 341 |
+
#stats-chatbot th, #stats-chatbot td { padding:8px 12px !important; }
|
| 342 |
+
#stats-chatbot .katex-display { direction:ltr; max-width:100%; overflow-x:auto; overflow-y:hidden; padding:8px 2px; }
|
| 343 |
+
|
| 344 |
+
#stats-input {
|
| 345 |
+
border:1px solid rgba(129,140,248,.25) !important;
|
| 346 |
+
border-radius:19px !important;
|
| 347 |
+
background:rgba(15,23,42,.88) !important;
|
| 348 |
+
box-shadow:0 8px 28px rgba(0,0,0,.14) !important;
|
| 349 |
+
}
|
| 350 |
+
#stats-input textarea {
|
| 351 |
+
direction:rtl !important; text-align:right !important;
|
| 352 |
+
color:#f1f5f9 !important; font-size:15px !important; line-height:1.9 !important;
|
| 353 |
+
padding:13px 15px !important;
|
| 354 |
+
}
|
| 355 |
+
#stats-input textarea::placeholder { color:#8695b1 !important; }
|
| 356 |
+
#chat-shell button { border-radius:13px !important; }
|
| 357 |
+
#chat-shell button[aria-label*="Submit"], #chat-shell button[aria-label*="submit"] {
|
| 358 |
+
background:linear-gradient(135deg,#4f46e5,#0891b2) !important;
|
| 359 |
+
color:white !important; border:0 !important;
|
| 360 |
+
}
|
| 361 |
+
|
| 362 |
+
#stats-footer {
|
| 363 |
+
margin:14px 4px 0; direction:rtl; text-align:center;
|
| 364 |
+
color:#8290aa; font-size:11px; line-height:1.9;
|
| 365 |
+
}
|
| 366 |
+
footer { display:none !important; }
|
| 367 |
+
|
| 368 |
+
@media (max-width: 700px) {
|
| 369 |
+
.gradio-container { padding:8px 8px 16px !important; }
|
| 370 |
+
#stats-header { padding:19px 17px; border-radius:21px; align-items:flex-start; }
|
| 371 |
+
.brand-lockup { gap:12px; }
|
| 372 |
+
.brand-symbol { width:49px; height:49px; flex-basis:49px; border-radius:15px; font-size:25px; }
|
| 373 |
+
.brand-eyebrow { font-size:9px; letter-spacing:1px; }
|
| 374 |
+
#stats-header p { font-size:12px; }
|
| 375 |
+
.status-pill { display:none; }
|
| 376 |
+
#chat-shell { padding:5px; border-radius:19px; }
|
| 377 |
+
#stats-chatbot .message { font-size:14px !important; }
|
| 378 |
+
}
|
| 379 |
+
"""
|
| 380 |
|
| 381 |
|
| 382 |
+
with gr.Blocks(
|
| 383 |
+
css=CUSTOM_CSS,
|
| 384 |
+
title="دستیار احتمال و آمار مهندسی دانشگاه تهران | Rezaeian StatsAI",
|
| 385 |
+
analytics_enabled=False,
|
| 386 |
+
) as demo:
|
| 387 |
+
gr.HTML(
|
| 388 |
+
"""
|
| 389 |
+
<section id="stats-header" dir="rtl">
|
| 390 |
+
<div class="brand-lockup">
|
| 391 |
+
<div class="brand-symbol">Σ</div>
|
| 392 |
+
<div>
|
| 393 |
+
<div class="brand-eyebrow">ENGINEERING • STATISTICS • PROBABILITY</div>
|
| 394 |
+
<h1>دستیار احتمال و آمار مهندسی دانشگاه تهران</h1>
|
| 395 |
+
<p>حل گامبهگام مسائل، توضیح مفاهیم و فرمولنویسی برای دانشجویان مهندسی</p>
|
| 396 |
+
</div>
|
| 397 |
+
</div>
|
| 398 |
+
<div class="status-pill"><span class="status-dot"></span> آماده پاسخگویی</div>
|
| 399 |
+
</section>
|
| 400 |
+
<div id="stats-features" dir="rtl">
|
| 401 |
+
<span class="feature-chip">∑ حل تشریحی مسائل</span>
|
| 402 |
+
<span class="feature-chip">∿ فرمولهای ریاضی</span>
|
| 403 |
+
<span class="feature-chip">▥ آزمون فرض و رگرسیون</span>
|
| 404 |
+
<span class="feature-chip">◉ احتمال و توزیعها</span>
|
| 405 |
+
</div>
|
| 406 |
+
"""
|
| 407 |
)
|
| 408 |
|
| 409 |
+
with gr.Column(elem_id="chat-shell"):
|
| 410 |
+
gr.ChatInterface(
|
| 411 |
+
fn=answer,
|
| 412 |
+
chatbot=gr.Chatbot(
|
| 413 |
+
elem_id="stats-chatbot",
|
| 414 |
+
height="67vh",
|
| 415 |
+
min_height=480,
|
| 416 |
+
rtl=True,
|
| 417 |
+
layout="bubble",
|
| 418 |
+
render_markdown=True,
|
| 419 |
+
line_breaks=True,
|
| 420 |
+
latex_delimiters=[
|
| 421 |
+
{"left": "$$", "right": "$$", "display": True},
|
| 422 |
+
{"left": "$", "right": "$", "display": False},
|
| 423 |
+
{"left": r"\[", "right": r"\]", "display": True},
|
| 424 |
+
{"left": r"\(", "right": r"\)", "display": False},
|
| 425 |
+
],
|
| 426 |
+
buttons=["copy", "copy_all"],
|
| 427 |
+
placeholder=(
|
| 428 |
+
"<div dir='rtl' style='text-align:center; padding:24px; line-height:2.2;'>"
|
| 429 |
+
"<div style='font-size:34px; margin-bottom:12px;'>∑</div>"
|
| 430 |
+
"<strong style='font-size:19px;'>از کجا شروع کنیم؟</strong><br>"
|
| 431 |
+
"سؤال خود را درباره آمار یا احتمال مهندسی بنویسید. "
|
| 432 |
+
"میتوانید مسئله را کامل وارد کنید تا مرحلهبهمرحله حل شود."
|
| 433 |
+
"</div>"
|
| 434 |
+
),
|
| 435 |
+
show_label=False,
|
| 436 |
+
),
|
| 437 |
+
textbox=gr.Textbox(
|
| 438 |
+
elem_id="stats-input",
|
| 439 |
+
placeholder="سؤال خود را اینجا بنویسید… (برای ارسال Enter را بزنید)",
|
| 440 |
+
lines=2,
|
| 441 |
+
max_lines=8,
|
| 442 |
+
show_label=False,
|
| 443 |
+
container=False,
|
| 444 |
+
autofocus=True,
|
| 445 |
+
rtl=True,
|
| 446 |
+
text_align="right",
|
| 447 |
+
submit_btn=True,
|
| 448 |
+
stop_btn=True,
|
| 449 |
+
),
|
| 450 |
+
examples=[
|
| 451 |
+
"اگر X دارای توزیع نرمال با میانگین 50 و انحراف معیار 8 باشد، احتمال P(X > 62) را مرحلهبهمرحله حساب کن.",
|
| 452 |
+
"تفاوت آزمون فرض یکطرفه و دوطرفه را با یک مثال مهندسی توضیح بده.",
|
| 453 |
+
"قضیه بیز را با یک مثال از کنترل کیفیت محصول توضیح بده.",
|
| 454 |
+
"رگرسیون خطی را توضیح بده و یک مثال عددی حل کن.",
|
| 455 |
+
],
|
| 456 |
+
example_labels=[
|
| 457 |
+
"توزیع نرمال",
|
| 458 |
+
"آزمون فرض",
|
| 459 |
+
"قضیه بیز",
|
| 460 |
+
"رگرسیون خطی",
|
| 461 |
+
],
|
| 462 |
+
run_examples_on_click=False,
|
| 463 |
+
submit_btn=True,
|
| 464 |
+
stop_btn=True,
|
| 465 |
+
fill_height=True,
|
| 466 |
+
fill_width=True,
|
| 467 |
+
concurrency_limit=1,
|
| 468 |
+
show_progress="minimal",
|
| 469 |
+
)
|
| 470 |
|
| 471 |
+
gr.HTML(
|
| 472 |
+
"""
|
| 473 |
+
<div id="stats-footer" dir="rtl">
|
| 474 |
+
پاسخها بهصورت خودکار تولید میشوند؛ برای تحویل دانشگاهی، فرمولها و محاسبات را با جزوه یا منبع درس تطبیق دهید.
|
| 475 |
+
</div>
|
| 476 |
+
"""
|
| 477 |
+
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 478 |
|
| 479 |
|
| 480 |
+
if __name__ == "__main__":
|
| 481 |
+
demo.queue(default_concurrency_limit=1)
|
| 482 |
+
demo.launch(
|
| 483 |
+
server_name="0.0.0.0",
|
| 484 |
+
theme=gr.themes.Soft(
|
| 485 |
+
primary_hue="indigo",
|
| 486 |
+
secondary_hue="cyan",
|
| 487 |
+
neutral_hue="slate",
|
| 488 |
+
),
|
| 489 |
+
)
|