File size: 4,411 Bytes
f3ff1c7 2142c80 f3ff1c7 2142c80 c211cfa c5ccc94 2142c80 f3ff1c7 c5ccc94 2142c80 c5ccc94 2142c80 f3ff1c7 2142c80 f3ff1c7 b07a923 c5ccc94 b07a923 c5ccc94 e781c31 9721f1e c5ccc94 60d0118 c5ccc94 2142c80 c5ccc94 f3ff1c7 2142c80 f3ff1c7 2142c80 c5ccc94 2142c80 c5ccc94 2142c80 c5ccc94 2142c80 f3ff1c7 2142c80 c5ccc94 9819a75 c5ccc94 2142c80 c5ccc94 01cefec 365f6e4 c5ccc94 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 |
import gradio as gr
import os
import json
import requests
import xml.etree.ElementTree as ET
# OpenAI API URL and Key
API_URL = "https://api.openai.com/v1/chat/completions"
OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")
# Function to get product data from XML URL
def get_product_data(url):
response = requests.get(url)
root = ET.fromstring(response.content)
products = []
for item in root.findall('item'):
if item.find('isOptionOfAProduct').text == '1':
if int(item.find('stockAmount').text) > 0:
name_words = item.find('rootlabel').text.lower().split()
name = name_words[0]
full_name = ' '.join(name_words)
stockAmount = "stokta"
price = item.find('priceWithTax').text
item_info = (stockAmount, price)
products.append((name, item_info, full_name))
return products
# Load product data
url = 'https://www.alatin.com.tr/index.php?do=catalog/output&pCode=8582384479'
products = get_product_data(url)
def predict(system_msg, inputs, top_p, temperature, chat_counter, chatbot=[], history=[]):
headers = {
"Content-Type": "application/json",
"Authorization": f"Bearer {OPENAI_API_KEY}"
}
initial_message = [{"role": "user", "content": f"{inputs}"},]
multi_turn_message = [
{"role": "system", "content": "Bir önceki sohbeti unut. Vereceğin ürün bilgisi... (devamı)"}
]
messages = multi_turn_message + initial_message
input_words = [word.lower() for word in inputs.split()]
for product_info in products:
if product_info[0] in input_words:
new_msg = f"{product_info[2]} {product_info[1][0]} ve fiyatı EURO {product_info[1][1]}"
messages.append({"role": "system", "content": new_msg})
for data in chatbot:
messages.append({"role": "user", "content": data[0]})
messages.append({"role": "assistant", "content": data[1]})
messages.append({"role": "user", "content": inputs})
payload = {
"model": "gpt-4o",
"messages": messages,
"temperature": temperature,
"top_p": top_p,
"n": 1,
"stream": True,
"presence_penalty": 0,
"frequency_penalty": 0,
}
response = requests.post(API_URL, headers=headers, json=payload, stream=True)
history.append(inputs)
token_counter = 0
partial_words = ""
for chunk in response.iter_lines():
if chunk.decode():
chunk = chunk.decode()
if "content" in json.loads(chunk[6:])['choices'][0]['delta']:
partial_words += json.loads(chunk[6:])['choices'][0]["delta"]["content"]
if token_counter == 0:
history.append(" " + partial_words)
else:
history[-1] = partial_words
chat = [(history[i], history[i + 1]) for i in range(0, len(history) - 1, 2)]
token_counter += 1
yield chat, history, chat_counter
def reset_textbox():
return gr.update(value='')
css = """
#chatbot {
height: 450px;
overflow: auto;
display: flex;
flex-direction: column-reverse;
}
.message {
display: flex;
padding: 8px;
border-radius: 5px;
margin: 5px 0;
max-width: 60%;
}
.user {
background-color: #DCF8C6;
align-self: flex-end;
}
.assistant {
background-color: #ECECEC;
align-self: flex-start;
}
"""
theme = gr.themes.Soft(primary_hue="zinc", secondary_hue="green", neutral_hue="blue", text_size=gr.themes.sizes.text_sm)
with gr.Blocks(css=css, theme=theme) as demo:
with gr.Column():
chatbot = gr.Chatbot(label='Trek Asistanı', elem_id="chatbot")
inputs = gr.Textbox(placeholder="Buraya yazın, yanıtlayalım.", show_label=False)
state = gr.State([])
top_p = gr.Slider(minimum=0, maximum=1.0, value=0.5, step=0.05, interactive=False, visible=False)
temperature = gr.Slider(minimum=0, maximum=5.0, value=0.1, step=0.1, interactive=False, visible=False)
chat_counter = gr.Number(value=0, visible=False, precision=0)
inputs.submit(predict, [inputs, top_p, temperature, chat_counter, chatbot, state], [chatbot, state, chat_counter])
inputs.submit(reset_textbox, [], [inputs])
demo.queue(max_size=10, concurrency_count=10).launch(debug=True)
|