clarice7 commited on
Commit
754c404
1 Parent(s): dc61214

Upload app.py

Browse files
Files changed (1) hide show
  1. app.py +75 -72
app.py CHANGED
@@ -1,18 +1,21 @@
1
  # import the relevant packages
2
  import os
3
  import csv
 
 
 
4
  import openai
5
  from openai import OpenAI
6
  import gradio as gr
7
  import huggingface_hub
8
  from huggingface_hub import Repository
9
- from datetime import datetime
10
 
11
- client = OpenAI(
12
- api_key=os.environ.get("API_TOKEN"),
13
- )
 
 
14
 
15
- # recording requests to Hugging Face dataset
16
  DATASET_REPO_URL = "https://huggingface.co/datasets/petcoblue/simulation_data"
17
  DATA_FILENAME = "user_agents.csv"
18
  DATA_FILE = os.path.join("data", DATA_FILENAME)
@@ -23,80 +26,80 @@ repo = Repository(
23
  local_dir="data", clone_from=DATASET_REPO_URL, use_auth_token=HF_TOKEN
24
  )
25
 
26
- # function to store the message to the Hugging Face site, if you would like to add more columns or information to track add it here
27
- def store_message(prompt: str, temperature: str, response: str):
28
- if prompt:
29
- with open(DATA_FILE, "a") as csvfile:
30
- writer = csv.DictWriter(csvfile, fieldnames=["prompt", "temperature", "response", "time"])
31
- writer.writerow(
32
- {"prompt": prompt,
33
- "temperature": temperature,
34
- "response": response,
35
- "time": str(datetime.now())}
36
- )
37
- commit_url = repo.push_to_hub()
38
- print(commit_url)
39
 
40
- return
 
 
 
 
 
 
 
 
 
41
 
42
- # defines who can enter the application with the secrets that are set up if used
43
- user_db = {
44
- os.environ["username"]: os.environ["password"],
45
- }
 
 
 
 
 
46
 
47
- # the OpenAI function to use the given prompt to the model defined.
48
- def mr_bot(prompt, tokens, temperature):
49
- response = client.chat.completions.create(
50
- model="gpt-3.5-turbo",
51
- messages=[{"role": "user", "content": prompt}],
52
- max_tokens=tokens,
53
- temperature=temperature,
54
- )
55
- store_message(prompt=prompt, temperature=temperature, response=response.choices[0].message.content)
56
-
57
- return response.choices[0].message.content
58
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
59
 
60
- # Gradio App interface and login set up
61
- description = "Use the examples below to see how different prompts generate different results. Use the examples to see how different prompting " \
62
- "techniques can enhance your prompts. They are split into three sections, (creative writing, problem solving in business, and " \
63
- "philosophical debate) with three different levels of prompt engineering, (basic, intermediate, and advanced)."
 
 
 
 
 
 
 
 
 
 
 
 
64
 
65
- demo = gr.Interface(fn=mr_bot,
66
- inputs=[gr.Textbox(placeholder="Select an example", interactive=False), gr.Slider(1, 800, default=800), gr.Slider(0.1, 1, default=0.75)],
67
- outputs="text",
68
- title="Intro to AI, Prompt Engineering",
69
- description=description,
70
- cache_examples=False,
71
- examples = [
72
- # Creative Writing
73
- # Basic Prompt:
74
- ["Write a story about a city.", 800, .90],
75
- # Intermediate Prompt:
76
- ["Write a story set in a futuristic city where technology controls everything.", 800, .90],
77
- # Advanced Prompt:
78
- ["Write a gripping tale set in a futuristic city named Neo-Philly, where an underground movement " \
79
- "is fighting against the oppressive control of AI over human life, focusing on a protagonist who was once a loyal AI prompt engineer.", 800, .90],
80
 
81
- # Problem Solving in Business
82
- # Basic Prompt:
83
- ["A company needs to improve its profits.", 800, .90],
84
- # Intermediate Prompt:
85
- ["A retail company is seeing a decline in profits due to online competition. What can they do?", 800, .90],
86
- # Advanced Prompt:
87
- ["Devise a comprehensive strategy for a brick-and-mortar retail company that has been losing market share to e-commerce giants. " \
88
- "Focus on innovative in-store experiences, digital integration, and customer loyalty programs to regain competitiveness.", 800, .90],
89
-
90
- # Philosophical Debate
91
- # Basic Prompt:
92
- ["Discuss the concept of happiness.", 800, .90],
93
- # Intermediate Prompt:
94
- ["Debate whether true happiness can be achieved through material wealth or if it's found in intangible experiences.", 800, .90],
95
- # Advanced Prompt:
96
- ["Critically analyze the philosophical arguments for and against the notion that true happiness is derived more from personal " \
97
- "fulfillment and self-actualization than from material possessions, considering perspectives from both Eastern and " \
98
- "Western philosophies.", 800, .90],
99
- ]
100
  )
