카테고리 없음
스파르타 AI-8기 TIL(1/4)-TeamProject
kimjunki-8
2025. 1. 4. 21:47
from KJK_data_collect import final_answer, language, selected_input
import os
import openai
from openai import OpenAI
openai.api_key = os.getenv("OPENAI_API_KEY2")
from PyPDF2 import PdfReader
import re
pdf_path = 'C:\\Users\\kevinkim\\Desktop\\Daily Calories\\Daily recommended Calories.pdf' #추후 변경 가능
pdf_file = PdfReader(pdf_path)
nutrition_file = ''
for file in pdf_file.pages:
nutrition_file += file.extract_text()
def filtered_file(text):
text = re.sub(r"\b(오전|오후)\s*\d{1,2}:\d{2}\b", "", text)
text = re.sub(r"https?://\S+", "", text)
text = re.sub(r"\s+", " ", text).strip()
return text
nutrition_file = filtered_file(nutrition_file)
chosen_language = ''
choose_language = input('한국어로 하시겠습니까? y/n:')
if choose_language == 'y':
chosen_language += 'Korean'
else:
chosen_language == ''
recommendation_history = []
while True:
if chosen_language == 'Korean':
time_check = input(f'''안녕하세요! 저는 당신의 식단을 책임질 SpartaChef입니다!
이미 {selected_input}을 드셨군요! 혹시 언제 드셨는지 알 수 있을까요?
예: 아침 6시, 오후 2시 등: ''')
else:
time_check = (f'''Hello! I am SpartaChef, your diet assistant!
You have already eaten {selected_input}. Can you tell me when you had it?
Example: 6 AM, 2 PM, etc.: ''')
client = OpenAI()
completion = client.chat.completions.create(
model = 'gpt-4o',
messages = [
{'role':'system', 'content': """
You are a helpful assistant named SpartaChef who helps people with their menu({selected_input})
Start by trying to figure out the time the user ate that food (you can round the minutes: for example, 6:48 am = 7 am).
The time: {time_check}
Example:
morning (Typically from 6:00 AM to 12:00 PM).
afternoon (From 12:00 PM to around 6:00 PM).
evening (From 6:00 PM to 9:00 PM).
If the user mentions the time, answer in the following format:
morning: 8 am
afternoon: 3 pm
evening: 8 pm
If the user is not typing a valid time or anything unrelated, respond with "none" and never say something else but none.
Do not say anything else when you say "none".
Always follow the language set in the prompt (e.g., if the language is Korean, respond in Korean).
"""},
{'role':'user', 'content' : language},
{'role':'user', 'content' : selected_input},
{'role':'user', 'content' : time_check},
])
time_menu = completion.choices[0].message.content
if time_menu == 'none':
print('잘모르겠어요....다시 말씀해 주실 수 있나요?')
continue
client1 = OpenAI()
completion = client1.chat.completions.create(
model='gpt-4o',
messages=[
{'role': 'system', 'content': """
You are a professional Personalized Nutrition Specialist and Nutrition Data Analyst. Follow these instructions carefully:
1. **Analyze the Nutrients:**
- Analyze the nutrients and calorie content of the food and its ingredients based on {final_answer}.
- Predict the calories and nutrients (e.g., proteins, carbs, fats, vitamins, etc.) of the given recipe.
- Identify any nutritional deficiencies or excesses using {nutrition_file}, considering the time of day ({food_time}).
- Always respond in the language specified by {language}.
2. **Recommend Food:**
- Based on the user's meal time ({time_menu}), recommend appropriate food or menu options for the upcoming meals (until the next day).
- Recommendations should align with the calculated calorie and nutrient needs.
- Consider the user's cultural and language preferences based on {language}.
- **Morning:** If the user ate in the morning, recommend menus for lunch and dinner.
- **Lunch:** If the user ate at lunch, recommend a menu for dinner.
- **Dinner:** If the user ate at dinner, recommend a menu for the next day's breakfast.
"""
},
{'role': 'user', 'content': final_answer},
{'role': 'user', 'content': language},
{'role': 'user', 'content': time_menu},
])
recommendation = completion.choices[0].message.content
print(recommendation)
while True:
continue_question = input('혹시 질문이나 궁금하신 점 있을까요? ')
client4 = OpenAI()
completion = client4.chat.completions.create(
model='gpt-4o',
messages=[
{'role': 'system', 'content': """
You are a master chef and a helpful health trainer. You will receive multiple questions based on {recommendation} but don't make any duplicated answers.
1. **Answer the Question**
- Provide a thorough and informative response to each question.
2. **Handle Exit Requests**
- If the user's message indicates a desire to leave or end the chat, respond with only the word "quit". Do not add any additional text or commentary.
example:
question no.1 = '아니야 없어', answer = 'quit'
question no.2 = '필요없을 거 같아, answer = 'quit'
question no.3 = '괜찮아', answer = 'quit'
question no.4 = '고마워', answer = 'quit'
question no.5 = '이제 괜찮아, answer = 'quit'
question no.6 = '없어', answer = 'quit'
3. **Detailed Instructions**
- If the user asks how to make specific ***ingredients***, provide a detailed, step-by-step explanation on how to prepare them.
4. **chat history**
- If user is asking a question regarding previous chat, try to find it in {chat_history}
**Notes:**
- Ensure all responses are clear, concise, and relevant to the user's queries.
- Maintain a professional and friendly tone throughout the conversation.
"""},
{'role': 'user', 'content': final_answer},
{'role': 'user', 'content': continue_question},
])
menu_questions = completion.choices[0].message.content
if menu_questions == 'quit':
print(menu_questions)
break
else:
print(menu_questions)
recommendation_history.append(recommendation)
recommendation_history.append(menu_questions)
오늘 만든 코드
하지만 사실 Chroma를 구축하면 전부 바꿔야 한다. 일단 기초적인 코드만 작성.
먼저 칼로리, 및 영양성분이 들어있는 pdf 파일을 넣어서, 확인하니, 링크 및 날짜가 적혀 있는것을 발견
pdf_path = 'C:\\Users\\kevinkim\\Desktop\\Daily Calories\\Daily recommended Calories.pdf' #추후 변경 가능
pdf_file = PdfReader(pdf_path)
nutrition_file = ''
for file in pdf_file.pages:
nutrition_file += file.extract_text()
def filtered_file(text):
text = re.sub(r"\b(오전|오후)\s*\d{1,2}:\d{2}\b", "", text)
text = re.sub(r"https?://\S+", "", text)
text = re.sub(r"\s+", " ", text).strip()
return text
이 부분에서 전처리를 실행합니다
1. 패턴: r"\b(오전|오후)\s*\d{1,2}:\d{2}\b"
이 패턴은 "오전" 또는 "오후"로 시작하고, 뒤에 공백(있어도 되고 없어도 됨)과 시간(예: 3:45)이 따라오는 형식을 탐지하여 제거합니다.
세부 설명:
r: 문자열이 "raw string"임을 나타냅니다. 백슬래시(\)를 정규식에서 그대로 해석하도록 해줍니다.
\b: 단어 경계를 나타냅니다. "오전"이나 "오후"가 단어의 시작 또는 끝에 있어야 함을 뜻합니다.
(오전|오후): 소괄호는 그룹을 의미하며, |는 "OR"을 뜻합니다. 즉, "오전" 또는 "오후"를 매칭합니다.
\s*: 공백 문자(\s)가 0개 이상(*) 나올 수 있음을 의미합니다.
\d{1,2}: 숫자(\d)가 1개에서 2개까지 나올 수 있음을 의미합니다. 예: "3" 또는 "12".
:: 콜론(:) 문자를 의미합니다.
\d{2}: 숫자 2개를 매칭합니다. 예: "45".
\b: 단어의 경계를 나타냅니다. 시간 형식이 단어 끝이어야 함을 의미합니다.
매칭 예:
"오전 3:45" → 매칭됨
"오후12:30" → 매칭됨
"12:45" → 매칭되지 않음 (오전/오후 없음)
2. 패턴: r"https?://\S+"
이 패턴은 http:// 또는 https://로 시작하는 URL을 탐지하여 제거합니다.
세부 설명:
https?: "http" 다음에 "s"가 있을 수도 있고 없을 수도 있음을 의미합니다(?는 0개 또는 1개를 의미).
://: "://" 문자열 그대로를 매칭합니다.
\S+: 공백이 아닌 문자(\S)가 1개 이상(+) 나오는 부분을 매칭합니다. URL의 나머지 부분을 잡아냅니다.
매칭 예:
"http://example.com" → 매칭됨
"https://example.com/test" → 매칭됨
"ftp://example.com" → 매칭되지 않음
3. 패턴: r"\s+"
이 패턴은 연속된 공백 문자를 탐지하여 한 개의 공백으로 대체합니다.
세부 설명:
\s: 공백 문자를 의미합니다. 여기에는 스페이스, 탭, 줄바꿈 등이 포함됩니다.
+: 하나 이상의 공백이 연속될 경우 모두 매칭됩니다.
매칭 예:
"Hello World" → "Hello World"
"Line\nBreak" → "Line Break"
대충 이런식이며, 그렇게 전처리된 텍스트들은 전부 이제 AI가 필터링해서 칼로리 계산 및 추후 음식을 추천해주는 방식입니다.