Spaces:
Sleeping
Sleeping
| import os | |
| import gradio as gr | |
| from openai import OpenAI | |
| import pandas as pd | |
| import ast | |
| from sklearn.metrics.pairwise import cosine_similarity | |
| import numpy as np | |
| # Get value OPEN_API_KEY | |
| OPENAI_API_KEY = os.environ.get("OPENAI_API_KEY") | |
| login = os.environ.get("login") | |
| password = os.environ.get("password") | |
| client = OpenAI(api_key=OPENAI_API_KEY) | |
| # Load embedding dataset | |
| data = pd.read_csv("embeddings.csv") | |
| data["embedding"] = data["embedding"].apply(ast.literal_eval) | |
| 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) | |
| ) | |
| ) | |
| res = df.sort_values("similarities", ascending=False).head(n) | |
| return res.reset_index(drop=True) | |
| def generate_response(text): | |
| reference = search_reviews(data, text, without_newlines=False)["Content"][0] | |
| completion = client.chat.completions.create( | |
| model="gpt-3.5-turbo", | |
| 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}"}, | |
| ], | |
| temperature=0 | |
| ) | |
| result = completion.choices[0].message.content | |
| return result | |
| iface = gr.Interface(fn=generate_response, inputs="text", outputs="text") | |
| iface.launch(auth=(login, password)) | |