stacyyth commited on
Commit
4cdcf08
·
verified ·
1 Parent(s): bcceb9d

Upload get_brand_name.py

Browse files
Files changed (1) hide show
  1. get_brand_name.py +109 -0
get_brand_name.py ADDED
@@ -0,0 +1,109 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ """get_brand_name.ipynb
3
+
4
+ Automatically generated by Colab.
5
+
6
+ Original file is located at
7
+ https://colab.research.google.com/drive/1xmza5DAj2s5uh_SNFAIGOGPOPaBFIIKt
8
+
9
+ # ChatGPT API
10
+
11
+ ## Install Packages
12
+ Install all the necessary packages, it may take some time.
13
+ """
14
+
15
+ # install required packages
16
+ !pip install openai==1.35.9
17
+ !pip install gradio==4.44.1
18
+
19
+ """## Import and Setup
20
+ **Remember to fill in your OpenAI API in this block, tutorial to get the api is in our homework3 slides. Please make double sure not to share your api with anyone else.**
21
+ """
22
+
23
+ pip install openai==0.28
24
+
25
+ """## Part 1: Identify Brand Name"""
26
+
27
+ import openai
28
+ import pandas as pd
29
+ import gradio as gr
30
+ import os
31
+ import tempfile
32
+
33
+ # Replace with your OpenAI API key (from environment variable)
34
+ openai.api_key = "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"
35
+
36
+ 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."
37
+
38
+ # Function to call the GPT model
39
+ def call_gpt_4o_mini(prompt: str, input_text: str, temperature=0.7, top_p=0.5):
40
+ try:
41
+ response = openai.ChatCompletion.create(
42
+ model="gpt-4o-mini",
43
+ messages=[
44
+ {"role": "system", "content": prompt},
45
+ {"role": "user", "content": input_text}
46
+ ],
47
+ max_tokens=2000, # Adjust based on the model's token limit
48
+ temperature=temperature,
49
+ )
50
+ return response.choices[0].message['content'] if response else "No response from model"
51
+ except Exception as e:
52
+ return f"Error: {str(e)}"
53
+
54
+ # Function to identify brands in a text
55
+ def identify_brands(text):
56
+ return call_gpt_4o_mini(prompt, text)
57
+
58
+ # Function to process the uploaded file and identify brand names
59
+ def process_file(file):
60
+ # Detect file type based on extension and read accordingly
61
+ if file.name.endswith(".csv"):
62
+ df = pd.read_csv(file.name, header=None, names=["Product Title"])
63
+ elif file.name.endswith(".txt"):
64
+ with open(file.name, "r", encoding="utf-8") as f:
65
+ lines = f.readlines()
66
+ df = pd.DataFrame({"Product Title": [line.strip() for line in lines if line.strip()]})
67
+ else:
68
+ raise ValueError("Unsupported file format. Please upload a CSV or TXT file.")
69
+
70
+ # Apply the brand identification function to each product title
71
+ df['Identified Brand'] = df['Product Title'].apply(identify_brands)
72
+ return df
73
+
74
+ # Gradio interface function
75
+ def process_inputs(input_text, file):
76
+ if input_text and not file:
77
+ # Process text input
78
+ return identify_brands(input_text), None, None
79
+ elif file and not input_text:
80
+ try:
81
+ result_df = process_file(file)
82
+
83
+ # Save the DataFrame to a temporary CSV file
84
+ temp_file = tempfile.NamedTemporaryFile(delete=False, suffix=".csv")
85
+ result_df.to_csv(temp_file.name, index=False)
86
+ return None, result_df, temp_file.name
87
+ except Exception as e:
88
+ return f"Error: {str(e)}", None, None
89
+ else:
90
+ return "Please provide either a product title or upload a file, not both.", None, None
91
+
92
+ # Define the Gradio interface
93
+ interface = gr.Interface(
94
+ fn=process_inputs,
95
+ inputs=[
96
+ gr.Textbox(label="Enter Product Title", placeholder="Type product title here...", lines=1),
97
+ gr.File(label="Upload CSV/TXT File")
98
+ ],
99
+ outputs=[
100
+ gr.Textbox(label="Identified Brand"),
101
+ gr.Dataframe(label="Identified Brands from File"),
102
+ gr.File(label="Download CSV")
103
+ ],
104
+ title="Brand Name Identifier",
105
+ description="Enter a product title to identify the brand or upload a CSV/TXT file containing product titles."
106
+ )
107
+
108
+ # Launch the interface
109
+ interface.launch(share=True)