Eyadddddddd commited on
Commit
5777353
·
verified ·
1 Parent(s): 0c1db11

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +52 -79
app.py CHANGED
@@ -8,12 +8,14 @@ from PIL import Image
8
  # =========================
9
 
10
  GROQ_API_KEY = os.getenv("GROQ_API_KEY")
11
- # Ideally, use a robust check or default to None if handling locally
12
- if not GROQ_API_KEY:
13
- print("⚠️ GROQ_API_KEY is missing! Ensure it is set in your environment or Secrets.")
14
 
 
15
  try:
16
- client = Groq(api_key=GROQ_API_KEY)
 
 
 
 
17
  except Exception as e:
18
  client = None
19
  print(f"Error initializing Groq client: {e}")
@@ -36,131 +38,102 @@ def image_to_ascii(image_path, output_width=100):
36
  try:
37
  img = Image.open(image_path).convert("L")
38
  w, h = img.size
39
- if w == 0:
40
- return "[Error: image width is zero]"
41
  ratio = h / w
42
  new_height = max(1, int(output_width * ratio * 0.55))
43
  img = img.resize((output_width, new_height))
44
  pixels = img.getdata()
45
  ascii_str = "".join([ASCII_CHARS[pixel // 25] for pixel in pixels])
46
- ascii_art = "\n".join(
47
- ascii_str[i:i + output_width]
48
- for i in range(0, len(ascii_str), output_width)
49
- )
50
  return ascii_art
51
  except Exception as e:
52
- return f"[Error converting image to ASCII: {e}]"
53
 
54
  # =========================
55
- # CHAT FUNCTION (FIXED FOR MESSAGES FORMAT)
56
  # =========================
57
 
58
- def chat_fn(message, history, mode="Normal Chat", model=DEFAULT_MODEL, image=None, include_ascii=False):
59
  try:
60
  if not client:
61
- return "⚠️ Error: Groq client not initialized. Check API Key."
62
 
63
  # 1. Prepare System Prompt
64
  system_prompt = MODE_PROMPTS.get(mode, MODE_PROMPTS["Normal Chat"])
65
  messages = [{"role": "system", "content": str(system_prompt).strip()}]
66
 
67
- # 2. Add History (Now in Dictionary Format)
68
- if isinstance(history, list):
69
- for msg in history:
70
- if isinstance(msg, dict) and "role" in msg and "content" in msg:
71
- messages.append(msg)
72
-
73
- # 3. Handle Image / Current Message
74
- safe_message_text = str(message).strip() if message else ""
 
 
 
 
75
 
76
  if image and include_ascii:
77
  try:
 
78
  ascii_art = image_to_ascii(image)
79
- final_content = f"[ASCII Art from Uploaded Image]\n{ascii_art}\n\nUser message: {safe_message_text}"
80
  except Exception:
81
- final_content = safe_message_text
82
  else:
83
- final_content = safe_message_text
84
 
85
- # Append current user message
86
- if final_content:
87
- messages.append({"role": "user", "content": final_content})
88
- else:
89
- return "⚠️ Error: No message content provided."
90
 
91
- # 4. Call Groq API
 
 
92
  response = client.chat.completions.create(
93
  model=model,
94
  messages=messages
95
  )
96
-
97
  return response.choices[0].message.content
98
 
99
  except Exception as e:
100
  return f"⚠️ Error: {str(e)}"
101
 
102
  # =========================
103
- # UI (FIXED)
104
  # =========================
105
 
106
- with gr.Blocks(title="🦙 NeoHelper — Eyad’s Groq-powered Assistant") as demo:
107
- gr.Markdown("## 🦙 NeoHelper — Eyad’s Groq-powered Assistant")
108
- gr.Markdown("Modes: School Helper, Shopping Assistant, Gaming Help, Normal Chat (English only).")
109
-
110
  with gr.Row():
111
- mode_dd = gr.Dropdown(
112
- choices=list(MODE_PROMPTS.keys()),
113
- value="Normal Chat",
114
- label="Mode"
115
- )
116
- model_dd = gr.Dropdown(
117
- choices=[
118
- "llama-3.1-8b-instant",
119
- "llama-3.1-70b-versatile",
120
- "mixtral-8x7b-instruct",
121
- "gemma2-9b-it"
122
- ],
123
- value=DEFAULT_MODEL,
124
- label="Model"
125
- )
126
 
127
- # FIX 1: Set type="messages" to match the data format Gradio expects
128
- chatbot = gr.Chatbot(height=500, type="messages")
129
 
130
  with gr.Row():
131
- user_input = gr.Textbox(
132
- placeholder="Type your message…",
133
- show_label=False,
134
- lines=2
135
- )
136
  send_btn = gr.Button("Send")
137
 
138
  image_input = gr.Image(type="filepath", label="Upload Image (Optional)")
139
  ascii_toggle = gr.Checkbox(label="Convert image to ASCII", value=False)
140
 
141
- def on_send(msg, history, mode, model, image, include_ascii):
142
- # Initialize history if empty
143
- if history is None:
144
- history = []
145
-
146
- # User message string
147
- user_msg = str(msg).strip() if msg else ""
148
 
149
  # Get response
150
- reply = chat_fn(
151
- user_msg,
152
- history, # Pass history as is (list of dicts)
153
- mode,
154
- model,
155
- image,
156
- include_ascii
157
- )
158
-
159
- # FIX 2: Append dictionaries {role, content} instead of lists [user, bot]
160
- if user_msg:
161
- history.append({"role": "user", "content": user_msg})
162
 
163
- history.append({"role": "assistant", "content": str(reply)})
 
164
 
165
  return history, ""
166
 
 
8
  # =========================
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}")
 
38
  try:
39
  img = Image.open(image_path).convert("L")
40
  w, h = img.size
41
+ if w == 0: return "[Error: Width 0]"
 
42
  ratio = h / w
43
  new_height = max(1, int(output_width * ratio * 0.55))
44
  img = img.resize((output_width, new_height))
45
  pixels = img.getdata()
46
  ascii_str = "".join([ASCII_CHARS[pixel // 25] for pixel in pixels])
47
+ ascii_art = "\n".join(ascii_str[i:i + output_width] for i in range(0, len(ascii_str), output_width))
 
 
 
48
  return ascii_art
49
  except Exception as e:
50
+ return f"[Error: {e}]"
51
 
52
  # =========================
53
+ # CHAT FUNCTION (ADAPTER FOR OLD GRADIO)
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. Convert Old Gradio History (Tuples) to Groq Format (Dicts)
66
+ # History comes in as: [['User msg 1', 'Bot msg 1'], ['User msg 2', 'Bot msg 2']]
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
+ # REMOVED type="messages" to fix your error
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
133
+ reply = chat_fn(msg, history, mode, model, img, ascii_on)
 
 
 
 
 
 
 
 
 
 
 
134
 
135
+ # Append as a TUPLE (List of 2 items) for older Gradio versions
136
+ history.append([str(msg), str(reply)])
137
 
138
  return history, ""
139