Spaces:
Sleeping
Sleeping
File size: 3,546 Bytes
4cdcf08 044d1dc 4cdcf08 044d1dc 4cdcf08 501a624 | 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 | # -*- coding: utf-8 -*-
"""get_brand_name.ipynb
Automatically generated by Colab.
Original file is located at
https://colab.research.google.com/drive/1xmza5DAj2s5uh_SNFAIGOGPOPaBFIIKt
# ChatGPT API
"""## Part 1: Identify Brand Name"""
import openai
import pandas as pd
import gradio as gr
import os
import tempfile
# Replace with your OpenAI API key (from environment variable)
openai.api_key = os.getenv("OPENAI_API_KEY")
prompt = "Identify the brand name from a list of product or mixed product-brand names I provide. The brand name could be pure Traditional Chinese or pure English or mix. If no brand name exists in a given entry, respond with no_brand. If you think the title is the brand name, it is ok to provide the same name as title."
# Function to call the GPT model
def call_gpt_4o_mini(prompt: str, input_text: str, temperature=0.7, top_p=0.5):
try:
response = openai.ChatCompletion.create(
model="gpt-4o-mini",
messages=[
{"role": "system", "content": prompt},
{"role": "user", "content": input_text}
],
max_tokens=20000, # Adjust based on the model's token limit
temperature=temperature,
)
return response.choices[0].message['content'] if response else "No response from model"
except Exception as e:
return f"Error: {str(e)}"
# Function to identify brands in a text
def identify_brands(text):
return call_gpt_4o_mini(prompt, text)
# Function to process the uploaded file and identify brand names
def process_file(file):
# Detect file type based on extension and read accordingly
if file.name.endswith(".csv"):
df = pd.read_csv(file.name, header=None, names=["Product Title"])
elif file.name.endswith(".txt"):
with open(file.name, "r", encoding="utf-8") as f:
lines = f.readlines()
df = pd.DataFrame({"Product Title": [line.strip() for line in lines if line.strip()]})
else:
raise ValueError("Unsupported file format. Please upload a CSV or TXT file.")
# Apply the brand identification function to each product title
df['Identified Brand'] = df['Product Title'].apply(identify_brands)
return df
# Gradio interface function
def process_inputs(input_text, file):
if input_text and not file:
# Process text input
return identify_brands(input_text), None, None
elif file and not input_text:
try:
result_df = process_file(file)
# Save the DataFrame to a temporary CSV file
temp_file = tempfile.NamedTemporaryFile(delete=False, suffix=".csv")
result_df.to_csv(temp_file.name, index=False)
return None, result_df, temp_file.name
except Exception as e:
return f"Error: {str(e)}", None, None
else:
return "Please provide either a product title or upload a file, not both.", None, None
# Define the Gradio interface
interface = gr.Interface(
fn=process_inputs,
inputs=[
gr.Textbox(label="Enter Product Title", placeholder="Type product title here...", lines=1),
gr.File(label="Upload CSV/TXT File")
],
outputs=[
gr.Textbox(label="Identified Brand"),
gr.Dataframe(label="Identified Brands from File"),
gr.File(label="Download CSV")
],
title="Brand Name Identifier",
description="Enter a product title to identify the brand or upload a CSV/TXT file containing product titles."
)
# Launch the interface
interface.launch() |