gaur3009 commited on
Commit
964e64f
Β·
verified Β·
1 Parent(s): 709c9f6

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +129 -70
app.py CHANGED
@@ -1,22 +1,17 @@
1
  import gradio as gr
2
  import pandas as pd
3
- from transformers import AutoTokenizer, AutoModelForCausalLM
4
- from sentence_transformers import SentenceTransformer
5
  import faiss
6
  import torch
 
 
7
 
8
  # -------------------------------
9
  # Load dataset
10
  # -------------------------------
11
- file_path = "marketing-campaigns.csv"
12
  df = pd.read_csv(file_path)
13
-
14
- if df.empty:
15
- raise ValueError("CSV is empty. Please provide a dataset with campaign info.")
16
-
17
- # Join all columns to form knowledge text
18
- df = df.dropna()
19
- df["text"] = df.astype(str).agg(" | ".join, axis=1)
20
 
21
  # -------------------------------
22
  # Embeddings + FAISS
@@ -30,91 +25,155 @@ index = faiss.IndexFlatL2(d)
30
  index.add(embeddings_np)
31
 
32
  # -------------------------------
33
- # Load LLM (Phi-4-mini)
34
  # -------------------------------
35
- model_name = "microsoft/phi-4-mini"
36
- tokenizer = AutoTokenizer.from_pretrained(model_name)
37
- model = AutoModelForCausalLM.from_pretrained(model_name, torch_dtype=torch.float32, device_map="auto")
 
 
 
 
 
 
 
 
 
38
 
39
  # -------------------------------
40
- # RAG functions
41
  # -------------------------------
42
  def retrieve_context(query, k=3):
43
- """Retrieve top-k similar rows from dataset"""
44
- if not query.strip():
45
- return []
46
  query_vec = embed_model.encode([query], convert_to_tensor=True).cpu().numpy()
47
- D, I = index.search(query_vec, min(k, len(df)))
48
  results = [df.iloc[i]["text"] for i in I[0]]
49
  return results
50
 
51
- def generate_with_rag(prompt, k=3, temperature=0.7):
52
- if not prompt.strip():
53
- return "⚠️ Please enter a campaign idea or theme."
54
-
55
- # Step 1: Retrieve supporting facts
56
- context = retrieve_context(prompt, k)
57
- if not context:
58
- return "⚠️ No relevant context found in dataset."
59
- context_str = "\n".join(context[:k])
60
-
61
- # Step 2: Build grounded structured prompt
62
  rag_prompt = f"""
63
- You are a top-tier creative marketing AI assistant.
64
- Use the following supporting dataset entries as context:
65
  {context_str}
66
 
67
- Task: Generate a **structured marketing campaign** for:
68
  {prompt}
69
-
70
- Format your answer clearly with:
71
- - πŸ“Œ Campaign Title
72
- - ✨ Tagline
73
- - πŸ§‘β€πŸ€β€πŸ§‘ Target Audience
74
- - 🎯 Key Selling Points
75
- - 🎬 Creative Idea
76
  """
77
 
78
- # Step 3: LLM Generation
79
  inputs = tokenizer(rag_prompt, return_tensors="pt").to(model.device)
80
  outputs = model.generate(
81
  **inputs,
82
- max_length=300,
83
- temperature=float(temperature),
84
- top_p=0.9,
85
- do_sample=True
86
  )
87
  return tokenizer.decode(outputs[0], skip_special_tokens=True)
88
 
89
- def search_dataset(query, k=5):
90
- """Search dataset and return top matching rows"""
91
- context = retrieve_context(query, k)
92
- if not context:
93
- return "⚠️ No results found."
94
- return "\n\n".join(context)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
95
 
96
  # -------------------------------
97
  # Gradio UI
98
  # -------------------------------
