Eyadddddddd commited on
Commit
a3fad22
·
verified ·
1 Parent(s): 7e0ce36

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +48 -74
app.py CHANGED
@@ -9,16 +9,13 @@ from PIL import Image
9
 
10
  GROQ_API_KEY = os.getenv("GROQ_API_KEY")
11
 
12
- # Safe client initialization
13
  try:
14
  if not GROQ_API_KEY:
15
- print("⚠️ GROQ_API_KEY is missing! Check Secrets.")
16
  client = None
17
  else:
18
  client = Groq(api_key=GROQ_API_KEY)
19
- except Exception as e:
20
  client = None
21
- print(f"Error initializing Groq client: {e}")
22
 
23
  DEFAULT_MODEL = "llama-3.1-8b-instant"
24
 
@@ -50,96 +47,73 @@ def image_to_ascii(image_path, output_width=100):
50
  return f"[Error: {e}]"
51
 
52
  # =========================
53
- # CHAT FUNCTION (UNIVERSAL COMPATIBILITY)
54
  # =========================
55
 
56
  def chat_fn(message, history, mode, model, image, include_ascii):
57
- try:
58
- if not client:
59
- return "⚠️ Error: Groq client not initialized."
60
-
61
- # 1. Prepare System Prompt
62
- system_prompt = MODE_PROMPTS.get(mode, MODE_PROMPTS["Normal Chat"])
63
- messages = [{"role": "system", "content": str(system_prompt).strip()}]
64
-
65
- # 2. MANUAL CONVERSION: Old Gradio (Tuples) -> Groq (Dicts)
66
- # History format received: [['User Hi', 'Bot Hello'], ['User How are you', 'Bot Good']]
67
- for pair in history:
68
- if isinstance(pair, (list, tuple)) and len(pair) == 2:
69
- user_h, bot_h = pair
70
- if user_h:
71
- messages.append({"role": "user", "content": str(user_h)})
72
- if bot_h:
73
- messages.append({"role": "assistant", "content": str(bot_h)})
74
-
75
- # 3. Handle Current Message / Image
76
- safe_message = str(message).strip() if message else ""
77
-
78
- if image and include_ascii:
79
- try:
80
- # Gradio passes image path string
81
- ascii_art = image_to_ascii(image)
82
- final_content = f"[ASCII Art from Uploaded Image]\n{ascii_art}\n\nUser message: {safe_message}"
83
- except Exception:
84
- final_content = safe_message
85
- else:
86
- final_content = safe_message
87
-
88
- if not final_content:
89
- return "⚠️ Error: Message is empty."
90
-
91
- messages.append({"role": "user", "content": final_content})
92
-
93
- # 4. Call Groq
94
- response = client.chat.completions.create(
95
- model=model,
96
- messages=messages
97
- )
98
- return response.choices[0].message.content
99
 
 
 
 
 
100
  except Exception as e:
101
- return f"⚠️ Error: {str(e)}"
102
 
103
  # =========================
104
- # UI (COMPATIBLE MODE)
105
  # =========================
106
 
107
- with gr.Blocks(title="NeoHelper") as demo:
108
- gr.Markdown("## 🦙 NeoHelper — Eyad’s Assistant")
109
 
110
  with gr.Row():
111
- mode_dd = gr.Dropdown(list(MODE_PROMPTS.keys()), value="Normal Chat", label="Mode")
112
- model_dd = gr.Dropdown([
113
- "llama-3.1-8b-instant",
114
- "llama-3.1-70b-versatile",
115
- "mixtral-8x7b-instruct",
116
- "gemma2-9b-it"
117
- ], value=DEFAULT_MODEL, label="Model")
118
 
119
- # FIX: Removed 'type="messages"' to support older Gradio versions
120
- chatbot = gr.Chatbot(height=500)
121
 
122
  with gr.Row():
123
- user_input = gr.Textbox(placeholder="Message...", show_label=False, lines=2)
124
- send_btn = gr.Button("Send")
125
 
126
- image_input = gr.Image(type="filepath", label="Upload Image (Optional)")
127
- ascii_toggle = gr.Checkbox(label="Convert image to ASCII", value=False)
128
 
129
- def on_send(msg, history, mode, model, img, ascii_on):
130
- if history is None: history = []
131
-
132
- # Get response string from Groq
133
- reply = chat_fn(msg, history, mode, model, img, ascii_on)
134
 
