File size: 13,629 Bytes
90f73b4
 
77500c8
90f73b4
 
 
77500c8
90f73b4
 
 
 
 
 
 
2efcbc9
 
 
 
 
90f73b4
 
 
 
 
 
 
89edb56
90f73b4
 
 
 
 
 
 
 
 
 
 
77500c8
90f73b4
 
2efcbc9
90f73b4
640f04d
7e963eb
640f04d
 
 
 
2efcbc9
 
640f04d
 
 
 
 
2efcbc9
34fc7d6
90f73b4
34fc7d6
 
 
ed60244
 
34fc7d6
90f73b4
 
34fc7d6
2efcbc9
611b85e
 
34fc7d6
 
 
 
2efcbc9
611b85e
5c7c910
611b85e
 
 
 
 
 
 
2efcbc9
 
 
640f04d
 
 
 
2efcbc9
640f04d
 
 
2efcbc9
640f04d
2efcbc9
 
 
 
 
 
 
 
 
 
 
640f04d
2efcbc9
640f04d
2efcbc9
 
640f04d
 
 
 
 
 
 
 
 
90f73b4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2efcbc9
 
 
 
90f73b4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2efcbc9
 
 
 
 
90f73b4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2efcbc9
 
 
 
90f73b4
 
 
 
df6b600
90f73b4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
df6b600
90f73b4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
df6b600
90f73b4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
df6b600
90f73b4
 
df6b600
 
 
90f73b4
 
 
 
 
 
df6b600
 
 
 
 
 
90f73b4
 
 
8a93e6d
fb38709
8aaf594
408a4a5
fb38709
 
90f73b4
dfc360a
78d2cad
89edb56
640f04d
 
 
4cb128f
90f73b4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
89edb56
cf284d1
90f73b4
 
2efcbc9
2e2f239
77500c8
df6b600
 
 
77500c8
90f73b4
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
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
# file: app_jp.py
from __future__ import annotations

import os
import sys
from typing import Dict, Iterable, List, Optional, Sequence, Tuple, Union

# ---- Gradio<5 + huggingface_hub>=1.0 compatibility shim (prevents HfFolder import error) ----
try:
    import huggingface_hub as _hub  # noqa: F401
    if not hasattr(_hub, "HfFolder"):
        class _HfFolder:
            @staticmethod
            def get_token() -> Optional[str]:
                return (
                    os.getenv("HUGGINGFACEHUB_API_TOKEN")
                    or os.getenv("HF_TOKEN")
                    or os.getenv("HF_HOME_TOKEN")
                )
        _hub.HfFolder = _HfFolder  # type: ignore[attr-defined]
    if not hasattr(_hub, "whoami"):
        def _whoami(token: Optional[str] = None) -> Dict[str, str]:
            return {}
        _hub.whoami = _whoami  # type: ignore[attr-defined]
except Exception:
    pass

import httpx
import gradio as gr
from huggingface_hub import InferenceClient, __version__ as _hub_ver

# Optional: print versions once for debugging
try:
    import importlib.metadata as _md
    _gr_ver = _md.version("gradio")
    print(f"[startup] gradio={_gr_ver} huggingface_hub={_hub_ver}", file=sys.stderr)
except Exception:
    pass

ROUTER_BASE = "https://router.huggingface.co"

# ---------- Styling (FIXED: don't override .gradio-container layout) ----------
css = """
body {
  background-image: url('https://cdn-uploads.huggingface.co/production/uploads/67351c643fe51cb1aa28f2e5/GdA9eNQKjOQjE6q47km3l.jpeg');
  background-size: cover;
  background-position: center;
  background-repeat: no-repeat;
}

/* ✅ FIX: do NOT set display:flex / justify-content on .gradio-container */
.gradio-container {
  min-height: 100vh;
  padding-top: 2rem;
  padding-bottom: 2rem;
}

#title-container {
  background-color: rgba(255, 255, 255, 0.85);
  border-radius: 16px;
  padding: 1.5rem 2rem;
  margin: 2rem 0;
  width: fit-content;
  max-width: 350px;
  text-align: left;
  box-shadow: 0 0 12px rgba(0, 0, 0, 0.1);
  margin-left: 0rem;
}

#title-container h1 {
  color: #222 !important;
  font-size: 4rem;
  font-family: 'Noto Sans JP', sans-serif;
  margin: 0;
}

#title-container .subtitle {
  font-size: 1.1rem;
  font-family: 'Noto Sans', sans-serif;
  color: #222 !important;
  margin-top: 0.5rem;
  margin-bottom: 0;
  width: 100%;
  display: block;
}

/* ✅ FIX: make chat panel a vertical flex container;
   let chatbot area scroll instead of the entire panel fighting ChatInterface */
#chat-panel {
  background-color: rgba(255, 255, 255, 0.85);
  padding: 2rem;
  border-radius: 12px;

  width: 100%;
  max-width: 700px;
  height: 70vh;

  box-shadow: 0 0 12px rgba(0, 0, 0, 0.3);

  display: flex;
  flex-direction: column;
  gap: 1rem;

  overflow: hidden; /* important */
}

/* ✅ FIX: let the chat transcript scroll */
#chat-panel .chatbot {
  flex: 1;
  overflow-y: auto;
  min-height: 0; /* crucial for flex children scrolling */
}

/* (Optional) keep your existing title styling */
.gradio-container .chatbot h1 {
   color: var(--custom-title-color) !important;
   font-family: 'Noto Sans', serif !important;
   font-size: 5rem !important;
   font-weight: bold !important;
   text-align: center !important;
   margin-bottom: 1.5rem !important;
   width: 100%;
}
"""

