enpaiva commited on
Commit
4043b0f
·
verified ·
1 Parent(s): aba845e

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +168 -0
app.py ADDED
@@ -0,0 +1,168 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # @title Think Paraguayo
2
+
3
+ import os
4
+ import random
5
+ import time
6
+
7
+ os.system("pip install gradio, llama_index, ragatouille, llama-cpp-python")
8
+ os.system("git clone https://github.com/EnPaiva93/think-paraguayo-space-aux.git")
9
+ os.system("wget https://huggingface.co/thinkPy/gua-a_ft-v0.1_mistral-7b_GGUF/resolve/main/gua-a_mistral-7b_q4_K_M.gguf -O model.gguf")
10
+
11
+ from llama_cpp import Llama
12
+ import gradio as gr
13
+ from ragatouille import RAGPretrainedModel
14
+ from llama_index.core import Document, SimpleDirectoryReader
15
+ from llama_index.core.node_parser import SentenceSplitter
16
+
17
+ max_seq_length = 512 # Choose any! We auto support RoPE Scaling internally!
18
+
19
+ prompt = """Responde a preguntas de forma clara, amable, concisa y solamente en el lenguaje español, sobre el libro Ñande Ypykuéra.
20
+ Contexto
21
+ -------------------------
22
+ {}
23
+ -------------------------
24
+ ### Pregunta:
25
+ {}
26
+ ### Respuesta:
27
+ {}"""
28
+
29
+ # Initialize the LLM
30
+ llm = Llama(model_path="model.gguf",
31
+ n_ctx=512,
32
+ n_threads=2)
33
+
34
+ DOC_PATH = "/app/think-paraguayo-space-aux/index"
35
+
36
+ print(os.getcwd())
37
+
38
+ documents = SimpleDirectoryReader(input_files=["/app/think-paraguayo-space-aux/libro.txt"]).load_data()
39
+
40
+ parser = SentenceSplitter(chunk_size=128, chunk_overlap=64)
41
+ nodes = parser.get_nodes_from_documents(
42
+ documents, show_progress=False
43
+ )
44
+ list_nodes = [node.text for node in nodes]
45
+
46
+ print(os.getcwd())
47
+
48
+ if os.path.exists(DOC_PATH):
49
+ RAG = RAGPretrainedModel.from_index(DOC_PATH)
50
+ else:
51
+ RAG = RAGPretrainedModel.from_pretrained("AdrienB134/ColBERTv2.0-spanish-mmarcoES")
52
+ my_documents = list_nodes
53
+ index_path = RAG.index(index_name=DOC_PATH, max_document_length= 100, collection=my_documents)
54
+
55
+ # def convert_list_to_dict(lst):
56
+ # res_dct = {i: lst[i] for i in range(len(lst))}
57
+ # return res_dct
58
+
59
+ def reformat_rag(results_rag):
60
+ if results_rag is not None:
61
+ return [result["content"] for result in results_rag]
62
+ else:
63
+ return [""]
64
+
65
+ # def response(query: str = "Quien es gua'a?", context: str = ""):
66
+ # # print(base_prompt.format(query,""))
67
+ # inputs = tokenizer([base_prompt.format(query,"")], return_tensors = "pt").to("cuda")
68
+ # outputs = model.generate(**inputs, max_new_tokens = 128, temperature = 0.1, repetition_penalty=1.15, pad_token_id=tokenizer.eos_token_id)
69
+ # return tokenizer.batch_decode(outputs[0][inputs["input_ids"].shape[1]:].unsqueeze(0), skip_special_tokens=True)[0]
70
+
71
+
72
+ def chat_stream_completion(message, history):
73
+
74
+ context = reformat_rag(RAG.search(message, k=1))
75
+ context = " \n ".join(context)
76
+
77
+ full_prompt = prompt.format(context,message,"")
78
+ print(full_prompt)
79
+
80
+ response = llm.create_completion(
81
+ prompt=full_prompt,
82
+ temperature=0.01,
83
+ max_tokens=256,
84
+ stream=True
85
+ )
86
+
87
+ # print(response)
88
+
89
+ message_repl = ""
90
+ for chunk in response:
91
+ if len(chunk['choices'][0]["text"]) != 0:
92
+ # print(chunk)
93
+ message_repl = message_repl + chunk['choices'][0]["text"]
94
+ yield message_repl
95
+
96
+
97
+ # def answer_question(pipeline, character, question):
98
+ # def answer_question(question):
99
+ # # context = reformat_rag(RAG.search(question, k=2))
100
+ # # context = " \n ".join(context)
101
+ # yield chat_stream_completion(question, None)
102
+
103
+ # def answer_question(question):
104
+ # context = reformat_rag(RAG.search(question, k=2))
105
+ # context = " \n ".join(context)
106
+ # return response(question, "")
107
+
108
+ # def random_element():
109
+ # return random.choice(list_nodes)
110
+
111
+ # clear_output()
112
+ print("Importación Completada.. OK")
113
+
114
+ css = """
115
+ h1 {
116
+ font-size: 32px;
117
+ text-align: center;
118
+ }
119
+ h2 {
120
+ text-align: center;
121
+ }
122
+ img {
123
+ height: 750px; /* Reducing the image height */
124
+ }
125
+ """
126
+
127
+ def main():
128
+ with gr.Blocks(css=css) as demo:
129
+ gr.Markdown("# Think Paraguayo")
130
+ gr.Markdown("## Conoce la cultura guaraní!!")
131
+
132
+ with gr.Row(variant='panel'):
133
+ with gr.Column(scale=1):
134
+ gr.Image(value="/app/think-paraguayo-space-aux/think_paraguayo.jpeg", type="filepath", label="Imagen Estática")
135
+
136
+ with gr.Column(scale=1):
137
+ # with gr.Row():
138
+ # button = gr.Button("Cuentame ...")
139
+ # with gr.Row():
140
+
141
+ # textbox = gr.Textbox(label="", interactive=False, value=random_element())
142
+ # button.click(fn=random_element, inputs=[], outputs=textbox)
143
+
144
+ # with gr.Row():
145
+ chatbot = gr.ChatInterface(
146
+ fn=chat_stream_completion,
147
+ retry_btn = None,
148
+ stop_btn = None,
149
+ undo_btn = None
150
+ ).queue()
151
+ # with gr.Row():
152
+ # msg = gr.Textbox()
153
+ # with gr.Row():
154
+ # clear = gr.ClearButton([msg, chatbot])
155
+
156
+ # def respond(message, chat_history):
157
+ # bot_message = answer_question(message)
158
+ # print(bot_message)
159
+ # chat_history.append((message, bot_message))
160
+ # time.sleep(2)
161
+ # return "", chat_history
162
+
163
+ # msg.submit(chat_stream_completion, [msg, chatbot], [msg, chatbot])
164
+
165
+
166
+ demo.launch(share=True, inline= False, debug=True)
167
+
168
+ main()