Nafiul Huda commited on
Commit
dced06c
·
verified ·
1 Parent(s): 314b597

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +71 -51
app.py CHANGED
@@ -1,95 +1,115 @@
1
  import os
2
  import threading
3
- import asyncio
4
  import gradio as gr
5
  import discord
6
  from discord.ext import commands
7
  from transformers import pipeline
8
  from duckduckgo_search import DDGS
 
9
 
10
- # --- CONFIGURATION ---
11
- # Note: Set your DISCORD_TOKEN in the Hugging Face Space Settings -> Variables and Secrets
 
12
  DISCORD_TOKEN = os.getenv("DISCORD_TOKEN")
13
- MODEL_ID = "google/gemma-3-270m-it"
14
 
15
- # Load the model locally on CPU
16
- print("Loading Gemma 3 270M...")
17
- pipe = pipeline(
18
- "text-generation",
19
- model=MODEL_ID,
20
- device_map="cpu",
21
- torch_dtype="auto"
22
- )
23
 
24
- # --- WEB SEARCH LOGIC ---
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
25
  def web_search(query):
26
- with DDGS() as ddgs:
27
- results = [r['body'] for r in ddgs.text(query, max_results=3)]
28
- return "\n".join(results)
 
 
 
29
 
30
  def generate_response(message, use_web=False):
 
 
 
31
  context = ""
32
  if use_web:
33
  print(f"Searching web for: {message}")
34
  search_results = web_search(message)
35
- context = f"Web Search Results:\n{search_results}\n\nTask: Answer the user query using the information above.\n"
36
-
37
- prompt = f"{context}User: {message}\nAssistant:"
38
- outputs = pipe(prompt, max_new_tokens=256, do_sample=True, temperature=0.7)
39
- return outputs[0]['generated_text'].split("Assistant:")[-1].strip()
40
 
41
- # --- GRADIO INTERFACE (The API) ---
42
- def api_wrapper(text, web_mode):
43
- return generate_response(text, use_web=web_mode)
44
-
45
- demo = gr.Interface(
46
- fn=api_wrapper,
47
- inputs=["text", "checkbox"],
48
- outputs="text",
49
- title="Gemma 3 270M Bot API"
50
- )
 
 
 
 
51
 
52
- # --- DISCORD BOT LOGIC ---
53
  intents = discord.Intents.default()
54
  intents.message_content = True
55
  bot = commands.Bot(command_prefix="!", intents=intents)
56
 
57
  @bot.event
58
  async def on_ready():
59
- print(f'Discord Bot logged in as {bot.user}')
60
 
61
  @bot.event
62
  async def on_message(message):
63
  if message.author == bot.user:
64
  return
65
 
66
- # Command: < message
67
  if message.content.startswith("< "):
68
- query = message.content[2:]
69
- response = generate_response(query, use_web=False)
70
  await message.reply(response)
71
 
72
- # Command: /web message (as a text prefix)
73
  elif message.content.startswith("/web "):
74
- query = message.content[5:]
75
- await message.channel.typing()
76
- response = generate_response(query, use_web=True)
77
- await message.reply(f"**Web Search Result:**\n{response}")
 
78
 
79
- await bot.process_commands(message)
80
-
81
- # Run Discord bot in a separate thread
82
- def run_discord():
83
  if DISCORD_TOKEN:
84
  bot.run(DISCORD_TOKEN)
85
  else:
86
- print("Missing DISCORD_TOKEN. Discord bot will not start.")
87
 
88
- # --- LAUNCH ---
89
  if __name__ == "__main__":
90
- # Start Discord thread
91
- t = threading.Thread(target=run_discord)
92
- t.start()
 
 
 
 
93
 
94
- # Start Gradio (Hugging Face needs this on port 7860)
95
  demo.launch(server_name="0.0.0.0", server_port=7860)
 
1
  import os
2
  import threading
 
3
  import gradio as gr
4
  import discord
5
  from discord.ext import commands
6
  from transformers import pipeline
7
  from duckduckgo_search import DDGS
8
+ from huggingface_hub import login
9
 
10
+ # --- 1. SETUP & AUTHENTICATION ---
11
+ # Fetch tokens from Environment Secrets
12
+ HF_TOKEN = os.getenv("HF_TOKEN")
13
  DISCORD_TOKEN = os.getenv("DISCORD_TOKEN")
 
