for_y_space / app.py
stacyyth's picture
Update app.py
501a624 verified
Raw History Blame Contribute Delete
3.55 kB
# -*- 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()