Sumandas990 commited on
Commit
14d9494
·
verified ·
1 Parent(s): 373dbdf

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +53 -50
app.py CHANGED
@@ -1,82 +1,85 @@
1
  import os
2
  import gradio as gr
3
 
4
- # We import lazily inside the function to avoid crashing on startup if the key isn't set.
5
  MODEL = "gpt-4o-mini"
6
 
7
  SYSTEM_HI = "तुम एक सहायक हिन्दी सहायक हो। स्पष्ट, संक्षिप्त और सही उत्तर दो।"
8
  SYSTEM_BN = "তুমি একজন সহায়ক বাংলা সহকারী। সংক্ষিপ্ত, স্পষ্ট এবং সঠিক উত্তর দাও।"
9
 
10
- def chat_fn(history, lang_label):
11
- """
12
- history: list of (user, bot) tuples from gr.Chatbot
13
- lang_label: "हिन्दी" or "বাংলা"
14
- """
15
- # Map UI label -> code
16
- lang = "bn" if lang_label == "বাংলা" else "hi"
17
- sys = SYSTEM_BN if lang == "bn" else SYSTEM_HI
18
-
19
- # Check API key
20
  api_key = os.getenv("OPENAI_API_KEY", "").strip()
21
  if not api_key:
22
- msg = ("OPENAI_API_KEY not set in this Space’s Settings → Variables and secrets."
23
- if lang == "hi" else
24
- "❗ এই স্পেসের Settings → Variables and secrets এ OPENAI_API_KEY সেট করা হয়নি।")
25
- return history + [("", msg)]
26
 
27
- # Import + client only when needed (safer on cold start)
28
- try:
29
- from openai import OpenAI
30
- client = OpenAI(api_key=api_key)
31
- except Exception as e:
32
- err = f"OpenAI client error: {e}"
33
- return history + [("", err if lang == "hi" else f"OpenAI ক্লায়েন্ট ত্রুটি: {e}")]
 
 
 
 
 
 
 
 
 
34
 
35
- # Convert history to OpenAI messages
36
  messages = [{"role": "system", "content": sys}]
37
  for user, bot in history:
38
  if user:
39
- messages.append({"role": "user", content_or_key("content"): user})
40
  if bot:
41
  messages.append({"role": "assistant", "content": bot})
 
42
 
 
 
 
 
 
 
 
 
 
43
  try:
44
- resp = client.chat.completions.create(
45
- model=MODEL,
46
- messages=messages,
47
- temperature=0.6,
48
- max_tokens=400,
49
- )
50
- answer = resp.choices[0].message.content
51
- return history + [("", answer)]
52
  except Exception as e:
53
- err = f"API error: {e}"
54
- return history + [("", err if lang == "hi" else f"API ত্রুটি: {e}")]
55
-
56
- def content_or_key(key_name):
57
- # tiny helper to satisfy static analyzers; keeps code readable above
58
- return key_name
59
 
60
  with gr.Blocks(theme=gr.themes.Soft()) as demo:
61
  gr.Markdown("### 🇮🇳 Indic Chat — हिंदी / বাংলা")
 
62
  lang = gr.Radio(
63
  choices=["हिन्दी", "বাংলা"],
64
  value="हिन्दी",
65
- label="Language"
66
  )
67
- chat = gr.Chatbot(height=420, type="tuple")
68
- txt = gr.Textbox(placeholder="Type in Hindi or Bangla…", autofocus=True)
69
- send = gr.Button("Send")
70
 
71
- def on_user_submit(user_text, chat_state):
72
- if not user_text.strip():
73
- return "", chat_state
74
- return "", chat_state + [(user_text, None)]
75
 
76
- def on_bot_reply(chat_state, lang_label):
77
- return chat_fn(chat_state, lang_label)
78
 
79
- txt.submit(on_user_submit, [txt, chat], [txt, chat]).then(on_bot_reply, [chat, lang], [chat])
80
- send.click(on_user_submit, [txt, chat], [txt, chat]).then(on_bot_reply, [chat, lang], [chat])
 
 
 
 
 
