msy127 commited on
Commit
8b945a6
โ€ข
1 Parent(s): 12000da

Upload app.py

Browse files
sentence-transformers/all-MiniLM-L6-v2/app.py ADDED
@@ -0,0 +1,231 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ path_work = "."
2
+
3
+ # hf_token
4
+ from dotenv import load_dotenv
5
+ load_dotenv()
6
+ import os
7
+ hf_token = os.getenv("HUGGINGFACEHUB_API_TOKEN")
8
+
9
+
10
+ # [์„ ํƒ1] ๊ฑฐ๋Œ€๋ชจ๋ธ ๋žญ์ฒด์ธ Custom LLM (HF InferenceClient) - 70B๊ฐ€ ๋ฌด๋ฃŒ!!!, openai๋ณด๋‹ค ์„ฑ๋Šฅ ์•ˆ๋–จ์–ด์ง (์ŠคํŠธ๋ฆฌ๋ฐ์€ ์•„์ง ์•ˆ๋จ)
11
+ # model_name = "tiiuae/falcon-180B-chat"
12
+ model_name="meta-llama/Llama-2-70b-chat-hf"
13
+ # model_name="NousResearch/Llama-2-70b-chat-hf"
14
+ # model_name="meta-llama/Llama-2-13b-chat-hf"
15
+ # model_name="meta-llama/Llama-2-7b-chat-hf"
16
+ # model_name = "HuggingFaceH4/zephyr-7b-alpha"
17
+
18
+ kwargs = {"max_new_tokens":256, "temperature":0.9, "top_p":0.6, "repetition_penalty":1.3, "do_sample":True}
19
+
20
+ # ์ปค์Šคํ…€ LLM
21
+ from pydantic import BaseModel, Field
22
+ from typing import Any, Optional, Dict, List
23
+ from huggingface_hub import InferenceClient
24
+ from langchain.llms.base import LLM
25
+
26
+ class KwArgsModel(BaseModel):
27
+ kwargs: Dict[str, Any] = Field(default_factory=dict)
28
+
29
+ class CustomInferenceClient(LLM, KwArgsModel):
30
+ model_name: str
31
+ inference_client: InferenceClient
32
+
33
+ def __init__(self, model_name: str, hf_token: str, kwargs: Optional[Dict[str, Any]] = None):
34
+ inference_client = InferenceClient(model=model_name, token=hf_token)
35
+ super().__init__(
36
+ model_name=model_name,
37
+ hf_token=hf_token,
38
+ kwargs=kwargs,
39
+ inference_client=inference_client # inference_client ์ธ์ž ์ถ”๊ฐ€
40
+ )
41
+
42
+ def _call(
43
+ self,
44
+ prompt: str,
45
+ stop: Optional[List[str]] = None
46
+ ) -> str:
47
+ if stop is not None:
48
+ raise ValueError("stop kwargs are not permitted.")
49
+ # pdb.set_trace()
50
+ # response_gen = self.__dict__['client'].text_generation(prompt, stream=True, **self.kwargs) # ์ €์žฅ๋œ kwargs๋ฅผ ์‚ฌ์šฉ,
51
+ response_gen = self.inference_client.text_generation(prompt, **self.kwargs, stream=True)
52
+ response = ''.join(response_gen) # ์ œ๋„ˆ๋ ˆ์ดํ„ฐ์˜ ๋ชจ๋“  ๊ฐ’์„ ๋ฌธ์ž์—ด๋กœ ์—ฐ๊ฒฐ
53
+ return response
54
+
55
+ @property
56
+ def _llm_type(self) -> str:
57
+ return "custom"
58
+
59
+ @property
60
+ def _identifying_params(self) -> dict:
61
+ return {"model_name": self.model_name}
62
+
63
+ # ์‚ฌ์šฉ ์˜ˆ์ œ:
64
+ # prompt="How do you make cheese?"
65
+ # prompt = "Tell me the names of the last 10 U.S. presidents"
66
+ prompt="Tell me 10 of the world's largest buildings in high order"
67
+
68
+ llm = CustomInferenceClient(model_name=model_name, hf_token=hf_token, kwargs=kwargs) # hf_token ์‚ฌ์šฉํ•˜๋Š” ๊ฒฝ์šฐ
69
+ # llm = CustomInferenceClient(model_name=model_name, kwargs=kwargs) # hf_token ์‚ฌ์šฉํ•˜์ง€ ์•Š๋Š” ๊ฒฝ์šฐ
70
+
71
+
72
+ # ์ž„๋ฒ ๋”ฉ ๊ฐ์ฒด ์ƒ์„ฑ
73
+ from langchain.embeddings import HuggingFaceInstructEmbeddings
74
+ embeddings = HuggingFaceInstructEmbeddings(
75
+ model_name="sentence-transformers/all-MiniLM-L6-v2",
76
+ cache_folder="./sentence-transformers/all-MiniLM-L6-v2",
77
+ model_kwargs={"device": "cpu"}
78
+ )
79
+
80
+ # ๋ฒกํ„ฐDB ๋กœ๋“œ
81
+ path_work ='.'
82
+
83
+ from langchain.vectorstores import Chroma
84
+ vectordb = Chroma(
85
+ persist_directory = path_work + '/cromadb_llama2-papers',
86
+ embedding_function=embeddings)
87
+
88
+ retriever = vectordb.as_retriever(search_kwargs={"k": 5})
89
+
90
+ # RetrievalQA ์ฒด์ธ ๋งŒ๋“ค๊ธฐ
91
+ from langchain.chains import RetrievalQA
92
+ qa_chain = RetrievalQA.from_chain_type(
93
+ # llm=OpenAI(), # from langchain.llms import OpenAI
94
+ llm=llm,
95
+ chain_type="stuff",
96
+ retriever=retriever,
97
+ return_source_documents=True,
98
+ verbose=True,
99
+ )
100
+ qa_chain
101
+
102
+ # ๊ทธ๋ผ๋””์˜ค
103
+ import json
104
+ import os
105
+ import gradio as gr
106
+
107
+ # Stream text
108
+ def predict(message, chatbot, temperature=0.9, max_new_tokens=512, top_p=0.6, repetition_penalty=1.3,):
109
+
110
+ temperature = float(temperature)
111
+ if temperature < 1e-2: temperature = 1e-2
112
+ top_p = float(top_p)
113
+
114
+ # ํ”„๋กฌํ”„ํŠธ
115
+ # system_message = "\nYou are a psychological counselor who gives friendly and professional counseling on the concerns of Korean clients."
116
+ # input_prompt = f"[INST] <<SYS>>\n{system_message}\n<</SYS>>\n\n "
117
+ # for interaction in chatbot:
118
+ # input_prompt = input_prompt + str(interaction[0]) + " [/INST] " + str(interaction[1]) + " </s><s> [INST] "
119
+
120
+ # input_prompt = input_prompt + str(message) + " [/INST] "
121
+
122
+
123
+ # conversationalRetrievalChain (ํžˆ์Šคํ† ๋ฆฌ๊ฐ€ ์ฒด์ธ ๋‚ด์žฅ ํ”„๋กฌํ”„ํŠธ์— ์ธํ’‹๋จ)
124
+ # chat_history = []
125
+ # for interaction in chatbot:
126
+ # chat_history = chat_history + [(str(interaction[0]), str(interaction[1]))]
127
+ # llm_response = qa_chain_conv({"question": message, "chat_history": chat_history})
128
+ # res_result = llm_response['answer']
129
+
130
+
131
+ # RetrievalQA ์ฒด์ธ (ํžˆ์Šคํ† ๋ฆฌ๊ฐ€ ์ฒด์ธ ๋‚ด์žฅ ํ”„๋กฌํ”„ํŠธ์— ์ธํ’‹ ์•ˆ๋จ)
132
+ llm_response = qa_chain(message)
133
+ res_result = llm_response['result']
134
+
135
+ # conversationalRetrievalChain, RetrievalQA ์ฒด์ธ ๊ณตํ†ต
136
+ res_relevant_doc = [source.metadata['source'] for source in llm_response["source_documents"]]
137
+ response = f"{res_result}" + "\n\n" + "[๋‹ต๋ณ€ ๊ทผ๊ฑฐ ์†Œ์Šค ๋…ผ๋ฌธ (ctrl + click ๏ฟฝ๏ฟฝ์„ธ์š”!)] :" + "\n" + f" \n {res_relevant_doc}"
138
+ print("response: =====> \n", response, "\n\n")
139
+
140
+ #3) json ํ˜•ํƒœ๋กœ ๋ณ€ํ™˜ (api response์™€ ๊ฐ™์€ ํ˜•ํƒœ)
141
+ import json
142
+ tokens = response.split('\n')
143
+ token_list = []
144
+ for idx, token in enumerate(tokens):
145
+ token_dict = {"id": idx + 1, "text": token}
146
+ token_list.append(token_dict)
147
+ response = {"data": {"token": token_list}}
148
+ response = json.dumps(response, indent=4)
149
+
150
+ '''{'data': {'token': [{'id': 1, 'text': 'Artificial intelligence (AI) refers to...'},
151
+ {'id': 2, 'text': 'I hope this information helher questions!'}]}}'''
152
+
153
+ # ===========================================================================
154
+ # ์ŠคํŠธ๋ฆฌ๋ฐ ์‹œ์ž‘ (partial_message)
155
+ response = json.loads(response) # {'data': {'token': [{'id': 1, 'text': '๋‹ต๋ณ€์€ " ์•ˆ๋…•ํ•˜์„ธ์š”. ์ €๋Š” ์†ก์ƒ์ง„ ๋ฐ•์‚ฌ.....
156
+ data_dict = response.get('data', {})
157
+ token_list = data_dict.get('token', [])
158
+
159
+ import time
160
+ partial_message = ""
161
+ # ํ•˜์ด๋ผ์ดํŠธ: .iter_lines() ๋Œ€์‹ ์— token_list๋ฅผ ์ง์ ‘ ์ˆœํšŒํ•ฉ๋‹ˆ๋‹ค.
162
+ for token_entry in token_list:
163
+ if token_entry: # filter out keep-alive new lines (if any)
164
+ try:
165
+ # ํ•˜์ด๋ผ์ดํŠธ: ์ง์ ‘ ์‚ฌ์ „์—์„œ 'id'์™€ 'text'๋ฅผ ์ถ”์ถœํ•ฉ๋‹ˆ๋‹ค.
166
+ token_id = token_entry.get('id', None)
167
+ token_text = token_entry.get('text', None)
168
+
169
+ # time.sleep์œผ๋กœ ๊ธ€์ž ์†๋„ ์กฐ์ ˆํ•˜๋ฉฐ ๊ธ€์ž ๋‚ด๋ณด๋ƒ„
170
+ if token_text: # ์ด ๋ถ€๋ถ„์€ ์›ํ•˜๋Š” ๋Œ€๋กœ ์กฐ์ •ํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.
171
+ # partial_message = partial_message + token_text
172
+ for char in token_text: # ๋ฌธ์ž ํ•˜๋‚˜์”ฉ ์ˆœํšŒ (์ถ”๊ฐ€๋จ)
173
+ partial_message += char # partial_message์— ๋ฌธ์ž ์ถ”๊ฐ€ (๋ณ€๊ฒฝ๋จ)
174
+ yield partial_message
175
+ time.sleep(0.01)
176
+ else:
177
+ # gr.Warning(f"The key 'text' does not exist or is None in this token entry: {token_entry}")
178
+ print(f"[[์›Œ๋‹]] ==> The key 'text' does not exist or is None in this token entry: {token_entry}")
179
+
180
+ except KeyError as e:
181
+ gr.Warning(f"KeyError: {e} occurred for token entry: {token_entry}")
182
+ continue
183
+
184
+ # ํƒ€์ดํ‹€/์„ค๋ช…/์งˆ๋ฌธ์˜ˆ์‹œ
185
+ title = "llama-2 ๋ชจ๋ธ ๊ด€๋ จ ๋…ผ๋ฌธ QA ์„œ๋น„์Šค"
186
+ description = """chat history ์œ ์ง€ ๋ณด๋‹ค๋Š” QA์— ์ถฉ์‹คํ•˜๋„๋ก ์ œ์ž‘๋˜์—ˆ์œผ๋‹ˆ Single turn์œผ๋กœ ํ™œ์šฉ์„ ํ•˜์—ฌ ์ฃผ์„ธ์š”. (chat history ํ™œ์šฉ์€ ๋‹ค๋ฅธ ์ฃผ์ œ๋กœ ๋ณ„๋„ ์ œ์ž‘ ์˜ˆ์ •)"""
187
+ css = """.toast-wrap { display: none !important } """
188
+ examples=[['Can you tell me about the llama-2 model?'],['What is percent accuracy, using the SPP layer as features on the SPP (ZF-5) model?'], ['What is percent accuracy, using the SPP layer as features on the SPP (ZF-5) model?'], ["tell me about method for human pose estimation based on DNNs"]]
189
+
190
+ # ์ข‹์•„์š”
191
+ import gradio as gr
192
+ def vote(data: gr.LikeData):
193
+ if data.liked: print("You upvoted this response: " + data.value)
194
+ else: print("You downvoted this response: " + data.value)
195
+
196
+ # ๊ทธ๋ผ๋””์˜ค (์ธ์ž ์กฐ์ ˆ)
197
+ additional_inputs = [
198
+ # gr.Textbox("", label="Optional system prompt"),
199
+ gr.Slider(label="Temperature", value=0.9, minimum=0.0, maximum=1.0, step=0.05, interactive=True, info="Higher values produce more diverse outputs"),
200
+ gr.Slider(label="Max new tokens", value=256, minimum=0, maximum=4096, step=64, interactive=True, info="The maximum numbers of new tokens"),
201
+ gr.Slider(label="Top-p (nucleus sampling)", value=0.6, minimum=0.0, maximum=1, step=0.05, interactive=True, info="Higher values sample more low-probability tokens"),
202
+ gr.Slider(label="Repetition penalty", value=1.2, minimum=1.0, maximum=2.0, step=0.05, interactive=True, info="Penalize repeated tokens")
203
+ ]
204
+
205
+ chatbot_stream = gr.Chatbot(avatar_images=(
206
+ "https://drive.google.com/uc?id=13rYrN0cH_9tR7GveqO1q2JiyBCqkfCLZ", # https://drive.google.com/uc?id= ๋’ค์— ID๊ฐ’๋งŒ (๋ชจ๋‘ ์‚ฌ์šฉ์ž ์•ก์„ธ์Šค ๊ถŒํ•œ ํ—ˆ์šฉ)
207
+ "https://drive.google.com/uc?id=1tfELAQW_VbPCy6QTRbexRlwAEYo8rSSv"
208
+ ), bubble_full_width = False)
209
+
210
+ chat_interface_stream = gr.ChatInterface(predict,
211
+ title=title,
212
+ description=description,
213
+ # textbox=gr.Textbox(lines=5),
214
+ chatbot=chatbot_stream,
215
+ css=css,
216
+ examples=examples,
217
+ # cache_examples=True,
218
+ # additional_inputs=additional_inputs,
219
+ )
220
+
221
+ # Gradio Demo
222
+ with gr.Blocks() as demo:
223
+
224
+ with gr.Tab("์ŠคํŠธ๋ฆฌ๋ฐ"):
225
+ #gr.ChatInterface(predict, title=title, description=description, css=css, examples=examples, cache_examples=True, additional_inputs=additional_inputs,)
226
+ chatbot_stream.like(vote, None, None)
227
+ chat_interface_stream.render()
228
+
229
+
230
+ demo.queue(concurrency_count=75, max_size=100).launch(debug=True)
231
+