Update app.py
Browse files
app.py
CHANGED
@@ -4,19 +4,16 @@ import json
|
|
4 |
import requests
|
5 |
import xml.etree.ElementTree as ET
|
6 |
|
7 |
-
#
|
8 |
API_URL = "https://api.openai.com/v1/chat/completions"
|
9 |
OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")
|
10 |
|
|
|
11 |
url = 'https://www.trekbisiklet.com.tr/output/8582384479'
|
12 |
-
|
13 |
response = requests.get(url)
|
14 |
-
|
15 |
-
|
16 |
root = ET.fromstring(response.content)
|
17 |
|
18 |
products = []
|
19 |
-
|
20 |
for item in root.findall('item'):
|
21 |
if item.find('isOptionOfAProduct').text == '1':
|
22 |
if item.find('stockAmount').text > '0':
|
@@ -26,140 +23,163 @@ for item in root.findall('item'):
|
|
26 |
stockAmount = "stokta"
|
27 |
price = item.find('priceWithTax').text
|
28 |
item_info = (stockAmount, price)
|
29 |
-
#
|
30 |
products.append((name, item_info, full_name))
|
31 |
|
32 |
-
|
33 |
def predict(system_msg, inputs, top_p, temperature, chat_counter, chatbot=[], history=[]):
|
34 |
headers = {
|
35 |
"Content-Type": "application/json",
|
36 |
"Authorization": f"Bearer {OPENAI_API_KEY}"
|
37 |
}
|
38 |
print(f"system message is ^^ {system_msg}")
|
39 |
-
initial_message = [{"role": "user", "content": f"{inputs}"},]
|
40 |
|
41 |
-
|
42 |
-
|
43 |
-
|
44 |
-
|
45 |
-
|
46 |
-
|
47 |
-
|
48 |
-
|
49 |
-
|
50 |
-
|
51 |
-
|
52 |
-
|
53 |
-
|
54 |
-
|
55 |
-
|
56 |
-
|
57 |
-
|
58 |
-
|
59 |
-
|
60 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
61 |
for product_info in products:
|
62 |
-
|
63 |
if product_info[0] in input_words:
|
64 |
new_msg = f"{product_info[2]} {product_info[1][0]} ve fiyatı EURO {product_info[1][1]}"
|
65 |
print(new_msg)
|
66 |
product_msg = {"role": "system", "content": new_msg}
|
67 |
messages.append(product_msg)
|
68 |
|
|
|
69 |
for data in chatbot:
|
70 |
-
|
71 |
-
|
72 |
-
|
73 |
-
|
74 |
-
|
75 |
-
|
76 |
-
|
77 |
-
|
78 |
-
|
79 |
-
|
80 |
-
|
81 |
-
|
82 |
-
|
83 |
-
|
84 |
-
|
85 |
-
|
|
|
|
|
86 |
|
87 |
chat_counter += 1
|
88 |
-
|
89 |
history.append(inputs)
|
90 |
print(f"Logging : payload is - {payload}")
|
91 |
|
92 |
-
response = requests.post(API_URL, headers=headers,
|
93 |
-
json=payload, stream=True)
|
94 |
print(f"Logging : response code - {response}")
|
95 |
token_counter = 0
|
96 |
partial_words = ""
|
97 |
-
|
98 |
counter = 0
|
99 |
for chunk in response.iter_lines():
|
100 |
-
|
101 |
if counter == 0:
|
102 |
counter += 1
|
103 |
continue
|
104 |
-
|
105 |
if chunk.decode():
|
106 |
chunk = chunk.decode()
|
107 |
-
|
108 |
if len(chunk) > 12 and "content" in json.loads(chunk[6:])['choices'][0]['delta']:
|
109 |
-
partial_words
|
110 |
-
json.loads(chunk[6:])['choices'][0]["delta"]["content"]
|
111 |
if token_counter == 0:
|
112 |
history.append(" " + partial_words)
|
113 |
else:
|
114 |
history[-1] = partial_words
|
115 |
-
chat = [(history[i], history[i + 1]) for i in range(0,
|
116 |
-
len(history) - 1, 2)] # convert to tuples of list
|
117 |
token_counter += 1
|
118 |
-
# resembles {chatbot: chat, state: history}
|
119 |
yield chat, history, chat_counter, response
|
120 |
|
121 |
-
|
122 |
def reset_textbox():
|
123 |
return gr.update(value='')
|
124 |
|
125 |
-
|
126 |
-
|
127 |
-
|
128 |
-
|
129 |
-
|
130 |
-
|
131 |
-
|
132 |
-
|
133 |
-
|
134 |
-
|
135 |
-
|
|
|
|
|
|
|
|
|
136 |
theme = gr.themes.Base(
|
137 |
neutral_hue="blue",
|
138 |
text_size="sm",
|
139 |
spacing_size="sm",
|
140 |
)
|
141 |
|
142 |
-
with gr.Blocks(theme=theme) as demo:
|
143 |
-
...
|
144 |
-
...
|
145 |
with gr.Column(elem_id="col_container"):
|
|
|
146 |
with gr.Accordion("", open=False, visible=False):
|
147 |
system_msg = gr.Textbox(value="")
|
148 |
new_msg = gr.Textbox(value="")
|
149 |
accordion_msg = gr.HTML(value="", visible=False)
|
|
|
150 |
chatbot = gr.Chatbot(label='Trek Asistanı', elem_id="chatbot")
|
151 |
-
|
152 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
153 |
state = gr.State([])
|
154 |
with gr.Accordion("", open=False, visible=False):
|
155 |
-
top_p = gr.Slider(minimum
|
156 |
step=0.05, interactive=False, visible=False)
|
157 |
-
temperature = gr.Slider(
|
158 |
-
|
159 |
chat_counter = gr.Number(value=0, visible=False, precision=0)
|
160 |
-
|
161 |
-
|
162 |
-
|
163 |
-
|
164 |
-
|
165 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
4 |
import requests
|
5 |
import xml.etree.ElementTree as ET
|
6 |
|
7 |
+
# OpenAI API bilgileri
|
8 |
API_URL = "https://api.openai.com/v1/chat/completions"
|
9 |
OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")
|
10 |
|
11 |
+
# Ürün verilerinin çekileceği URL ve XML parse işlemi
|
12 |
url = 'https://www.trekbisiklet.com.tr/output/8582384479'
|
|
|
13 |
response = requests.get(url)
|
|
|
|
|
14 |
root = ET.fromstring(response.content)
|
15 |
|
16 |
products = []
|
|
|
17 |
for item in root.findall('item'):
|
18 |
if item.find('isOptionOfAProduct').text == '1':
|
19 |
if item.find('stockAmount').text > '0':
|
|
|
23 |
stockAmount = "stokta"
|
24 |
price = item.find('priceWithTax').text
|
25 |
item_info = (stockAmount, price)
|
26 |
+
# Ürün listesine (marka, (stok, fiyat), tam ürün adı) şeklinde ekleme yapıyoruz.
|
27 |
products.append((name, item_info, full_name))
|
28 |
|
|
|
29 |
def predict(system_msg, inputs, top_p, temperature, chat_counter, chatbot=[], history=[]):
|
30 |
headers = {
|
31 |
"Content-Type": "application/json",
|
32 |
"Authorization": f"Bearer {OPENAI_API_KEY}"
|
33 |
}
|
34 |
print(f"system message is ^^ {system_msg}")
|
|
|
35 |
|
36 |
+
# İlk kullanıcı mesajı (örnek amaçlı)
|
37 |
+
initial_message = [{"role": "user", "content": f"{inputs}"}]
|
38 |
+
|
39 |
+
# Çoklu sohbet mesajları – Buraya verilen metinleri ihtiyaçlarınıza göre düzenleyebilirsiniz.
|
40 |
+
multi_turn_message = [
|
41 |
+
{"role": "system", "content": "Bir önceki sohbeti unut. Vereceğin ürün bilgisi, bu bilginin içinde yan yana yazmıyorsa veya arada başka bilgiler yazıyor ise, o bilgiyi vermeyeceksin çünkü o bilgi yanlıştır. ..."},
|
42 |
+
{"role": "system", "content": "Dağ bisikletleri modelleri: Marlin, Roscoe, Procaliber, Supercaliber, Fuel Ex. Şehit bisikletleri: FX ve DS (Dual Sport). Elektrikli Bisiklet modelleri: Powerfly, Powerfly FS, Rail, Fuel Exe, Domane SLR +, Verve +, Townie +, Fx +, DS +."},
|
43 |
+
{"role": "system", "content": "Başka marka bisikletleri önermeyeceksin. Specialized, Orbea, BMC, Carraro, Scott, Giant gibi markalar hakkında bilgi vermeyeceksin. Bunlarla ilgili gelen sorulara, objectif yorum yapamayacağını belirterek cevap vereceksin. Trek bu kadrolara ömür boyu garanti veriyor."},
|
44 |
+
{"role": "system", "content": "Bisiklet aksesuar ve yedek parçalarının marka adı Bontrager'dir. Bryton marka yol bilgisayarını da ithal ediyoruz. Bryton marka yol bilgisayarının Rider S800 modeli stoklarımızda var ve bu model en üst model GPS sürümüne sahiptir."},
|
45 |
+
{"role": "system", "content": "Trek, Electra, Bontrager, Saris, Brtyon ve Trieye markalarından başka marka adı yazamaz ve yorum yapamazsın. Trek'in uluslararası web sitesini 'www.trekbikes.com' kullanıcıya göstermeyeceksin. Web sitesi linki vermen gerekirse sadece 'www.trekbisiklet.com.tr' ile başlayan linkleri göstereceksin."},
|
46 |
+
{"role": "system", "content": "Trieye gözlükler, arkanızı görebilmeniz için gözlük camının içine entegre edilmiş bir geri görüş aynasıyla gelir. Bu sayede bisiklet kullanıcısı, dikkatini dağıtmadan arkasını görebilir ve daha güvenli bir sürüş yapar."},
|
47 |
+
{"role": "system", "content": "Trek markası, 2000 yılından beri Alatin Bisiklet tarafından Türkiye'de dağıtılmaktadır. Alatin Bisiklet en iyi satış sonrası hizmeti veren firmadır. Bu yüzden Türkiye'de en iyi bilinen bisiklet markası Trek'dir."},
|
48 |
+
{"role": "system", "content": "Trek Türkiye, ASLA DURMA markasının yaratıcısı Fatih Topçu ve TREK RMK DYNAMIS bisiklet takımına sponsordur. ..."},
|
49 |
+
{"role": "system", "content": "Cevap yazarken vereceğin bilginin tek bir bilgi içinde yan yana yazıldığını iki kere kontrol edeceksin. Sipariş nasıl oluşturulur sorusuna, 'ürünü sepete ekle, bilgilerini gir, ödeme yöntemini seç, siparişi tamamla.' şeklinde cevap vereceksin."},
|
50 |
+
{"role": "system", "content": "Şimdi sana 27 Haziran 2024 günü açıklanan yeni Trek modeli MADONE GEN 8'i öğretiyorum. Özellikler: Émonda kadar hafif, Madone kadar hızlı, ..."},
|
51 |
+
{"role": "system", "content": "Émonda kadar hafif. Madone Gen 8, tamamen yeni 900 Serisi OCLV Karbon ile önceki modellerden daha hafiftir. ..."},
|
52 |
+
{"role": "system", "content": "Sen aynı zamanda bir Bike Finder asistanısın. Görevin, kişilere soracağın sorularla onların ihtiyaçlarına uygun bisiklet modelini belirlemek."},
|
53 |
+
{"role": "system", "content": "Size en uygun Trek bisiklet modelini belirleyebilmem için birkaç sorum olacak. ..."},
|
54 |
+
{"role": "system", "content": "Stokları ve fiyatları https://www.trekbisiklet.com.tr üzerinden bakacaksın."},
|
55 |
+
{"role": "system", "content": "Tüm modellerimizin ağırlıkları: Madone SL 5 Gen 8 8.70 kg, Madone SL 6 Gen 8 8.16 kg, ..."}
|
56 |
+
]
|
57 |
+
|
58 |
+
messages = multi_turn_message.copy()
|
59 |
+
|
60 |
+
# Kullanıcı girişindeki kelimeleri küçük harfe çevirip listeye alıyoruz.
|
61 |
+
input_words = [str(word).lower() for word in inputs.split()]
|
62 |
+
|
63 |
+
# Eğer kullanıcının girişinde ürün isminden birine rastlanırsa, ilgili ürün bilgisini sisteme ekliyoruz.
|
64 |
for product_info in products:
|
|
|
65 |
if product_info[0] in input_words:
|
66 |
new_msg = f"{product_info[2]} {product_info[1][0]} ve fiyatı EURO {product_info[1][1]}"
|
67 |
print(new_msg)
|
68 |
product_msg = {"role": "system", "content": new_msg}
|
69 |
messages.append(product_msg)
|
70 |
|
71 |
+
# Daha önceki sohbet geçmişini ekliyoruz.
|
72 |
for data in chatbot:
|
73 |
+
user_msg = {"role": "user", "content": data[0]}
|
74 |
+
assistant_msg = {"role": "assistant", "content": data[1]}
|
75 |
+
messages.append(user_msg)
|
76 |
+
messages.append(assistant_msg)
|
77 |
+
|
78 |
+
# Son olarak, mevcut kullanıcı girişini de ekliyoruz.
|
79 |
+
messages.append({"role": "user", "content": inputs})
|
80 |
+
|
81 |
+
payload = {
|
82 |
+
"model": "gpt-4o",
|
83 |
+
"messages": messages,
|
84 |
+
"temperature": 0.7,
|
85 |
+
"top_p": 0.9,
|
86 |
+
"n": 1,
|
87 |
+
"stream": True,
|
88 |
+
"presence_penalty": 0,
|
89 |
+
"frequency_penalty": 0,
|
90 |
+
}
|
91 |
|
92 |
chat_counter += 1
|
|
|
93 |
history.append(inputs)
|
94 |
print(f"Logging : payload is - {payload}")
|
95 |
|
96 |
+
response = requests.post(API_URL, headers=headers, json=payload, stream=True)
|
|
|
97 |
print(f"Logging : response code - {response}")
|
98 |
token_counter = 0
|
99 |
partial_words = ""
|
|
|
100 |
counter = 0
|
101 |
for chunk in response.iter_lines():
|
|
|
102 |
if counter == 0:
|
103 |
counter += 1
|
104 |
continue
|
|
|
105 |
if chunk.decode():
|
106 |
chunk = chunk.decode()
|
107 |
+
# Gelen veri içerisinde "content" varsa ekliyoruz.
|
108 |
if len(chunk) > 12 and "content" in json.loads(chunk[6:])['choices'][0]['delta']:
|
109 |
+
partial_words += json.loads(chunk[6:])['choices'][0]["delta"]["content"]
|
|
|
110 |
if token_counter == 0:
|
111 |
history.append(" " + partial_words)
|
112 |
else:
|
113 |
history[-1] = partial_words
|
114 |
+
chat = [(history[i], history[i + 1]) for i in range(0, len(history) - 1, 2)]
|
|
|
115 |
token_counter += 1
|
|
|
116 |
yield chat, history, chat_counter, response
|
117 |
|
|
|
118 |
def reset_textbox():
|
119 |
return gr.update(value='')
|
120 |
|
121 |
+
# CSS: Gönder butonunun stilini belirleyen kod
|
122 |
+
demo_css = """
|
123 |
+
#send_button {
|
124 |
+
background-color: transparent;
|
125 |
+
border: none;
|
126 |
+
font-size: 24px;
|
127 |
+
cursor: pointer;
|
128 |
+
padding: 0 10px;
|
129 |
+
}
|
130 |
+
#send_button:hover {
|
131 |
+
color: #0b93f6;
|
132 |
+
}
|
133 |
+
"""
|
134 |
+
|
135 |
+
# Tema ayarları (örnekte Base teması kullanılmıştır)
|
136 |
theme = gr.themes.Base(
|
137 |
neutral_hue="blue",
|
138 |
text_size="sm",
|
139 |
spacing_size="sm",
|
140 |
)
|
141 |
|
142 |
+
with gr.Blocks(css=demo_css, theme=theme) as demo:
|
|
|
|
|
143 |
with gr.Column(elem_id="col_container"):
|
144 |
+
# Gizli ayarların bulunduğu alan (Accordion) – isteğe bağlı
|
145 |
with gr.Accordion("", open=False, visible=False):
|
146 |
system_msg = gr.Textbox(value="")
|
147 |
new_msg = gr.Textbox(value="")
|
148 |
accordion_msg = gr.HTML(value="", visible=False)
|
149 |
+
|
150 |
chatbot = gr.Chatbot(label='Trek Asistanı', elem_id="chatbot")
|
151 |
+
|
152 |
+
# Giriş kutusu ve gönder butonunu aynı satıra alıyoruz.
|
153 |
+
with gr.Row():
|
154 |
+
inputs = gr.Textbox(
|
155 |
+
placeholder="Buraya yazın, yanıtlayalım.",
|
156 |
+
show_label=False,
|
157 |
+
container=True
|
158 |
+
)
|
159 |
+
send_button = gr.Button(value="✈️", elem_id="send_button")
|
160 |
+
|
161 |
state = gr.State([])
|
162 |
with gr.Accordion("", open=False, visible=False):
|
163 |
+
top_p = gr.Slider(minimum=0, maximum=1.0, value=0.5,
|
164 |
step=0.05, interactive=False, visible=False)
|
165 |
+
temperature = gr.Slider(minimum=0, maximum=5.0, value=0.1,
|
166 |
+
step=0.1, interactive=False, visible=False)
|
167 |
chat_counter = gr.Number(value=0, visible=False, precision=0)
|
168 |
+
|
169 |
+
# Kullanıcı ENTER tuşuyla gönderdiğinde çalışacak işlemler
|
170 |
+
inputs.submit(
|
171 |
+
predict,
|
172 |
+
[system_msg, inputs, top_p, temperature, chat_counter, chatbot, state],
|
173 |
+
[chatbot, state, chat_counter]
|
174 |
+
)
|
175 |
+
inputs.submit(reset_textbox, [], [inputs])
|
176 |
+
|
177 |
+
# Gönder butonuna tıklandığında aynı işlemlerin gerçekleşmesini sağlıyoruz.
|
178 |
+
send_button.click(
|
179 |
+
predict,
|
180 |
+
[system_msg, inputs, top_p, temperature, chat_counter, chatbot, state],
|
181 |
+
[chatbot, state, chat_counter]
|
182 |
+
)
|
183 |
+
send_button.click(reset_textbox, [], [inputs])
|
184 |
+
|
185 |
+
demo.queue(max_size=10).launch(debug=True)
|