14
 
15
+ # Authenticate with Hugging Face (Required for Gated Models like Gemma)
16
+ if HF_TOKEN:
17
+ login(token=HF_TOKEN)
18
+ else:
19
+ print("⚠️ WARNING: HF_TOKEN is missing. Model download will fail if the model is gated.")
 
 
 
20
 
21
+ # --- 2. MODEL LOADING (CPU LOCAL) ---
22
+ MODEL_ID = "google/gemma-3-270m-it"
23
+
24
+ print(f"Loading {MODEL_ID} locally on CPU...")
25
+ try:
26
+ pipe = pipeline(
27
+ "text-generation",
28
+ model=MODEL_ID,
29
+ device_map="cpu",
30
+ torch_dtype="auto",
31
+ )
32
+ print("Model loaded successfully!")
33
+ except Exception as e:
34
+ print(f"Error loading model: {e}")
35
+ pipe = None
36
+
37
+ # --- 3. LOGIC: SEARCH & GENERATION ---
38
  def web_search(query):
39
+ try:
40
+ with DDGS() as ddgs:
41
+ results = [r['body'] for r in ddgs.text(query, max_results=3)]
42
+ return "\n- ".join(results)
43
+ except Exception as e:
44
+ return f"Search failed: {e}"
45
 
46
  def generate_response(message, use_web=False):
47
+ if pipe is None:
48
+ return "System Error: Model failed to load."
49
+
50
  context = ""
51
  if use_web:
52
  print(f"Searching web for: {message}")
53
  search_results = web_search(message)
54
+ context = f"Context from Web:\n- {search_results}\n\nInstructions: Answer the user using the context above.\n"
 
 
 
 
55
 
56
+ # Chat template structure for Gemma
57
+ prompt = f"<start_of_turn>user\n{context}{message}<end_of_turn>\n<start_of_turn>model\n"
58
+
59
+ outputs = pipe(
60
+ prompt,
61
+ max_new_tokens=256,
62
+ do_sample=True,
63
+ temperature=0.7,
64
+ truncation=True
65
+ )
66
+ # Extract only the new text
67
+ generated_text = outputs[0]['generated_text']
68
+ response = generated_text.split("<start_of_turn>model\n")[-1].strip()
69
+ return response
70
 
71
+ # --- 4. DISCORD BOT ---
72
  intents = discord.Intents.default()
73
  intents.message_content = True
74
  bot = commands.Bot(command_prefix="!", intents=intents)
75
 
76
  @bot.event
77
  async def on_ready():
78
+ print(f'✅ Discord Bot logged in as {bot.user}')
79
 
80
  @bot.event
81
  async def on_message(message):
82
  if message.author == bot.user:
83
  return
84
 
85
+ # Check for < command
86
  if message.content.startswith("< "):
87
+ user_query = message.content[2:].strip()
88
+ response = generate_response(user_query, use_web=False)
89
  await message.reply(response)
90
 
91
+ # Check for /web command
92
  elif message.content.startswith("/web "):
93
+ user_query = message.content[5:].strip()
94
+ # Send a placeholder while processing
95
+ msg = await message.reply(f"🔎 Searching web for: *{user_query}*...")
96
+ response = generate_response(user_query, use_web=True)
97
+ await msg.edit(content=f"**Result:**\n{response}")
98
 
99
+ # --- 5. EXECUTION ---
100
+ def run_bot():
 
 
101
  if DISCORD_TOKEN:
102
  bot.run(DISCORD_TOKEN)
103
  else:
104
+ print("❌ ERROR: DISCORD_TOKEN is missing. Bot cannot start.")
105
 
 
106
  if __name__ == "__main__":
107
+ # Run Discord Bot in background thread
108
+ threading.Thread(target=run_bot, daemon=True).start()
109
+
110
+ # Run Dummy Gradio App (Required to keep HF Space alive)
111
+ with gr.Blocks() as demo:
112
+ gr.Markdown("## Gemma 3 Discord Bot Running")
113
+ gr.Markdown("Check your Discord server to interact.")
114
 
 
115
  demo.launch(server_name="0.0.0.0", server_port=7860)