99
- with gr.Blocks() as demo:
100
- gr.Markdown("# πŸ€– RAG-powered Creative Campaign Assistant")
101
- gr.Markdown("Generate **smart, creative, and data-grounded campaigns** with retrieval-augmented AI.")
102
-
103
- with gr.Tab("πŸ”Ž Explore Dataset"):
104
- search_query = gr.Textbox(label="Search dataset by keyword / theme")
105
- search_results = gr.Textbox(label="Top Matches", lines=10)
106
- search_btn = gr.Button("Search")
107
- search_btn.click(search_dataset, inputs=search_query, outputs=search_results)
108
-
109
- with gr.Tab("✍️ Generate Campaign"):
110
- with gr.Row():
111
- prompt = gr.Textbox(label="Enter campaign idea / theme", lines=3)
112
- with gr.Row():
113
- k_slider = gr.Slider(1, 10, value=3, step=1, label="Number of supporting facts (k)")
114
- temp_slider = gr.Slider(0.3, 1.2, value=0.7, step=0.1, label="Creativity (temperature)")
115
- campaign_output = gr.Textbox(label="Generated Campaign", lines=15)
116
- gen_btn = gr.Button("Generate with RAG")
117
- gen_btn.click(generate_with_rag, inputs=[prompt, k_slider, temp_slider], outputs=campaign_output)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
118
 
119
  if __name__ == "__main__":
120
  demo.launch()
 
1
  import gradio as gr
2
  import pandas as pd
 
 
3
  import faiss
4
  import torch
5
+ from transformers import AutoTokenizer, AutoModelForCausalLM
6
+ from sentence_transformers import SentenceTransformer
7
 
8
  # -------------------------------
9
  # Load dataset
10
  # -------------------------------
11
+ file_path = "marketing-campaigns.csv" # file uploaded in Hugging Face space
12
  df = pd.read_csv(file_path)
13
+ df = df.dropna() # drop completely empty rows
14
+ df["text"] = df.astype(str).agg(" | ".join, axis=1) # merge all cols into text
 
 
 
 
 
15
 
16
  # -------------------------------
17
  # Embeddings + FAISS
 
25
  index.add(embeddings_np)
26
 
27
  # -------------------------------
28
+ # Load LLM (default Phi-4-mini)
29
  # -------------------------------
30
+ model_choices = {
31
+ "openai/gpt-oss-120b": "microsoft/phi-4-mini",
32
+ "openai/gpt-oss-20b": "microsoft/phi-4-mini" # placeholder, can map to another HF model
33
+ }
34
+
35
+ current_model_id = "openai/gpt-oss-120b"
36
+ hf_model = model_choices[current_model_id]
37
+
38
+ tokenizer = AutoTokenizer.from_pretrained(hf_model)
39
+ model = AutoModelForCausalLM.from_pretrained(
40
+ hf_model, torch_dtype=torch.float32, device_map="auto"
41
+ )
42
 
43
  # -------------------------------
44
+ # RAG Functions
45
  # -------------------------------
46
  def retrieve_context(query, k=3):
 
 
 
47
  query_vec = embed_model.encode([query], convert_to_tensor=True).cpu().numpy()
48
+ D, I = index.search(query_vec, k)
49
  results = [df.iloc[i]["text"] for i in I[0]]
50
  return results
51
 
52
+ def generate_with_rag(prompt, temperature=0.8, max_tokens=250):
53
+ # Step 1: Retrieve context
54
+ context = retrieve_context(prompt, k=3)
55
+ context_str = "\n".join(context)
56
+
57
+ # Step 2: Construct grounded prompt
 
 
 
 
 
58
  rag_prompt = f"""
59
+ You are a creative AI campaign assistant.
60
+ Use the following supporting data to ground your answer:
61
  {context_str}
62
 
63
+ Task: Generate a unique and creative marketing campaign idea for:
64
  {prompt}
 
 
 
 
 
 
 
65
  """
66
 
67
+ # Step 3: Generate
68
  inputs = tokenizer(rag_prompt, return_tensors="pt").to(model.device)
69
  outputs = model.generate(
70
  **inputs,
71
+ max_length=max_tokens,
72
+ temperature=temperature,
73
+ top_p=0.9
 
74
  )
75
  return tokenizer.decode(outputs[0], skip_special_tokens=True)
76
 
