File size: 2,753 Bytes
3e7aec7
52af337
 
 
 
 
ea1d523
52af337
ea1d523
3e7aec7
 
 
52af337
ea1d523
 
 
 
52af337
 
 
ea1d523
ecc0438
ea1d523
 
 
52af337
ea1d523
52af337
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ea1d523
52af337
 
 
 
ea1d523
3e7aec7
ea1d523
52af337
98fc1cc
 
3e7aec7
98fc1cc
 
 
 
 
 
 
 
52af337
98fc1cc
52af337
 
ea1d523
 
 
 
d23c9b8
ea1d523
52af337
ea1d523
d23c9b8
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
import os
import gradio as gr
import pandas as pd
import ast
from sklearn.metrics.pairwise import cosine_similarity
import numpy as np
from openai import OpenAI, ChatCompletion

# Получаем значения OPEN_API_KEY, login, и password
OPENAI_API_KEY = os.environ.get("OPENAI_API_KEY")
login = os.environ.get("login")
password = os.environ.get("password")

# Инициализируем OpenAI API клиент
client = OpenAI(api_key=OPENAI_API_KEY)

# Загружаем данные embeddings
data = pd.read_csv("embeddings.csv")
data["embedding"] = data["embedding"].apply(ast.literal_eval)

# Элементы Gradio интерфейса
model_dropdown = gr.Dropdown(choices=["gpt-3.5-turbo", "gpt-4-1106-preview"], label="Select Model")
temperature_slider = gr.Slider(minimum=0, maximum=1.0, value=0, label="Temperature")
top_p_slider = gr.Slider(minimum=0.01, maximum=1.0, value=1, label="Top P")
textbox_input = gr.Textbox(label="Enter text here")

# Функция поиска отзывов
def search_reviews(df_original, product_description, without_newlines=False, n=1):
    df = df_original.copy()
    if without_newlines:
        product_description = product_description.replace("\n", " ")

    embedding = (
        client.embeddings.create(
            input=[product_description], model="text-embedding-ada-002"
        )
        .data[0]
        .embedding
    )
    df["similarities"] = df["embedding"].apply(
        lambda x: cosine_similarity(
            np.array(x).reshape(1, -1), np.array(embedding).reshape(1, -1)
        )[0][0]
    )
    res = df.sort_values("similarities", ascending=False).head(n)
    return res.reset_index(drop=True)

# Функция генерации ответа
def generate_response(text, model, temperature, top_p):
    reference = search_reviews(data, text, without_newlines=True)["Content"][0]

    completion = client.chat.completions.create(
        model=model,
        temperature=temperature,
        top_p=top_p,
        messages=[
            {
                "role": "system",
                "content": f"Generate high-quality rewritten articles, ensuring logical composition, avoiding over-exaggeration, and refraining from any imaginative elements. Use the provided sample text as a reference for the desired writing style:{reference}",
            },
            {"role": "user", "content": f"{text}"},
        ],
    )
    result = completion.choices[0].message.content
    return result

# Создаём интерфейс Gradio
iface = gr.Interface(
    fn=generate_response,
    inputs=[textbox_input, model_dropdown, temperature_slider, top_p_slider],
    outputs='text'
)

# Запускаем интерфейс Gradio
iface.launch(auth=(login, password))