# ---------- JLPT prompt ----------
def level_to_prompt_japanese(level: str) -> str:
    return {
        "N5": "You are a kind Japanese tutor. Respond only to what the user asks. Use simple greetings, basic vocabulary, and Romaji. Provide English explanations and avoid off-topic content or voice suggestions.",
        "N4": "You are a patient Japanese tutor. Use short Japanese phrases with Romaji and English explanations. Introduce basic Kanji but avoid tangents or voice interaction.",
        "N3": "You are a helpful Japanese tutor. Use mostly Japanese with Romaji in parentheses. Include essential grammar or Kanji only if relevant to the user’s question.",
        "N2": "You are a fluent Japanese tutor. Respond only in Japanese unless clarification is requested. Use Kanji with Furigana or Hiragana, and remain on-topic.",
        "N1": "You are a Japanese language professor. Respond entirely in advanced Japanese using native expressions, Keigo (敬語), and idioms. Do not include translations or voice references unless explicitly asked."
    }.get(level, "You are a helpful Japanese tutor.")

# ---------- Types & shaping ----------
GradioMessage = Dict[str, str]
HistoryItem = Union[Tuple[str, str], GradioMessage]
History = Optional[Sequence[HistoryItem]]

def _history_to_messages(history: History) -> List[GradioMessage]:
    msgs: List[GradioMessage] = []
    if not history:
        return msgs
    for item in history:
        if isinstance(item, tuple) and len(item) == 2:
            u, a = item
            if u:
                msgs.append({"role": "user", "content": u})
            if a:
                msgs.append({"role": "assistant", "content": a})
        elif isinstance(item, dict) and "role" in item and "content" in item:
            if item["role"] != "system":
                msgs.append({"role": item["role"], "content": item["content"]})
    return msgs

def coerce_to_messages(
    message: Union[str, List[GradioMessage]],
    history: History,
    system_text: str,
) -> List[GradioMessage]:
    if isinstance(message, list) and all(isinstance(m, dict) and "role" in m for m in message):
        user_msgs = [m for m in message if m.get("role") != "system"]
        return [{"role": "system", "content": system_text}, *user_msgs]
    msgs = [{"role": "system", "content": system_text}, *_history_to_messages(history)]
    if isinstance(message, str) and message:
        msgs.append({"role": "user", "content": message})
    return msgs

# ---------- Token & model helpers ----------
def get_token(user_token: Optional[str]) -> str:
    tok = user_token or os.getenv("HUGGINGFACEHUB_API_TOKEN") or os.getenv("HF_TOKEN")
    if not tok:
        raise RuntimeError("トークンが必要です(Hugging Faceの“Make calls to Inference Providers”権限が必要)。")
    return tok

def list_models(token: str) -> List[str]:
    r = httpx.get(
        f"{ROUTER_BASE}/v1/models",
        headers={"Authorization": f"Bearer {token}"},
        timeout=30
    )
    r.raise_for_status()
    data = r.json()
    return [m["id"] for m in data.get("data", []) if isinstance(m, dict) and "id" in m]

def choose_model(token: str, requested: Optional[str]) -> tuple[str, Optional[str]]:
    prefs = [
        "meta-llama/Llama-3.1-8B-Instruct",
        "mistralai/Mixtral-8x7B-Instruct-v0.1",
        "Qwen/Qwen2.5-7B-Instruct",
        "deepseek-ai/DeepSeek-R1",
    ]
    note: Optional[str] = None
    try:
        available = list_models(token)
    except Exception:
        return (requested or "meta-llama/Llama-3.1-8B-Instruct"), None

    if requested and requested in available:
        return requested, None

    for mid in prefs:
        if mid in available:
            if requested and requested not in available:
                note = f"指定のモデル『{requested}』は利用不可です。『{mid}』を使用します。"
            elif not requested:
                note = f"モデル未指定のため『{mid}』を使用します。"
            return mid, note

    if available:
        chosen = available[0]
        note = (
            f"指定のモデル『{requested}』は利用不可です。『{chosen}』を使用します。"
            if requested else f"モデル未指定のため『{chosen}』を使用します。"
        )
        return chosen, note

    return (requested or "meta-llama/Llama-3.1-8B-Instruct"), "トークンで利用可能なモデルが見つかりません。"

