Spaces:
Sleeping
Sleeping
Download src/decision_model/ui.py from xstard/decision-model: direct link, hf CLI and curl.
- Browser
- Download file 7.71 kB
-
https://huggingface.co/spaces/xstard/decision-model/resolve/main/src/decision_model/ui.py
- Command line
-
hf download hf://spaces/xstard/decision-model/src/decision_model/ui.py
-
curl -L -o ui.py https://huggingface.co/spaces/xstard/decision-model/resolve/main/src/decision_model/ui.py
7.71 kB
| import json | |
| import os | |
| os.environ.setdefault("GRADIO_ANALYTICS_ENABLED", "False") | |
| import gradio as gr | |
| from .data import DEPARTMENTS, THREE_LEVELS | |
| from .encoding import candidates | |
| from .prediction import ModelNotReady | |
| from .schemas import DecisionRequest | |
| def default_questions(language="uk"): | |
| uk = language == "uk" | |
| return { | |
| "department": {"type": "choice", "instructions": "Яка команда має обробити головне прохання клієнта?" if uk else "Which team should handle the customer's main request?", "criteria": DEPARTMENTS[language]}, | |
| "wants_refund": {"type": "noul", "instructions": "Клієнт явно просить повернути гроші?" if uk else "Does the customer explicitly request a refund?"}, | |
| "frustration": {"type": "score", "instructions": "Наскільки клієнт роздратований?" if uk else "How frustrated is the customer?", "criteria": THREE_LEVELS[language]}, | |
| } | |
| def run_ui(service, state, questions_json): | |
| if service is None: | |
| raise ModelNotReady("Модель ще не готова. Власнику потрібно завершити навчання та завантажити артефакти.") | |
| request = DecisionRequest.model_validate({"state": state, "questions": json.loads(questions_json)}) | |
| response = service.predict(request) | |
| summary, rows = [], [] | |
| for key, answer in response.answers.items(): | |
| question = request.questions[key] | |
| ids, descriptions = candidates(question) | |
| if answer.type == "noul": | |
| decision = "Так" if answer.noul >= .5 else "Ні" | |
| summary.append(f"**{key}:** {decision} · імовірність «так» {answer.noul:.1%}") | |
| p = [1 - answer.noul, answer.noul] | |
| elif answer.type == "choice": | |
| description = question.criteria[answer.choice] | |
| summary.append(f"**{key}:** {description} · {answer.confidence:.1%}") | |
| p = [answer.probabilities[i] for i in ids] | |
| else: | |
| most_likely=max(answer.probabilities,key=answer.probabilities.get) | |
| summary.append(f"**{key}:** {answer.legend[most_likely]} · {answer.confidence:.1%} · середній бал {answer.score:.2f} з {len(ids)-1}") | |
| p = [answer.probabilities[i] for i in ids] | |
| rows.extend([[key, description, round(float(probability), 6)] for description, probability in zip(descriptions, p, strict=True)]) | |
| return "\n\n".join(summary), rows, response.model_dump(mode="json") | |
| def build_theme(): | |
| return gr.themes.Soft(primary_hue="teal", neutral_hue="slate", font=["Segoe UI", "Arial", "sans-serif"]) | |
| def build_demo(get_service): | |
| with gr.Blocks(title="Модель рішень") as demo: | |
| gr.Markdown("# Модель рішень\n### Текст звернення → відділ, повернення коштів, тон") | |
| gr.Markdown("Вставте звернення українською або англійською. Модель оцінить кожну відповідь і покаже ймовірності. " | |
| "Це експериментальний навчальний сервіс; результати оцінювання наведено в описі проєкту.") | |
| gr.Markdown("**Обмеження цієї версії:** прохання повернути кошти й тон іноді визначаються помилково, особливо українською. " | |
| "Перевіряйте результат перед рішенням щодо клієнта.") | |
| with gr.Row(): | |
| with gr.Column(scale=5): | |
| state = gr.Textbox(label="Звернення клієнта", lines=8, placeholder="Опишіть ситуацію та головне прохання…") | |
| with gr.Accordion("Запитання та критерії — можна редагувати", open=False): | |
| gr.Markdown("`noul` — так/ні; `choice` — вибір за описами; `score` — рівні від найнижчого до найвищого. " | |
| "Кожне запитання має унікальний ідентифікатор. До 8 запитань і 8 варіантів.") | |
| questions = gr.Code(label="Запитання", language="json", value=json.dumps(default_questions(), ensure_ascii=False, indent=2), lines=18) | |
| with gr.Row(): | |
| submit = gr.Button("Проаналізувати", variant="primary") | |
| clear = gr.ClearButton(value="Очистити") | |
| with gr.Column(scale=5): | |
| summary = gr.Markdown("Рішення з’являться тут після аналізу.") | |
| probabilities = gr.Dataframe(headers=["Запитання", "Варіант відповіді", "Імовірність"], | |
| datatype=["str", "str", "number"], interactive=False, label="Усі варіанти", | |
| wrap=True, column_widths=["20%", "60%", "20%"]) | |
| with gr.Accordion("Відповідь JSON", open=False): | |
| output = gr.JSON(label="Результат") | |
| gr.Markdown("**Спробуйте приклад**") | |
| examples = [ | |
| ("Повернення коштів", "Вітаю! З мене двічі списали оплату за місячну підписку. Поверніть, будь ласка, зайве.", "uk"), | |
| ("Технічна помилка", "Ваш застосунок знову вилетів! Третій день не можу відкрити звіт. Негайно виправте це, інакше піду до конкурентів.", "uk"), | |
| ("Нова покупка — EN", "Hello! Could you send a quote for twenty team subscriptions?", "en"), | |
| ("Заперечення — EN", "I am frustrated by the delay, but I am not asking for a refund. Please fix the broken export.", "en"), | |
| ] | |
| with gr.Row(): | |
| for label, text, language in examples: | |
| button = gr.Button(label) | |
| button.click(lambda t=text, lang=language: (t, json.dumps(default_questions(lang), ensure_ascii=False, indent=2)), | |
| outputs=[state, questions], api_name=False, queue=False) | |
| gr.Markdown("Шкала має індекси від 0. Дробовий бал — середнє за ймовірностями рівнів. " | |
| "Тексти не зберігаються в історії сервісу. [Опис і результати](https://huggingface.co/spaces/xstard/decision-model) · [API](/docs)") | |
| def analyze(text, question_text): | |
| try: | |
| return run_ui(get_service(), text, question_text) | |
| except ModelNotReady as exc: | |
| raise gr.Error(str(exc)) from None | |
| except (ValueError, TypeError): | |
| raise gr.Error("Перевірте текст, JSON запитань і критерії. До 512 токенів на запитання; скоротіть задовгий ввід.") from None | |
| submit.click(analyze, inputs=[state, questions], outputs=[summary, probabilities, output], api_name=False) | |
| clear.add([state, probabilities, output]) | |
| clear.click(lambda: "Рішення з’являться тут після аналізу.", outputs=summary, api_name=False) | |
| return demo.queue(default_concurrency_limit=1, max_size=16) | |