77
+ def switch_model(model_choice):
78
+ """Switch between available models."""
79
+ global model, tokenizer, current_model_id
80
+ hf_model = model_choices.get(model_choice, "microsoft/phi-4-mini")
81
+ tokenizer = AutoTokenizer.from_pretrained(hf_model)
82
+ model = AutoModelForCausalLM.from_pretrained(
83
+ hf_model, torch_dtype=torch.float32, device_map="auto"
84
+ )
85
+ current_model_id = model_choice
86
+ return gr.update(visible=(model_choice=="openai/gpt-oss-120b")), gr.update(visible=(model_choice=="openai/gpt-oss-20b")), model_choice
87
+
88
+ # -------------------------------
89
+ # Custom CSS
90
+ # -------------------------------
91
+ custom_css = """
92
+ .gradio-container {
93
+ background: linear-gradient(135deg, #667eea 0%, #764ba2 25%, #f093fb 50%, #4facfe 75%, #00f2fe 100%);
94
+ background-size: 400% 400%;
95
+ animation: gradient-animation 15s ease infinite;
96
+ min-height: 100vh;
97
+ }
98
+ @keyframes gradient-animation {
99
+ 0% { background-position: 0% 50%; }
100
+ 50% { background-position: 100% 50%; }
101
+ 100% { background-position: 0% 50%; }
102
+ }
103
+ .main-container {
104
+ background-color: rgba(255, 255, 255, 0.95);
105
+ backdrop-filter: blur(10px);
106
+ border-radius: 20px;
107
+ padding: 20px;
108
+ box-shadow: 0 8px 32px 0 rgba(31, 38, 135, 0.37);
109
+ border: 1px solid rgba(255, 255, 255, 0.18);
110
+ margin: 10px;
111
+ }
112
+ """
113
 
114
  # -------------------------------
115
  # Gradio UI
116
  # -------------------------------
117
+ with gr.Blocks(fill_height=True, theme=gr.themes.Soft, css=custom_css) as demo:
118
+ # Top badges
119
+ with gr.Row(elem_classes="badge-container"):
120
+ gr.HTML("""
121
+ <div style="display: flex; justify-content: center; align-items: center; gap: 15px;">
122
+ <a href="https://huggingface.co/spaces/VIDraft/gpt-oss-RAG" target="_blank">
123
+ <img src="https://img.shields.io/static/v1?label=gpt-oss-20b&message=RAG&color=%23000080&labelColor=%23ffa500&logo=huggingface&logoColor=white&style=for-the-badge" alt="badge">
124
+ </a>
125
+ <a href="https://discord.gg/openfreeai" target="_blank">
126
+ <img src="https://img.shields.io/static/v1?label=Discord&message=Openfree%20AI&color=%23000080&labelColor=%23ffa500&logo=discord&logoColor=white&style=for-the-badge" alt="badge">
127
+ </a>
128
+ </div>
129
+ """)
130
+
131
+ with gr.Row():
132
+ # Sidebar
133
+ with gr.Column(scale=1):
134
+ with gr.Group(elem_classes="main-container"):
135
+ gr.Markdown("# πŸš€ Inference Provider")
136
+ model_dropdown = gr.Dropdown(
137
+ choices=list(model_choices.keys()),
138
+ value=current_model_id,
139
+ label="πŸ“Š Select Model"
140
+ )
141
+ reload_btn = gr.Button("πŸ”„ Apply Model Change", variant="primary")
142
+
143
+ with gr.Accordion("βš™οΈ Advanced Options", open=False):
144
+ temperature = gr.Slider(
145
+ minimum=0, maximum=2, value=0.8, step=0.1, label="Temperature"
146
+ )
147
+ max_tokens = gr.Slider(
148
+ minimum=50, maximum=1024, value=250, step=10, label="Max Tokens"
149
+ )
150
+
151
+ # Main chat area
152
+ with gr.Column(scale=3):
153
+ with gr.Group(elem_classes="main-container"):
154
+ gr.Markdown("## πŸ’¬ RAG-powered Creative Campaign Assistant")
155
+
156
+ query = gr.Textbox(label="Enter campaign idea / theme", lines=2)
157
+ output = gr.Textbox(label="Generated Campaign Script", lines=10)
158
+
159
+ btn = gr.Button("✨ Generate with RAG")
160
+
161
+ btn.click(
162
+ generate_with_rag,
163
+ inputs=[query, temperature, max_tokens],
164
+ outputs=output
165
+ )
166
+
167
+ with gr.Column(visible=True) as model_120b_container:
168
+ gr.Markdown("### Active Model: openai/gpt-oss-120b")
169
+ with gr.Column(visible=False) as model_20b_container:
170
+ gr.Markdown("### Active Model: openai/gpt-oss-20b")
171
+
172
+ reload_btn.click(
173
+ fn=switch_model,
174
+ inputs=[model_dropdown],
175
+ outputs=[model_120b_container, model_20b_container, gr.State(current_model_id)]
176
+ )
177
 
178
  if __name__ == "__main__":
179
  demo.launch()