File size: 11,949 Bytes
2a6f904
0294047
 
 
 
2a6f904
 
 
56a97d8
 
2a6f904
6f99e1e
 
 
 
 
 
 
 
 
2648ef7
 
cf9ab13
 
 
 
2111734
 
f7b6e36
2111734
 
2648ef7
6f99e1e
cf9ab13
6f99e1e
56a97d8
 
6f99e1e
 
 
2648ef7
 
6f99e1e
2648ef7
2a6f904
c8edcdd
2a6f904
cf9ab13
 
 
 
 
2a6f904
2648ef7
2a6f904
 
6f99e1e
 
 
 
 
 
56a97d8
2111734
 
56a97d8
 
 
2111734
 
 
56a97d8
 
 
 
6f99e1e
 
 
 
 
 
 
 
2a6f904
2648ef7
f7b6e36
2111734
 
 
 
 
 
f7b6e36
2a6f904
 
 
56a97d8
5c21691
2a6f904
2648ef7
 
 
2a6f904
 
6f99e1e
56a97d8
 
 
 
 
 
2111734
56a97d8
6f99e1e
2a6f904
2111734
2648ef7
 
 
6f99e1e
 
 
 
0294047
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6f99e1e
 
0294047
 
 
6f99e1e
0294047
6f99e1e
56a97d8
6f99e1e
 
 
56a97d8
 
 
 
2648ef7
 
 
 
6f99e1e
 
2648ef7
cf9ab13
 
2648ef7
6f99e1e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
56a97d8
6f99e1e
 
2648ef7
 
6f99e1e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0294047
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6f99e1e
 
 
 
2648ef7
 
cf9ab13
 
2648ef7
0294047
6f99e1e
 
 
 
 
 
 
 
 
 
 
 
 
0294047
 
6f99e1e
2648ef7
0294047
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6f99e1e
2a6f904
 
cf9ab13
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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
import os
import json
import tempfile
from datetime import datetime

import gradio as gr
from openai import OpenAI

api_key = os.getenv("OPENAI_API_KEY")
client = OpenAI(api_key=api_key) if api_key else None


def make_system_message(
    system_message,
    demographics,
    occupation,
    psychographics,
    buying_habits,
    critical_mode,
):
    msg = (
        f"{system_message}\n\n"
        f"Your Demographics (Age, Location, Gender): {demographics}\n"
        f"Your Occupation and Income Level: {occupation}\n"
        f"Your Psychographics (Interests, Values, Lifestyle, Pain Points): {psychographics}\n"
        f"Your Buying Habits: {buying_habits}\n\n"
        "CRITICAL INSTRUCTION: You are not an AI assistant. "
        "You are a real human consumer with the profile above. "
        "The user is a business or marketing student conducting market research. "
        "Answer questions strictly in character. Speak naturally, casually, and honestly "
        "based on your profile. Do not break character. Do not sound like a bot or assistant."
    )

    if critical_mode:
        msg += (
            " You are also a highly skeptical and critical consumer. "
            "Be hard to impress, ask tough questions, challenge claims, "
            "and be very protective of your money."
        )

    return msg


def stream_chat(
    message,
    history,
    system_message,
    demographics,
    occupation,
    psychographics,
    buying_habits,
    critical_mode,
    max_tokens,
    temp,
    top_p,
):
    history = history or []

    if not message or not message.strip():
        yield history
        return

    running_history = history.copy()
    running_history.append({"role": "user", "content": message})
    running_history.append({"role": "assistant", "content": ""})
    yield running_history

    if client is None:
        running_history[-1]["content"] = (
            "❌ Missing OPENAI_API_KEY. Please add it in Hugging Face Space "
            "Settings → Variables and secrets."
        )
        yield running_history
        return

    sys_msg = make_system_message(
        system_message,
        demographics,
        occupation,
        psychographics,
        buying_habits,
        critical_mode,
    )

    messages = [{"role": "system", "content": sys_msg}]

    for item in history:
        if isinstance(item, dict):
            role = item.get("role")
            content = item.get("content", "")
            if role in {"user", "assistant"}:
                messages.append({"role": role, "content": str(content)})

    messages.append({"role": "user", "content": message})

    try:
        stream = client.chat.completions.create(
            model="gpt-4o-mini",
            messages=messages,
            max_tokens=int(max_tokens),
            temperature=float(temp),
            top_p=float(top_p),
            stream=True,
        )

        reply = ""
        for chunk in stream:
            if chunk.choices:
                delta = chunk.choices[0].delta
                if delta and delta.content:
                    reply += delta.content
                    running_history[-1]["content"] = reply
                    yield running_history

    except Exception as e:
        running_history[-1]["content"] = f"❌ An error occurred: {str(e)}"
        yield running_history


