Atualli commited on
Commit
509a8e2
·
verified ·
1 Parent(s): 9e3e9cd

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +22 -113
app.py CHANGED
@@ -1,128 +1,37 @@
1
  import os
2
  import threading
3
- import gradio as gr
4
  import telebot
5
- from huggingface_hub import InferenceClient
6
-
7
- # --- CONFIGURAÇÃO DO TELEGRAM ---
8
- TELEGRAM_TOKEN = os.environ.get("TELEGRAM_TOKEN")
9
- HF_TOKEN = os.environ.get("HF_TOKEN") # Necessário para o bot usar a API
10
-
11
- # Definição do modelo (usando um muito estável e gratuito)
12
- MODEL_ID = "HuggingFaceH4/zephyr-7b-beta"
13
 
14
- # --- LÓGICA DO BOT TELEGRAM ---
15
- if TELEGRAM_TOKEN and HF_TOKEN:
16
- bot = telebot.TeleBot(TELEGRAM_TOKEN)
17
-
18
- # Cliente de IA exclusivo para o Telegram
19
- tele_client = InferenceClient(token=HF_TOKEN, model=MODEL_ID)
20
 
21
- def get_ai_reply(user_message):
22
- try:
23
- # Configuração simples para o Telegram
24
- messages = [
25
- {"role": "system", "content": "You are a friendly Chatbot."},
26
- {"role": "user", "content": user_message}
27
- ]
28
-
29
- # Chamada para a API (sem streaming para simplificar no Telegram)
30
- response = tele_client.chat_completion(
31
- messages,
32
- max_tokens=512,
33
- temperature=0.7,
34
- top_p=0.95
35
- )
36
- return response.choices[0].message.content
37
- except Exception as e:
38
- return f"Erro ao processar IA: {e}"
39
 
40
- @bot.message_handler(func=lambda message: True)
41
- def handle_telegram_message(message):
42
- # Envia ação de "digitando..."
43
- bot.send_chat_action(message.chat.id, 'typing')
44
-
45
- # Pega a resposta da IA
46
- ai_reply = get_ai_reply(message.text)
47
-
48
- # Responde no Telegram
49
- bot.reply_to(message, ai_reply)
50
 
51
- def run_telegram():
52
- print("Iniciando bot do Telegram...")
53
  try:
 
54
  bot.infinity_polling()
55
  except Exception as e:
56
- print(f"Erro no bot Telegram: {e}")
57
-
58
- # Inicia o Telegram em uma thread separada (background)
59
- threading.Thread(target=run_telegram, daemon=True).start()
60
 
 
 
61
  else:
62
- print("AVISO: Tokens (TELEGRAM_TOKEN ou HF_TOKEN) não configurados. O bot do Telegram não iniciará.")
63
-
64
-
65
- # --- LÓGICA DO GRADIO (SEU SITE) ---
66
-
67
- def respond(
68
- message,
69
- history: list[dict[str, str]],
70
- system_message,
71
- max_tokens,
72
- temperature,
73
- top_p,
74
- hf_token: gr.OAuthToken,
75
- ):
76
- # Se o usuário não estiver logado no site, usa o token do ambiente ou falha
77
- token_to_use = hf_token.token if hf_token else HF_TOKEN
78
-
79
- if not token_to_use:
80
- yield "Por favor, faça login com o botão Hugging Face ou configure o HF_TOKEN nos Secrets."
81
- return
82
-
83
- client = InferenceClient(token=token_to_use, model=MODEL_ID)
84
-
85
- messages = [{"role": "system", "content": system_message}]
86
- messages.extend(history)
87
- messages.append({"role": "user", "content": message})
88
-
89
- response = ""
90
-
91
- try:
92
- for msg in client.chat_completion(
93
- messages,
94
- max_tokens=max_tokens,
95
- stream=True,
96
- temperature=temperature,
97
- top_p=top_p,
98
- ):
99
- choices = msg.choices
100
- token = ""
101
- if len(choices) and choices[0].delta.content:
102
- token = choices[0].delta.content
103
-
104
- response += token
105
- yield response
106
- except Exception as e:
107
- yield f"Erro: {e}"
108
-
109
- # Configuração da Interface Visual
110
- chatbot = gr.ChatInterface(
111
- respond,
112
- type="messages",
113
- additional_inputs=[
114
- gr.Textbox(value="You are a friendly Chatbot.", label="System message"),
115
- gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"),
116
- gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),
117
- gr.Slider(minimum=0.1, maximum=1.0, value=0.95, step=0.05, label="Top-p (nucleus sampling)"),
118
- ],
119
- )
120
 
121
- with gr.Blocks() as demo:
122
- # Mantive o botão de login, mas o site funcionará também com o token de ambiente se falhar o login
123
- with gr.Sidebar():
124
- gr.LoginButton()
125
- chatbot.render()
126
 
127
  if __name__ == "__main__":
128
- demo.launch()
 
 
1
  import os
2
  import threading
 
3
  import telebot
4
+ import gradio as gr
 
 
 
 
 
 
 
5
 
6
+ # --- DIAGNÓSTICO ---
7
+ TOKEN = os.environ.get("TELEGRAM_TOKEN")
8
+ print(f"STATUS DO TOKEN: {'Encontrado' if TOKEN else 'NÃO ENCONTRADO'}")
 
 
 
9
 
10
+ # --- BOT TELEGRAM SIMPLES ---
11
+ if TOKEN:
12
+ bot = telebot.TeleBot(TOKEN)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
13
 
14
+ @bot.message_handler(func=lambda m: True)
15
+ def echo(message):
16
+ bot.reply_to(message, "Teste OK! O servidor está rodando.")
 
 
 
 
 
 
 
17
 
18
+ def runner():
19
+ print("Tentando iniciar o polling do Telegram...")
20
  try:
21
+ bot.remove_webhook() # Garante que não tenha conflito
22
  bot.infinity_polling()
23
  except Exception as e:
24
+ print(f"ERRO CRÍTICO NO TELEGRAM: {e}")
 
 
 
25
 
26
+ # Inicia em background
27
+ threading.Thread(target=runner, daemon=True).start()
28
  else:
29
+ print("ERRO: Configure o Secret TELEGRAM_TOKEN nas Settings.")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
30
 
31
+ # --- SITE GRADIO ( para manter o space vivo) ---
32
+ def greet(name):
33
+ return "Olá " + name
 
 
34
 
35
  if __name__ == "__main__":
36
+ iface = gr.Interface(fn=greet, inputs="text", outputs="text")
37
+ iface.launch()