soyhehe commited on
Commit
b039d30
·
verified ·
1 Parent(s): 1f6a3c3

Upload 8 files

Browse files
.gitattributes CHANGED
@@ -33,3 +33,5 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
 
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ local_model/tokenizer.json filter=lfs diff=lfs merge=lfs -text
37
+ recipes.csv filter=lfs diff=lfs merge=lfs -text
cooking.py ADDED
@@ -0,0 +1,161 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import pandas as pd
3
+ import faiss
4
+ import torch
5
+ from transformers import AutoModel, AutoTokenizer
6
+ from langchain_community.vectorstores import FAISS
7
+ from langchain.text_splitter import CharacterTextSplitter
8
+ from langchain_huggingface import HuggingFaceEmbeddings
9
+ from langchain.prompts import PromptTemplate
10
+ from langchain_community.chat_models import ChatOllama
11
+ from langchain.schema import Document
12
+
13
+ # GPU 설정
14
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
15
+
16
+ VECTOR_STORE_PATH = "./vectorstore"
17
+ EMBEDDINGS = HuggingFaceEmbeddings(model_name="intfloat/multilingual-e5-small")
18
+
19
+ # CSV 파일에서 데이터를 로드하고 Document 객체로 변환
20
+ def load_csv_to_documents(csv_file):
21
+ df = pd.read_csv(csv_file)
22
+ documents = []
23
+
24
+ # 각 행을 Document 객체로 변환
25
+ for index, row in df.iterrows():
26
+ document_text = f"Name: {row['name']}\nIngredients: {row['recipeIngredient']}\nInstructions: {row['recipeInstructions']}"
27
+ documents.append(Document(page_content=document_text)) # Document 객체로 변환
28
+
29
+ return documents
30
+
31
+ def create_vectorstore():
32
+ csv_file = '/home/sohee/pj/united/recipes.csv' # CSV 파일 경로
33
+
34
+ # 벡터 저장소 캐시를 먼저 확인하고 로드
35
+ if os.path.exists(VECTOR_STORE_PATH):
36
+ print("Vector store already exists. Loading it from disk...")
37
+ return FAISS.load_local(VECTOR_STORE_PATH, EMBEDDINGS, allow_dangerous_deserialization=True)
38
+
39
+ print("Creating new vector store...")
40
+ text_splitter = CharacterTextSplitter(
41
+ separator="\n",
42
+ chunk_size=1000,
43
+ chunk_overlap=200,
44
+ length_function=len,
45
+ is_separator_regex=False,
46
+ )
47
+
48
+ # CSV 파일에서 문서 로드
49
+ documents = load_csv_to_documents(csv_file)
50
+
51
+ # 문서를 청크로 분할
52
+ chunked_documents = text_splitter.split_documents(documents)
53
+
54
+ # 벡터 저장소 생성 (GPU 가속화 사용)
55
+ index = faiss.IndexFlatL2(EMBEDDINGS.embed_dimension)
56
+ if torch.cuda.is_available():
57
+ print("Using GPU for FAISS...")
58
+ res = faiss.StandardGpuResources()
59
+ index = faiss.index_cpu_to_gpu(res, 0, index)
60
+
61
+ vectorstore = FAISS.from_documents(chunked_documents, EMBEDDINGS, index=index)
62
+ vectorstore.save_local(VECTOR_STORE_PATH)
63
+
64
+ return vectorstore
65
+
66
+ # 프롬프트 템플릿 정의
67
+ prompt = PromptTemplate(
68
+ input_variables=["context", "question"],
69
+ template="Context: {context}\nQuestion: {question}\nAnswer:"
70
+ )
71
+
72
+ # LLM 모델 및 토크나이저 로컬 저장
73
+ def save_model_locally():
74
+ model_name = "intfloat/multilingual-e5-small" # 모델 이름
75
+ save_directory = "/home/sohee/pj/local_model" # 저장할 경로
76
+
77
+ # 모델과 토크나이저 로드
78
+ model = AutoModel.from_pretrained(model_name)
79
+ tokenizer = AutoTokenizer.from_pretrained(model_name)
80
+
81
+ # 모델 및 토크나이저를 로컬에 저장
82
+ model.save_pretrained(save_directory)
83
+ tokenizer.save_pretrained(save_directory)
84
+ print(f"Model and tokenizer saved locally at {save_directory}")
85
+
86
+ # GPU 지원 LLM 모델 초기화
87
+ llm = ChatOllama(model="llama3.1:8b", device=device)
88
+
89
+ # 메타 텐서 문제 처리
90
+ def initialize_meta_tensor_model():
91
+ print("Handling meta tensor...")
92
+ model = AutoModel.from_pretrained("intfloat/multilingual-e5-small")
93
+ model = model.to_empty(device=device) # Meta 텐서를 처리하기 위한 to_empty 사용
94
+ return model
95
+
96
+ # Format the retrieved documents to filter out the recipes containing the ingredient
97
+ def format_docs(docs, query):
98
+ results = []
99
+ unique_recipes = set()
100
+
101
+ for doc in docs:
102
+ content = doc.page_content
103
+
104
+ # Extract name, ingredients, and instructions
105
+ name_line = content.split("\n")[0].split(": ")[1].strip() if "Name:" in content else ""
106
+ ingredients_line = content.split("\n")[1].split(": ")[1].strip() if "Ingredients:" in content else ""
107
+ instructions_line = content.split("\nInstructions: ")[-1].strip() if "Instructions:" in content else ""
108
+
109
+ # 검색어가 요리 이름(name) 또는 재료(ingredients)에 포함되는지 확인
110
+ if (query.lower() in name_line.lower() or any(q.lower() in ingredients_line.lower() for q in query.split(","))) and name_line not in unique_recipes:
111
+ unique_recipes.add(name_line)
112
+
113
+ # 만드는 방법을 목록으로 변경
114
+ formatted_instructions = '\n'.join([f"- {step.strip()}" for step in instructions_line.split('.') if step])
115
+
116
+ results.append({
117
+ "name": name_line,
118
+ "ingredients": ingredients_line,
119
+ "instructions": formatted_instructions # 목록 형식으로 변경된 instructions
120
+ })
121
+
122
+ # 최대 5개까지만 결과를 포함하도록 제한
123
+ if len(results) >= 5:
124
+ break
125
+
126
+ return results
127
+
128
+ def ask_query(query):
129
+ # 벡터 저장소 생성 또는 로드
130
+ vectorstore = create_vectorstore()
131
+ retriever = vectorstore.as_retriever(search_kwargs={"k": 150000}) # 검색 결과 수를 15개로 늘림
132
+
133
+ # Use `invoke` method instead of the deprecated one
134
+ docs = retriever.invoke(query)
135
+
136
+ # Format the documents based on the query (ingredient or name)
137
+ formatted_results = format_docs(docs, query)
138
+
139
+ # 결과 출력
140
+ if not formatted_results:
141
+ print(f"'{query}'에 해당하는 요리 레시피를 찾을 수 없습니다.")
142
+ else:
143
+ print(f"'{query}'이(가) 포함된 모든 음식명 리스트:")
144
+ for i, result in enumerate(formatted_results, 1):
145
+ print(f"[{i}번째 레시피]\n (1) 음식 이름: {result['name']}")
146
+ print(f" (2) 재료: {result['ingredients']}")
147
+ print(f" (3) 만드는 방법: \n{result['instructions']}")
148
+ print("--" * 100)
149
+ print()
150
+
151
+ if __name__ == "__main__":
152
+ while True:
153
+ user_query = input("질문을 입력하세요 (예:다이어트(다이어트식) 또는 된장찌개 또는 재료명(돼지고기, 오이 등) 입력. 종료를 원할 시 'exit' 입력): ") # 사용자에게 질문 입력 받기
154
+
155
+ if user_query.lower() == 'exit': # 사용자가 'exit'을 입력하면 프로그램 종료
156
+ print("프로그램을 종료합니다.")
157
+ save_model_locally() # 프로그램 종료 시 모델 저장
158
+ break
159
+
160
+ ask_query(user_query) # 입력된 질문 처리 및 응답 출력
161
+
local_model/config.json ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_name_or_path": "intfloat/multilingual-e5-small",
3
+ "architectures": [
4
+ "BertModel"
5
+ ],
6
+ "attention_probs_dropout_prob": 0.1,
7
+ "classifier_dropout": null,
8
+ "hidden_act": "gelu",
9
+ "hidden_dropout_prob": 0.1,
10
+ "hidden_size": 384,
11
+ "initializer_range": 0.02,
12
+ "intermediate_size": 1536,
13
+ "layer_norm_eps": 1e-12,
14
+ "max_position_embeddings": 512,
15
+ "model_type": "bert",
16
+ "num_attention_heads": 12,
17
+ "num_hidden_layers": 12,
18
+ "pad_token_id": 0,
19
+ "position_embedding_type": "absolute",
20
+ "tokenizer_class": "XLMRobertaTokenizer",
21
+ "torch_dtype": "float32",
22
+ "transformers_version": "4.43.3",
23
+ "type_vocab_size": 2,
24
+ "use_cache": true,
25
+ "vocab_size": 250037
26
+ }
local_model/model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:7a77d5da5ee721c7c740e4082447d3026b6521d3eac5edb93edb6aa88f03b7d7
3
+ size 470637416
local_model/sentencepiece.bpe.model ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:cfc8146abe2a0488e9e2a0c56de7952f7c11ab059eca145a0a727afce0db2865
3
+ size 5069051
local_model/special_tokens_map.json ADDED
@@ -0,0 +1,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "bos_token": {
3
+ "content": "<s>",
4
+ "lstrip": false,
5
+ "normalized": false,
6
+ "rstrip": false,
7
+ "single_word": false
8
+ },
9
+ "cls_token": {
10
+ "content": "<s>",
11
+ "lstrip": false,
12
+ "normalized": false,
13
+ "rstrip": false,
14
+ "single_word": false
15
+ },
16
+ "eos_token": {
17
+ "content": "</s>",
18
+ "lstrip": false,
19
+ "normalized": false,
20
+ "rstrip": false,
21
+ "single_word": false
22
+ },
23
+ "mask_token": {
24
+ "content": "<mask>",
25
+ "lstrip": false,
26
+ "normalized": false,
27
+ "rstrip": false,
28
+ "single_word": false
29
+ },
30
+ "pad_token": {
31
+ "content": "<pad>",
32
+ "lstrip": false,
33
+ "normalized": false,
34
+ "rstrip": false,
35
+ "single_word": false
36
+ },
37
+ "sep_token": {
38
+ "content": "</s>",
39
+ "lstrip": false,
40
+ "normalized": false,
41
+ "rstrip": false,
42
+ "single_word": false
43
+ },
44
+ "unk_token": {
45
+ "content": "<unk>",
46
+ "lstrip": false,
47
+ "normalized": false,
48
+ "rstrip": false,
49
+ "single_word": false
50
+ }
51
+ }
local_model/tokenizer.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:cd98e5698b201ba914efb8c18b6709fa8735ab71dcad8d2b431e52e8bf68d932
3
+ size 17082800
local_model/tokenizer_config.json ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "added_tokens_decoder": {
3
+ "0": {
4
+ "content": "<s>",
5
+ "lstrip": false,
6
+ "normalized": false,
7
+ "rstrip": false,
8
+ "single_word": false,
9
+ "special": true
10
+ },
11
+ "1": {
12
+ "content": "<pad>",
13
+ "lstrip": false,
14
+ "normalized": false,
15
+ "rstrip": false,
16
+ "single_word": false,
17
+ "special": true
18
+ },
19
+ "2": {
20
+ "content": "</s>",
21
+ "lstrip": false,
22
+ "normalized": false,
23
+ "rstrip": false,
24
+ "single_word": false,
25
+ "special": true
26
+ },
27
+ "3": {
28
+ "content": "<unk>",
29
+ "lstrip": false,
30
+ "normalized": false,
31
+ "rstrip": false,
32
+ "single_word": false,
33
+ "special": true
34
+ },
35
+ "250001": {
36
+ "content": "<mask>",
37
+ "lstrip": false,
38
+ "normalized": false,
39
+ "rstrip": false,
40
+ "single_word": false,
41
+ "special": true
42
+ }
43
+ },
44
+ "bos_token": "<s>",
45
+ "clean_up_tokenization_spaces": true,
46
+ "cls_token": "<s>",
47
+ "eos_token": "</s>",
48
+ "mask_token": "<mask>",
49
+ "model_max_length": 512,
50
+ "pad_token": "<pad>",
51
+ "sep_token": "</s>",
52
+ "sp_model_kwargs": {},
53
+ "tokenizer_class": "XLMRobertaTokenizer",
54
+ "unk_token": "<unk>"
55
+ }
recipes.csv ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d3f0ca7dc1c49c0b9969c85bb2c1debb77dfe18c9a3ba490bce07c80828c8d25
3
+ size 139790399