AminFaraji commited on
Commit
968efc4
·
verified ·
1 Parent(s): c92d14f

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +5 -235
app.py CHANGED
@@ -1,236 +1,6 @@
1
- print(55)
2
- import argparse
3
- # from dataclasses import dataclass
4
- from langchain.prompts import ChatPromptTemplate
5
 
6
- try:
7
- from langchain_community.vectorstores import Chroma
8
- except:
9
- from langchain_community.vectorstores import Chroma
10
-
11
- # from langchain.document_loaders import DirectoryLoader
12
- from langchain_community.document_loaders import DirectoryLoader
13
- from langchain.text_splitter import RecursiveCharacterTextSplitter
14
- from langchain.schema import Document
15
- # from langchain.embeddings import OpenAIEmbeddings
16
- #from langchain_openai import OpenAIEmbeddings
17
- from langchain_community.vectorstores import Chroma
18
- import openai
19
- from dotenv import load_dotenv
20
- import os
21
- import shutil
22
- import torch
23
- from langchain_experimental.text_splitter import SemanticChunker
24
- from typing import List
25
- import re
26
- import warnings
27
- from typing import List
28
-
29
- import torch
30
- from langchain import PromptTemplate
31
- from langchain.chains import ConversationChain
32
- from langchain.chains.conversation.memory import ConversationBufferWindowMemory
33
- from langchain.llms import HuggingFacePipeline
34
- from langchain.schema import BaseOutputParser
35
- from transformers import (
36
- AutoModelForCausalLM,
37
- AutoTokenizer,
38
- StoppingCriteria,
39
- StoppingCriteriaList,
40
- pipeline,
41
- )
42
-
43
-
44
- MODEL_NAME = "tiiuae/falcon-7b-instruct"
45
-
46
- model = AutoModelForCausalLM.from_pretrained(
47
- MODEL_NAME, trust_remote_code=True, device_map="auto",offload_folder="offload"
48
- )
49
- model = model.eval()
50
-
51
- tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME)
52
- print(f"Model device: {model.device}")
53
-
54
- from transformers import AutoModel,AutoTokenizer
55
- model2 = AutoModel.from_pretrained("sentence-transformers/all-MiniLM-L6-v2")
56
- tokenizer2 = AutoTokenizer.from_pretrained("sentence-transformers/all-MiniLM-L6-v2")
57
-
58
-
59
- # this shoub be used when we can not use sentence_transformers (which reqiures transformers==4.39. we cannot use
60
- # this version since causes using large amount of RAm when loading falcon model)
61
- # a custom embedding
62
- #from sentence_transformers import SentenceTransformer
63
-
64
- warnings.filterwarnings("ignore", category=UserWarning)
65
-
66
-
67
- class MyEmbeddings:
68
- def __init__(self):
69
- #self.model = SentenceTransformer("sentence-transformers/all-MiniLM-L6-v2")
70
- self.model=model2
71
-
72
- def embed_documents(self, texts: List[str]) -> List[List[float]]:
73
- inputs = tokenizer2(texts, padding=True, truncation=True, return_tensors="pt")
74
-
75
- # Get the model outputs
76
- with torch.no_grad():
77
- outputs = self.model(**inputs)
78
-
79
- # Mean pooling to get sentence embeddings
80
- embeddings = outputs.last_hidden_state.mean(dim=1)
81
- return [embeddings[i].tolist() for i, sentence in enumerate(texts)]
82
- def embed_query(self, query: str) -> List[float]:
83
- inputs = tokenizer2(query, padding=True, truncation=True, return_tensors="pt")
84
-
85
- # Get the model outputs
86
- with torch.no_grad():
87
- outputs = self.model(**inputs)
88
-
89
- # Mean pooling to get sentence embeddings
90
- embeddings = outputs.last_hidden_state.mean(dim=1)
91
- return embeddings[0].tolist()
92
-
93
-
94
- embeddings = MyEmbeddings()
95
-
96
- splitter = SemanticChunker(embeddings)
97
-
98
-
99
- CHROMA_PATH = "chroma8"
100
- # call the chroma generated in a directory
101
- db = Chroma(persist_directory=CHROMA_PATH, embedding_function=embeddings)
102
-
103
-
104
-
105
-
106
-
107
-
108
- generation_config = model.generation_config
109
- generation_config.temperature = 0
110
- generation_config.num_return_sequences = 1
111
- generation_config.max_new_tokens = 256
112
- generation_config.use_cache = False
113
- generation_config.repetition_penalty = 1.7
114
- generation_config.pad_token_id = tokenizer.eos_token_id
115
- generation_config.eos_token_id = tokenizer.eos_token_id
116
- generation_config
117
-
118
-
119
- prompt = """
120
- The following is a friendly conversation between a human and an AI. The AI is talkative and provides lots of specific details from its context.
121
-
122
- Current conversation:
123
-
124
- Human: Who is Dwight K Schrute?
125
- AI:
126
- """.strip()
127
- input_ids = tokenizer(prompt, return_tensors="pt").input_ids
128
- input_ids = input_ids.to(model.device)
129
-
130
-
131
-
132
- class StopGenerationCriteria(StoppingCriteria):
133
- def __init__(
134
- self, tokens: List[List[str]], tokenizer: AutoTokenizer, device: torch.device
135
- ):
136
- stop_token_ids = [tokenizer.convert_tokens_to_ids(t) for t in tokens]
137
- self.stop_token_ids = [
138
- torch.tensor(x, dtype=torch.long, device=device) for x in stop_token_ids
139
- ]
140
-
141
- def __call__(
142
- self, input_ids: torch.LongTensor, scores: torch.FloatTensor, **kwargs
143
- ) -> bool:
144
- for stop_ids in self.stop_token_ids:
145
- if torch.eq(input_ids[0][-len(stop_ids) :], stop_ids).all():
146
- return True
147
- return False
148
-
149
-
150
- stop_tokens = [["Human", ":"], ["AI", ":"]]
151
- stopping_criteria = StoppingCriteriaList(
152
- [StopGenerationCriteria(stop_tokens, tokenizer, model.device)]
153
- )
154
-
155
- generation_pipeline = pipeline(
156
- model=model,
157
- tokenizer=tokenizer,
158
- return_full_text=True,
159
- task="text-generation",
160
- stopping_criteria=stopping_criteria,
161
- generation_config=generation_config,
162
- )
163
-
164
- llm = HuggingFacePipeline(pipeline=generation_pipeline)
165
-
166
-
167
- class CleanupOutputParser(BaseOutputParser):
168
- def parse(self, text: str) -> str:
169
- user_pattern = r"\nUser"
170
- text = re.sub(user_pattern, "", text)
171
- human_pattern = r"\nHuman:"
172
- text = re.sub(human_pattern, "", text)
173
- ai_pattern = r"\nAI:"
174
- return re.sub(ai_pattern, "", text).strip()
175
-
176
- @property
177
- def _type(self) -> str:
178
- return "output_parser"
179
-
180
-
181
- template = """
182
- The following
183
- Current conversation:
184
-
185
- {history}
186
-
187
- Human: {input}
188
- AI:""".strip()
189
- prompt = PromptTemplate(input_variables=["history", "input"], template=template)
190
-
191
- memory = ConversationBufferWindowMemory(
192
- memory_key="history", k=6, return_only_outputs=True
193
- )
194
-
195
- chain = ConversationChain(
196
- llm=llm,
197
- memory=memory,
198
- prompt=prompt,
199
- output_parser=CleanupOutputParser(),
200
- verbose=True,
201
- )
202
-
203
-
204
- def get_llama_response(message: str, history: list) -> str:
205
- query_text = message
206
-
207
- results = db.similarity_search_with_relevance_scores(query_text, k=3)
208
- if len(results) == 0 or results[0][1] < 0.5:
209
- print(f"Unable to find matching results.")
210
-
211
-
212
- context_text = "\n\n---\n\n".join([doc.page_content for doc, _score in results])
213
- template = """
214
- The following is a conversation between a human an AI. The AI acts exactly like Dwight K Schrute from the TV show The Office.
215
- Dwight is an experienced and very successful online marketer and salesperson. He is witty, persuasive, uncensored, direct and practical.
216
- Dwight helps with every marketing task is given to him. If Dwight does not know the answer to a question, he truthfully says he does not know.
217
-
218
- Current conversation:
219
- """
220
- s="""
221
- {history}
222
- Human: {input}
223
- AI:""".strip()
224
-
225
-
226
- prompt = PromptTemplate(input_variables=["history", "input"], template=template+context_text+ s)
227
-
228
- #print(template)
229
- print('the answer is',chain(query_text))
230
- chain.prompt=prompt
231
- res = chain(query_text)
232
- return(res["response"])
233
-
234
- import gradio as gr
235
-
236
- gr.ChatInterface(get_llama_response).launch()
 
1
+ import subprocess
2
+ import sys
 
 
3
 
4
+ def install(package):
5
+ subprocess.check_call([sys.executable, "-m", "pip", "install", package])
6
+ install('langchain==0.0.233')