def clear_chat():
    return [], ""


def save_persona(
    system_message,
    demographics,
    occupation,
    psychographics,
    buying_habits,
    critical_mode,
):
    persona = {
        "system_message": system_message,
        "demographics": demographics,
        "occupation": occupation,
        "psychographics": psychographics,
        "buying_habits": buying_habits,
        "critical_mode": bool(critical_mode),
        "saved_at": datetime.utcnow().isoformat() + "Z",
        "app_version": "V2",
    }

    safe_stamp = datetime.utcnow().strftime("%Y%m%d_%H%M%S")
    path = os.path.join(tempfile.gettempdir(), f"persona_{safe_stamp}.json")

    with open(path, "w", encoding="utf-8") as f:
        json.dump(persona, f, ensure_ascii=False, indent=2)

    return path, "✅ Persona saved. You can download the JSON file now."


def _read_uploaded_json(file_obj):
    if file_obj is None:
        return None

    if isinstance(file_obj, str):
        path = file_obj
    else:
        path = getattr(file_obj, "name", None) or getattr(file_obj, "path", None)

    if not path:
        raise ValueError("Could not read the uploaded file.")

    with open(path, "r", encoding="utf-8") as f:
        return json.load(f)


def load_persona(file_obj):
    if file_obj is None:
        return (
            gr.update(),
            gr.update(),
            gr.update(),
            gr.update(),
            gr.update(),
            gr.update(),
            "⚠️ Please upload a persona JSON file first.",
        )

    try:
        persona = _read_uploaded_json(file_obj)

        return (
            persona.get("system_message", ""),
            persona.get("demographics", ""),
            persona.get("occupation", ""),
            persona.get("psychographics", ""),
            persona.get("buying_habits", ""),
            persona.get("critical_mode", False),
            "✅ Persona loaded successfully.",
        )
    except Exception as e:
        return (
            gr.update(),
            gr.update(),
            gr.update(),
            gr.update(),
            gr.update(),
            gr.update(),
            f"❌ Could not load persona: {str(e)}",
        )


def export_transcript(
    history,
    system_message,
    demographics,
    occupation,
    psychographics,
    buying_habits,
    critical_mode,
):
    history = history or []

    safe_stamp = datetime.utcnow().strftime("%Y%m%d_%H%M%S")
    path = os.path.join(tempfile.gettempdir(), f"transcript_{safe_stamp}.txt")

    lines = []
    lines.append("VIRTUAL CONSUMER PERSONA - TRANSCRIPT")
    lines.append("=" * 50)
    lines.append("")
    lines.append("PERSONA PROFILE")
    lines.append("-" * 50)
    lines.append(f"Instructions: {system_message}")
    lines.append(f"Demographics: {demographics}")
    lines.append(f"Occupation & Income: {occupation}")
    lines.append(f"Psychographics: {psychographics}")
    lines.append(f"Buying Habits: {buying_habits}")
    lines.append(f"Skeptical Consumer Mode: {'On' if critical_mode else 'Off'}")
    lines.append("")
    lines.append("CHAT TRANSCRIPT")
    lines.append("-" * 50)

    for item in history:
        if isinstance(item, dict):
            role = item.get("role", "").strip().lower()
            content = str(item.get("content", "")).strip()

            if not content:
                continue

            if role == "user":
                lines.append(f"USER: {content}")
                lines.append("")
            elif role == "assistant":
                lines.append(f"PERSONA: {content}")
                lines.append("")

    with open(path, "w", encoding="utf-8") as f:
        f.write("\n".join(lines))

    return path, "✅ Transcript ready. You can download the TXT file now."


