beriond commited on
Commit
e2037da
·
verified ·
1 Parent(s): 9ab2538

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +63 -52
app.py CHANGED
@@ -1,64 +1,75 @@
1
  import gradio as gr
2
- from huggingface_hub import InferenceClient
 
 
 
 
 
 
 
 
 
3
 
4
- """
5
- For more information on `huggingface_hub` Inference API support, please check the docs: https://huggingface.co/docs/huggingface_hub/v0.22.2/en/guides/inference
6
- """
7
- client = InferenceClient("HuggingFaceH4/zephyr-7b-beta")
8
 
 
9
 
10
- def respond(
11
- message,
12
- history: list[tuple[str, str]],
13
- system_message,
14
- max_tokens,
15
- temperature,
16
- top_p,
17
- ):
18
- messages = [{"role": "system", "content": system_message}]
19
 
20
- for val in history:
21
- if val[0]:
22
- messages.append({"role": "user", "content": val[0]})
23
- if val[1]:
24
- messages.append({"role": "assistant", "content": val[1]})
 
 
25
 
26
- messages.append({"role": "user", "content": message})
 
 
 
27
 
28
- response = ""
 
29
 
30
- for message in client.chat_completion(
31
- messages,
32
- max_tokens=max_tokens,
33
- stream=True,
34
- temperature=temperature,
35
- top_p=top_p,
36
- ):
37
- token = message.choices[0].delta.content
38
 
39
- response += token
40
- yield response
 
 
 
41
 
 
 
 
 
 
 
 
 
 
42
 
43
- """
44
- For information on how to customize the ChatInterface, peruse the gradio docs: https://www.gradio.app/docs/chatinterface
45
- """
46
- demo = gr.ChatInterface(
47
- respond,
48
- additional_inputs=[
49
- gr.Textbox(value="You are a friendly Chatbot.", label="System message"),
50
- gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"),
51
- gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),
52
- gr.Slider(
53
- minimum=0.1,
54
- maximum=1.0,
55
- value=0.95,
56
- step=0.05,
57
- label="Top-p (nucleus sampling)",
58
- ),
59
- ],
60
- )
61
 
62
-
63
- if __name__ == "__main__":
64
- demo.launch()
 
1
  import gradio as gr
2
+ from langchain import LLMChain, ConversationChain
3
+ from langchain.memory import ConversationBufferMemory
4
+ from langchain.llms import HuggingFacePipeline
5
+ from transformers import pipeline
6
+ from langchain.document_loaders import PyPDFLoader, CSVLoader
7
+ from langchain.text_splitter import RecursiveCharacterTextSplitter
8
+ from langchain.embeddings import HuggingFaceEmbeddings
9
+ from langchain.vectorstores import FAISS
10
+ from langchain.chains import ConversationalRetrievalChain
11
+ from datasets import load_dataset
12
 
13
+ # Modelo Hugging Face
14
+ pipe = pipeline("text-generation", model="mistralai/Mistral-7B-Instruct", max_new_tokens=200, temperature=0.7)
15
+ llm = HuggingFacePipeline(pipeline=pipe)
 
16
 
17
+ memory = ConversationBufferMemory()
18
 
19
+ # PDF loader e vetores
20
+ def init_pdf(path):
21
+ loader = PyPDFLoader(path)
22
+ docs = loader.load_and_split()
23
+ embeddings = HuggingFaceEmbeddings()
24
+ vectorstore = FAISS.from_documents(docs, embeddings)
25
+ return vectorstore
 
 
26
 
27
+ # CSV loader e vetores (ou pandas agent)
28
+ def init_csv(path):
29
+ loader = CSVLoader(path)
30
+ docs = loader.load_and_split()
31
+ embeddings = HuggingFaceEmbeddings()
32
+ vectorstore = FAISS.from_documents(docs, embeddings)
33
+ return vectorstore
34
 
35
+ # Fluxo de retriever
36
+ def make_rag_chain(vectorstore):
37
+ retriever = vectorstore.as_retriever()
38
+ return ConversationalRetrievalChain(llm=llm, retriever=retriever, memory=memory)
39
 
40
+ pdf_chain = None
41
+ csv_chain = None
42
 
43
+ def upload_pdf(uploaded_pdf):
44
+ global pdf_chain
45
+ vectorstore = init_pdf(uploaded_pdf.name)
46
+ pdf_chain = make_rag_chain(vectorstore)
47
+ return "PDF carregado com sucesso."
 
 
 
48
 
49
+ def upload_csv(uploaded_csv):
50
+ global csv_chain
51
+ vectorstore = init_csv(uploaded_csv.name)
52
+ csv_chain = make_rag_chain(vectorstore)
53
+ return "CSV carregado com sucesso."
54
 
55
+ def chat(message):
56
+ if pdf_chain:
57
+ resp = pdf_chain.run({"question":message})
58
+ elif csv_chain:
59
+ resp = csv_chain.run({"question":message})
60
+ else:
61
+ chain = ConversationChain(llm=llm, memory=memory)
62
+ resp = chain.predict(input=message)
63
+ return resp
64
 
65
+ with gr.Blocks() as demo:
66
+ gr.Markdown("## Chatbot com memória — PDF, CSV ou conversa simples")
67
+ pdf_file = gr.File(label="Upload PDF", file_types=['.pdf'])
68
+ csv_file = gr.File(label="Upload CSV", file_types=['.csv'])
69
+ pdf_file.upload(upload_pdf, inputs=pdf_file, outputs="text")
70
+ csv_file.upload(upload_csv, inputs=csv_file, outputs="text")
71
+ chatbot = gr.Chatbot()
72
+ msg = gr.Textbox(placeholder="Digite aqui sua pergunta…")
73
+ msg.submit(lambda m: (msg.clear(), chatbot.append((m, chat(m)))), outputs=chatbot)
 
 
 
 
 
 
 
 
 
74
 
75
+ demo.launch()