ceadibc commited on
Commit
94472f0
·
verified ·
1 Parent(s): 67a60d7

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +58 -46
app.py CHANGED
@@ -1,47 +1,59 @@
1
- from transformers import AutoModelForCausalLM, AutoTokenizer
2
  import gradio as gr
3
- import torch
4
-
5
-
6
- title = "????AI ChatBot"
7
- description = "A State-of-the-Art Large-scale Pretrained Response generation model (DialoGPT)"
8
- examples = [["How are you?"]]
9
-
10
-
11
- tokenizer = AutoTokenizer.from_pretrained("microsoft/DialoGPT-large")
12
- model = AutoModelForCausalLM.from_pretrained("microsoft/DialoGPT-large")
13
-
14
-
15
- def predict(input, history=[]):
16
- # tokenize the new input sentence
17
- new_user_input_ids = tokenizer.encode(
18
- input + tokenizer.eos_token, return_tensors="pt"
19
- )
20
-
21
- # append the new user input tokens to the chat history
22
- bot_input_ids = torch.cat([torch.LongTensor(history), new_user_input_ids], dim=-1)
23
-
24
- # generate a response
25
- history = model.generate(
26
- bot_input_ids, max_length=4000, pad_token_id=tokenizer.eos_token_id
27
- ).tolist()
28
-
29
- # convert the tokens to text, and then split the responses into lines
30
- response = tokenizer.decode(history[0]).split("<|endoftext|>")
31
- # print('decoded_response-->>'+str(response))
32
- response = [
33
- (response[i], response[i + 1]) for i in range(0, len(response) - 1, 2)
34
- ] # convert to tuples of list
35
- # print('response-->>'+str(response))
36
- return response, history
37
-
38
-
39
- gr.Interface(
40
- fn=predict,
41
- title=title,
42
- description=description,
43
- examples=examples,
44
- inputs=["text", "state"],
45
- outputs=["chatbot", "state"],
46
- theme="finlaymacklon/boxy_violet",
47
- ).launch()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import gradio as gr
2
+ from huggingface_hub import InferenceClient
3
+
4
+ # Cliente de inferência com modelo de IA pública
5
+ client = InferenceClient(model="mistralai/Mistral-7B-Instruct-v0.3") # Modelo gratuito e avançado
6
+
7
+ # Função para processar a conversa
8
+ def responder(mensagem, historico):
9
+ mensagens = []
10
+ if historico is None:
11
+ historico = []
12
+
13
+ for item in historico:
14
+ if isinstance(item, list) and len(item) == 2:
15
+ user_msg, bot_msg = item
16
+ mensagens.append({"role": "user", "content": user_msg})
17
+ if bot_msg:
18
+ mensagens.append({"role": "assistant", "content": bot_msg})
19
+
20
+ mensagens.append({"role": "user", "content": mensagem})
21
+ resposta = ""
22
+
23
+ try:
24
+ for mensagem in client.chat_completion(
25
+ mensagens,
26
+ max_tokens=250,
27
+ stream=True,
28
+ temperature=0.2,
29
+ top_p=0.7,
30
+ ):
31
+ if not mensagem or not isinstance(mensagem, dict):
32
+ continue
33
+
34
+ try:
35
+ conteudo = mensagem["choices"][0]["delta"].get("content", "")
36
+ if conteudo.strip():
37
+ resposta += conteudo
38
+ yield resposta
39
+ except (AttributeError, IndexError, KeyError) as e:
40
+ print(f"Erro ao processar mensagem: {e}")
41
+ continue
42
+
43
+ except Exception as e:
44
+ print(f"Erro inesperado: {e}")
45
+ yield "Ocorreu um erro ao gerar a resposta."
46
+
47
+ if not resposta.strip():
48
+ yield "Nenhuma resposta gerada. Tente novamente."
49
+
50
+ # Interface do chat com labels em português
51
+ demo = gr.ChatInterface(
52
+ responder,
53
+ title="Benjamin – Assistente Virtual da CEaD - IBC. Tire suas dúvidas com a minha inteligência artificial! Minha base de conhecimento vai até 2021, por isso posso não trazer respostas precisas sobre pessoas, conceitos, lugares ou fatos históricos. Se isso acontecer, entre em contato com o mediador do curso para obter ajuda mais adequada.",
54
+ textbox=gr.Textbox(label="Campo de mensagem: Digite uma mensagem e depois tecle Enter para enviar"),
55
+ type="messages"
56
+ )
57
+
58
+ if __name__ == "__main__":
59
+ demo.launch()