# ---------- Stream chunk extractor ----------
def _extract_piece(chunk) -> Optional[str]:
    try:
        choices = getattr(chunk, "choices", None)
        if choices is None and isinstance(chunk, dict):
            choices = chunk.get("choices")
        if not choices:
            return None
        first = choices[0] if len(choices) > 0 else None
        if not first:
            return None
        delta = getattr(first, "delta", None)
        if delta is None and isinstance(first, dict):
            delta = first.get("delta")
        if not delta:
            return None
        piece = getattr(delta, "content", None)
        if piece is None and isinstance(delta, dict):
            piece = delta.get("content")
        return piece
    except Exception:
        return None

# ---------- Streaming via HF Router ----------
def stream_chat(
    client: InferenceClient,
    *,
    model_id: str,
    messages: List[GradioMessage],
    max_tokens: int,
    temperature: float,
    top_p: float,
) -> Iterable[str]:
    buf = ""
    try:
        events = client.chat.completions.create(
            model=model_id,
            messages=messages,
            max_tokens=max_tokens,
            temperature=temperature,
            top_p=top_p,
            stream=True,
        )
        for ev in events:
            piece = _extract_piece(ev)
            if piece:
                buf += piece
                yield buf
    except Exception as e:
        msg = str(e)
        if any(x in msg for x in ("api-inference.huggingface.co", "410", "404")):
            yield "申し訳ありません!旧エンドポイントは廃止されました。最新のhuggingface_hubとRouter対応モデルをご利用ください。"
        elif "model_not_found" in msg or "does not exist" in msg:
            yield f"申し訳ありません!モデル『{model_id}』が見つからない/利用できません。『モデル一覧』で利用可能なIDを選んでください。"
        elif any(x in msg for x in ("401", "403", "Unauthorized", "permission")):
            yield "申し訳ありません!認証エラーです。Inference Providers権限付きのHFトークンを指定してください。"
        else:
            yield f"申し訳ありません!エラーが発生しました: {msg}"

# ---------- Gradio callback (FIXED: single continuous stream, no separate note-yield) ----------
def respond(
    message: Union[str, List[GradioMessage]],
    history: History,
    user_level: str,
    max_tokens: int,
    temperature: float,
    top_p: float,
    model_id: str,
    hf_token: Optional[str],
):
    system_message = level_to_prompt_japanese(user_level)
    msgs = coerce_to_messages(message, history, system_message)

    max_tokens = int(max(1, min(int(max_tokens), 4096)))
    temperature = float(max(0.0, min(float(temperature), 4.0)))
    top_p = float(max(0.0, min(float(top_p), 1.0)))

    try:
        token = get_token(hf_token)
    except Exception as e:
        yield f"申し訳ありません!{e}"
        return

    chosen_model, note = choose_model(token, (model_id or "").strip() or None)
    prefix = f"ℹ️ {note}\n\n" if note else ""

    client = InferenceClient(api_key=token)

    first = True
    for chunk in stream_chat(
        client,
        model_id=chosen_model,
        messages=msgs,
        max_tokens=max_tokens,
        temperature=temperature,
        top_p=top_p,
    ):
        if first and prefix:
            yield prefix + chunk
            first = False
        else:
            yield chunk

# ---------- UI ----------
with gr.Blocks(css=css) as demo:
    gr.HTML("""
    <div id="title-container">
      <h1>先生</h1>
      <p class="subtitle">Japanese Tutor</p>
    </div>
    """)

    with gr.Column(elem_id="chat-panel"):
        with gr.Accordion("Advanced Settings", open=False):
            user_level = gr.Dropdown(
                choices=["N5", "N4", "N3", "N2", "N1"],
                value="N5",
                label="Your Japanese Level (JLPT)"
            )
            max_tokens = gr.Slider(1, 4096, value=400, step=1, label="Response Length")
            temperature = gr.Slider(0.0, 2.0, value=0.6, step=0.1, label="Creativity")
            top_p = gr.Slider(0.0, 1.0, value=0.85, step=0.05, label="Dynamic Text Sampling")
            model_id = gr.Textbox(
                label="Model (HF Inference Providers)",
                value="meta-llama/Llama-3.1-8B-Instruct",
                placeholder="Leave blank to auto-pick; e.g. mistralai/Mixtral-8x7B-Instruct-v0.1"
            )
            hf_token = gr.Textbox(
                label="Hugging Face Token",
                type="password",
                placeholder="hf_xxx — needs 'Make calls to Inference Providers'"
            )
            with gr.Row():
                list_btn = gr.Button("モデル一覧(トークンで利用可能)")
                models_box = gr.Textbox(label="Available models", lines=10)

        def list_models_ui(tok: Optional[str]) -> str:
            try:
                token = get_token(tok)
                models = list_models(token)
                if not models:
                    return "利用可能なモデルが見つかりません。"
                return "\n".join(models)
            except Exception as e:
                return f"モデル一覧取得エラー: {e}"

        list_btn.click(list_models_ui, inputs=[hf_token], outputs=[models_box])

        gr.ChatInterface(
            fn=respond,
            additional_inputs=[user_level, max_tokens, temperature, top_p, model_id, hf_token],
            type="messages",
        )

# ✅ Recommended on Spaces for stable streaming behind proxies
demo = demo.queue()

if __name__ == "__main__":
    demo.launch(server_name="0.0.0.0", server_port=7860, share=False)