101
 
102
  if __name__ == "__main__":
 
1
  # import the relevant packages
2
  import os
3
  import csv
4
+ import requests
5
+ import time
6
+ import pandas as pd
7
  import openai
8
  from openai import OpenAI
9
  import gradio as gr
10
  import huggingface_hub
11
  from huggingface_hub import Repository
 
12
 
13
+ api_key = os.environ.get("API_TOKEN")
14
+ headers = {
15
+ 'Authorization': 'Bearer ' + api_key,
16
+ 'Content-Type': 'application/json'
17
+ }
18
 
 
19
  DATASET_REPO_URL = "https://huggingface.co/datasets/petcoblue/simulation_data"
20
  DATA_FILENAME = "user_agents.csv"
21
  DATA_FILE = os.path.join("data", DATA_FILENAME)
 
26
  local_dir="data", clone_from=DATASET_REPO_URL, use_auth_token=HF_TOKEN
27
  )
28
 
29
+ user_agents = pd.read_csv('./user_agents.csv')
30
+ user_agents = user_agents.iloc[:,1:]
31
+ user_batch = user_agents[:10]
 
 
 
 
 
 
 
 
 
 
32
 
33
+ def create_description(row):
34
+ description = (
35
+ f"Imagine that you are currently {int(row['age'])} years old. You have {int(row['num_pets'])} pets "
36
+ f"and spend an average of ${row['avg_spending']} on Petco purchases. "
37
+ f"Your engagement with Petco marketing has a score of {int(row['engagement_score'])}. "
38
+ f"You have an income level of {int(row['income_level'])} and "
39
+ f"regularly buy items from Petco every {int(row['purchase_regularity'])} months. "
40
+ f"It has been {int(row['time_since_last_purchase'])} days since your last purchase with Petco."
41
+ )
42
+ return description
43
 
44
+ question = (
45
+ "Here are two images of Petco marketing emails:\n"
46
+ "- Image 0 is shown first.\n"
47
+ "- Image 1 is shown second.\n"
48
+ "Which email are you more likely to click through? Just answer with 0 for the first image or 1 for the second image.\n"
49
+ "Then, provide a list of up to five one-word characteristics of the email you chose that made you want to click through it. Separate each characteristic with a comma.\n\n"
50
+ "Example response:\n"
51
+ "1; Characteristics: Appealing, Sale, Bright, Simple, Exclusive\n"
52
+ )
53
 
54
+ def query_agent(description, question, image0, image1):
55
+ image0_path = os.path.join(image_directory, image0)
56
+ image1_path = os.path.join(image_directory, image1)
57
+ base64_image0 = encode_image(image0_path)
58
+ base64_image1 = encode_image(image1_path)
 
 
 
 
 
 
59
 
60
+ payload = {
61
+ "model": "gpt-4-vision-preview",
62
+ "messages": [
63
+ {"role": "system", "content": description},
64
+ {
65
+ "role": "user",
66
+ "content": [
67
+ {"type": "text", "text": question},
68
+ {"type": "image", "image_url": f"data:image/jpeg;base64,{base64_image0}"},
69
+ {"type": "image", "image_url": f"data:image/jpeg;base64,{base64_image1}"}
70
+ ]
71
+ }
72
+ ],
73
+ "max_tokens": 300,
74
+ "logprobs": True,
75
+ "top_logprobs": 1
76
+ }
77
 
78
+ for attempt in range(3):
79
+ try:
80
+ response = requests.post("https://api.openai.com/v1/chat/completions", headers=headers, json=payload)
81
+ if response.status_code == 200:
82
+ data = response.json()
83
+ preference = data['choices'][0]['message']['content']
84
+ top_logprobs = data['choices'][0]['logprobs']['content'][0]['top_logprobs']
85
+ return preference, top_logprobs
86
+ else:
87
+ print(f"HTTP Error {response.status_code} on attempt {attempt + 1}")
88
+ except requests.exceptions.RequestException as e:
89
+ print(f"Request failed on attempt {attempt + 1}: {e}")
90
+ time.sleep(1)
91
+ else:
92
+ print(f"Failed to analyze {image0} and {image1} after 3 attempts.")
93
+ return None, None
94
 
95
+ description = "Upload two images of emails and see which is generally preferred by Petco customers!"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
96
 
97
+ demo = gr.Interface(fn=query_agent,
98
+ inputs=[gr.UploadButton("Click to Upload Email 0", file_types=["image"], file_count="1"),
99
+ gr.UploadButton("Click to Upload Email 1", file_types=["image"], file_count="1")],
100
+ outputs="text",
101
+ title="Pairwise Simulation of Petco Email Preference",
102
+ description=description
 
 
 
 
 
 
 
 
 
 
 
 
 
103
  )
104
 
105
  if __name__ == "__main__":