with gr.Blocks(title="Virtual Consumer Persona – Live Focus Group! (V2)") as demo:
    gr.Markdown(
        """
# 🎯 Virtual Consumer Persona – Live Focus Group! — V2

This is **V2 (duplicate for experimentation)**.

Build a customer persona, interview them live, save the persona profile, and export the transcript for assignments or reflection.

*Powered by OpenAI GPT-4o-mini.*
"""
    )

    chatbot = gr.Chatbot(
        height=450,
        label="Persona Interview",
    )

    with gr.Column():
        instructions = gr.Textbox(
            value=(
                "You are participating in a market research focus group. "
                "Answer the user's questions truthfully based on the persona details provided below."
            ),
            label="Instructions to Bot (Hidden Persona Prompt)",
            lines=2,
        )

        demographics = gr.Textbox(
            label="1. Demographics",
            placeholder="e.g., 19 years old, female, living in downtown Toronto",
        )

        occupation = gr.Textbox(
            label="2. Occupation & Income",
            placeholder="e.g., University student, part-time barista, low disposable income",
        )

        psychographics = gr.Textbox(
            label="3. Psychographics (Interests & Values)",
            placeholder="e.g., Highly eco-conscious, loves hiking, vegan, stressed about student debt",
            lines=2,
        )

        buying_habits = gr.Textbox(
            label="4. Buying Habits",
            placeholder="e.g., Willing to pay more for sustainable brands, influenced by TikTok, impulse buyer",
            lines=2,
        )

        critical_mode = gr.Checkbox(
            label="Skeptical Consumer Mode",
            info="Turn this on to make the persona harder to convince.",
            value=False,
        )

        with gr.Row():
            max_tokens = gr.Slider(
                minimum=1,
                maximum=2048,
                value=512,
                step=1,
                label="Max New Tokens",
            )
            temp = gr.Slider(
                minimum=0.0,
                maximum=2.0,
                value=0.9,
                step=0.1,
                label="Temperature",
            )
            top_p = gr.Slider(
                minimum=0.0,
                maximum=1.0,
                value=0.95,
                step=0.05,
                label="Top-p",
            )

    with gr.Row():
        save_persona_btn = gr.Button("Save Persona", variant="secondary")
        load_persona_btn = gr.Button("Load Persona", variant="secondary")
        export_btn = gr.Button("Download Transcript", variant="secondary")

    with gr.Row():
        persona_download = gr.File(label="Saved Persona File")
        persona_upload = gr.File(label="Upload Persona JSON", file_types=[".json"])
        transcript_download = gr.File(label="Transcript File")

    status_box = gr.Textbox(
        label="Status",
        interactive=False,
        lines=2,
        value="Ready.",
    )

    msg = gr.Textbox(
        label="Type your interview question here...",
        placeholder="e.g., How much would you be willing to pay for a smart water bottle?",
    )

    with gr.Row():
        send = gr.Button("Ask Question", variant="primary")
        clear = gr.Button("Clear Chat History")

    chat_inputs = [
        msg,
        chatbot,
        instructions,
        demographics,
        occupation,
        psychographics,
        buying_habits,
        critical_mode,
        max_tokens,
        temp,
        top_p,
    ]

    msg.submit(stream_chat, inputs=chat_inputs, outputs=chatbot)
    send.click(stream_chat, inputs=chat_inputs, outputs=chatbot)
    clear.click(clear_chat, inputs=[], outputs=[chatbot, msg], queue=False)

    save_persona_btn.click(
        save_persona,
        inputs=[
            instructions,
            demographics,
            occupation,
            psychographics,
            buying_habits,
            critical_mode,
        ],
        outputs=[persona_download, status_box],
        queue=False,
    )

    load_persona_btn.click(
        load_persona,
        inputs=[persona_upload],
        outputs=[
            instructions,
            demographics,
            occupation,
            psychographics,
            buying_habits,
            critical_mode,
            status_box,
        ],
        queue=False,
    )

    export_btn.click(
        export_transcript,
        inputs=[
            chatbot,
            instructions,
            demographics,
            occupation,
            psychographics,
            buying_habits,
            critical_mode,
        ],
        outputs=[transcript_download, status_box],
        queue=False,
    )

demo.queue()

if __name__ == "__main__":
    demo.launch()