135
- # FIX: Append as a TUPLE [User, Bot] for the UI
136
- history.append([str(msg), str(reply)])
 
137
 
138
- return history, ""
 
139
 
140
  send_btn.click(
141
- on_send,
142
- inputs=[user_input, chatbot, mode_dd, model_dd, image_input, ascii_toggle],
143
  outputs=[chatbot, user_input]
144
  )
145
 
 
9
 
10
  GROQ_API_KEY = os.getenv("GROQ_API_KEY")
11
 
 
12
  try:
13
  if not GROQ_API_KEY:
 
14
  client = None
15
  else:
16
  client = Groq(api_key=GROQ_API_KEY)
17
+ except Exception:
18
  client = None
 
19
 
20
  DEFAULT_MODEL = "llama-3.1-8b-instant"
21
 
 
47
  return f"[Error: {e}]"
48
 
49
  # =========================
50
+ # CHAT LOGIC
51
  # =========================
52
 
53
  def chat_fn(message, history, mode, model, image, include_ascii):
54
+ if not client:
55
+ return "⚠️ Error: Groq API Key is missing in Settings > Secrets."
56
+
57
+ # 1. Build the messages list for Groq API
58
+ system_prompt = MODE_PROMPTS.get(mode, MODE_PROMPTS["Normal Chat"])
59
+ messages = [{"role": "system", "content": system_prompt}]
60
+
61
+ # 2. Convert Gradio's history (list of lists) to Groq's format (list of dicts)
62
+ if history:
63
+ for user_msg, bot_msg in history:
64
+ if user_msg: messages.append({"role": "user", "content": str(user_msg)})
65
+ if bot_msg: messages.append({"role": "assistant", "content": str(bot_msg)})
66
+
67
+ # 3. Process current input
68
+ user_input_text = str(message).strip()
69
+ if image and include_ascii:
70
+ ascii_art = image_to_ascii(image)
71
+ user_input_text = f"[ASCII Art]\n{ascii_art}\n\nUser: {user_input_text}"
72
+
73
+ messages.append({"role": "user", "content": user_input_text})
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
74
 
75
+ # 4. Get response
76
+ try:
77
+ completion = client.chat.completions.create(model=model, messages=messages)
78
+ return completion.choices[0].message.content
79
  except Exception as e:
80
+ return f"⚠️ Groq Error: {str(e)}"
81
 
82
  # =========================
83
+ # STABLE UI
84
  # =========================
85
 
86
+ with gr.Blocks() as demo:
87
+ gr.Markdown("# 🦙 NeoHelper")
88
 
89
  with gr.Row():
90
+ mode_dd = gr.Dropdown(choices=list(MODE_PROMPTS.keys()), value="Normal Chat", label="Mode")
91
+ model_dd = gr.Dropdown(choices=["llama-3.1-8b-instant", "llama-3.1-70b-versatile"], value=DEFAULT_MODEL, label="Model")
 
 
 
 
 
92
 
93
+ # We leave the chatbot as default. No type="messages" and no complex settings.
94
+ chatbot = gr.Chatbot(height=450)
95
 
96
  with gr.Row():
97
+ user_input = gr.Textbox(placeholder="Ask anything...", show_label=False, scale=4)
98
+ send_btn = gr.Button("Send", variant="primary", scale=1)
99
 
100
+ image_input = gr.Image(type="filepath", label="Image (Optional)")
101
+ ascii_toggle = gr.Checkbox(label="Convert image to ASCII art")
102
 
103
+ def respond(msg, chat_history, mode, model, img, ascii_on):
104
+ # 1. Get the bot's response
105
+ bot_message = chat_fn(msg, chat_history, mode, model, img, ascii_on)
 
 
106
 
107
+ # 2. Append the new interaction as a LIST [User, Bot]
108
+ # This is the "Classic" format that works on all Gradio versions.
109
+ chat_history.append([msg, bot_message])
110
 
111
+ # 3. Return history and clear the input box
112
+ return chat_history, ""
113
 
114
  send_btn.click(
115
+ respond,
116
+ inputs=[user_input, chatbot, mode_dd, model_dd, image_input, ascii_toggle],
117
  outputs=[chatbot, user_input]
118
  )
119