81
 
82
  demo.launch()
 
1
  import os
2
  import gradio as gr
3
 
 
4
  MODEL = "gpt-4o-mini"
5
 
6
  SYSTEM_HI = "तुम एक सहायक हिन्दी सहायक हो। स्पष्ट, संक्षिप्त और सही उत्तर दो।"
7
  SYSTEM_BN = "তুমি একজন সহায়ক বাংলা সহকারী। সংক্ষিপ্ত, স্পষ্ট এবং সঠিক উত্তর দাও।"
8
 
9
+ def call_openai(messages):
 
 
 
 
 
 
 
 
 
10
  api_key = os.getenv("OPENAI_API_KEY", "").strip()
11
  if not api_key:
12
+ raise RuntimeError("OPENAI_API_KEY is not set in Settings → Variables and secrets")
 
 
 
13
 
14
+ # Lazy import so startup doesn't crash if deps missing
15
+ from openai import OpenAI
16
+ client = OpenAI(api_key=api_key)
17
+
18
+ resp = client.chat.completions.create(
19
+ model=MODEL,
20
+ messages=messages,
21
+ temperature=0.6,
22
+ max_tokens=400,
23
+ )
24
+ return resp.choices[0].message.content
25
+
26
+ def build_messages(history, lang_label):
27
+ # lang_label is "हिन्दी" or "বাংলা"
28
+ lang = "bn" if lang_label == "বাংলা" else "hi"
29
+ sys = SYSTEM_BN if lang == "bn" else SYSTEM_HI
30
 
 
31
  messages = [{"role": "system", "content": sys}]
32
  for user, bot in history:
33
  if user:
34
+ messages.append({"role": "user", "content": user})
35
  if bot:
36
  messages.append({"role": "assistant", "content": bot})
37
+ return messages
38
 
39
+ def on_user_submit(user_text, chat_state):
40
+ """Append the user message; bot will fill the reply in the next step."""
41
+ if not user_text.strip():
42
+ return "", chat_state
43
+ chat_state = chat_state + [(user_text, None)]
44
+ return "", chat_state
45
+
46
+ def on_bot_reply(chat_state, lang_label):
47
+ """Call the model and set the reply for the last turn."""
48
  try:
49
+ messages = build_messages(chat_state, lang_label)
50
+ answer = call_openai(messages)
51
+ # put the bot answer into the last tuple
52
+ last_user, _ = chat_state[-1]
53
+ chat_state[-1] = (last_user, answer)
54
+ return chat_state
 
 
55
  except Exception as e:
56
+ last_user, _ = chat_state[-1]
57
+ err_hi = f"त्रुटि: {e}"
58
+ err_bn = f"ত্রুটি: {e}"
59
+ chat_state[-1] = (last_user, err_bn if lang_label == "বাংলা" else err_hi)
60
+ return chat_state
 
61
 
62
  with gr.Blocks(theme=gr.themes.Soft()) as demo:
63
  gr.Markdown("### 🇮🇳 Indic Chat — हिंदी / বাংলা")
64
+
65
  lang = gr.Radio(
66
  choices=["हिन्दी", "বাংলা"],
67
  value="हिन्दी",
68
+ label="Language",
69
  )
 
 
 
70
 
71
+ # ✅ Use 'tuples' (plural)
72
+ chat = gr.Chatbot(height=420, type="tuples")
 
 
73
 
74
+ txt = gr.Textbox(placeholder="Type in Hindi or Bangla…", autofocus=True)
75
+ send = gr.Button("Send")
76
 
77
+ # Wire up: user adds a turn → then bot replies
78
+ txt.submit(on_user_submit, [txt, chat], [txt, chat]).then(
79
+ on_bot_reply, [chat, lang], [chat]
80
+ )
81
+ send.click(on_user_submit, [txt, chat], [txt, chat]).then(
82
+ on_bot_reply, [chat, lang], [chat]
83
+ )
84
 
85
  demo.launch()