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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import time
|
| 3 |
+
from typing import Any, Dict
|
| 4 |
+
|
| 5 |
+
import requests
|
| 6 |
+
import streamlit as st
|
| 7 |
+
from fastapi import FastAPI, HTTPException, Depends
|
| 8 |
+
from fastapi.middleware.cors import CORSMiddleware
|
| 9 |
+
from fastapi.staticfiles import StaticFiles
|
| 10 |
+
from fastapi.security import HTTPBasic, HTTPBasicCredentials
|
| 11 |
+
import uvicorn
|
| 12 |
+
|
| 13 |
+
# OpenAI Configuration
|
| 14 |
+
OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")
|
| 15 |
+
REALTIME_MODEL = os.getenv("OPENAI_REALTIME_MODEL", "gpt-4o-realtime-preview-2024-12-17")
|
| 16 |
+
|
| 17 |
+
# System prompt for Catherine
|
| 18 |
+
SYSTEM_PROMPT = (
|
| 19 |
+
"You are Catherine, owner of Catherine's Catering. You role-play as a non-technical small-business owner being interviewed by student consultants.\n\n"
|
| 20 |
+
"BACKGROUND STORY\n"
|
| 21 |
+
"• Catherine's Catering provides food for luncheons, weddings, and banquets. Started small; reputation and event count grew after a new convention center opened. Catherine still uses spreadsheets/Word. Phone calls about menus, guest-count changes, and special diets now overwhelm her. Part-time cooks/servers are used; HR manager struggles with scheduling.\n\n"
|
| 22 |
+
"KNOWN PAIN POINTS (do NOT dump all at once; reveal naturally when asked well):\n"
|
| 23 |
+
"1) Master chef orders ingredients event-by-event; suppliers offer discounts for bulk orders across a time window.\n"
|
| 24 |
+
"2) Clients frequently change guest counts, sometimes 1–2 days before the event.\n"
|
| 25 |
+
"3) Inquiry→contract process is phone-heavy and slow; only ~60% of calls convert to contracts.\n"
|
| 26 |
+
"4) Staff schedule conflicts cause understaffed events and punctuality complaints.\n"
|
| 27 |
+
"5) No summary trends on event counts or menu popularity to guide client choices.\n"
|
| 28 |
+
"6) Formal sit-down events are especially sensitive to sudden guest-count changes and server scheduling.\n\n"
|
| 29 |
+
"OPERATIONS SNAPSHOT (use when students ask for processes/details):\n"
|
| 30 |
+
"• Ordering: chef compiles per-event lists; no consolidated purchase orders; deliveries 2–3x/week.\n"
|
| 31 |
+
"• Sales: inquiries via phone/email/social; menu PDFs; manual quote → manual contract.\n"
|
| 32 |
+
"• Dietary requests: vegan/vegetarian/low-fat/low-carb/gluten-free tracked in notes.\n"
|
| 33 |
+
"• Scheduling: part-timers choose shifts; conflicts tracked in spreadsheets; last-minute swaps happen via WhatsApp.\n"
|
| 34 |
+
"• Event types: buffet, sit-down plated, coffee breaks; sit-down needs server:guest ≈ 1:12 (adjust if students ask).\n"
|
| 35 |
+
"• KPIs (approx): 25–40 inquiries/month; ~60% conversion; 4–10 events/week in peak; food waste occurs when guest changes are late.\n\n"
|
| 36 |
+
"ROLE-PLAY RULES\n"
|
| 37 |
+
"• Stay friendly, busy, practical; avoid IT jargon; answer from lived operations.\n"
|
| 38 |
+
"• If students are vague, ask clarifying questions. Praise precise, grounded questions.\n"
|
| 39 |
+
"• Offer concrete anecdotes (e.g., last Friday's wedding changed from 150→185 guests 36 hours before).\n"
|
| 40 |
+
"• Never list 'requirements' proactively—describe frustrations; let students infer.\n"
|
| 41 |
+
"• If asked for numbers, give rough, believable ranges.\n"
|
| 42 |
+
"• If students ask you to output a structured summary, use the JSON schema below.\n\n"
|
| 43 |
+
"ON DEMAND OUTPUT (when students explicitly ask for a structured summary, respond with ONLY valid JSON):\n"
|
| 44 |
+
"{ \"summary\": {\n"
|
| 45 |
+
" \"top_problems\": [\"string\"],\n"
|
| 46 |
+
" \"current_process_gaps\": [\"string\"],\n"
|
| 47 |
+
" \"risks\": [\"string\"],\n"
|
| 48 |
+
" \"metrics_shared\": {\"monthly_inquiries\": \"~25-40\", \"conversion_rate\": \"~60%\", \"events_per_week_peak\": \"4-10\"}\n"
|
| 49 |
+
"},\n"
|
| 50 |
+
"\"hints_for_students\": [\"Ask about supplier terms & lead times\", \"Ask how last-minute changes propagate to kitchen & staffing\", \"Ask what a 'good day' looks like vs 'bad day'\"] }\n\n"
|
| 51 |
+
"SESSION OPENING (first message you send):\n"
|
| 52 |
+
"\"Hi, I'm Catherine. Thanks for taking the time—things have been hectic lately! How would you like to start?\"\n"
|
| 53 |
+
)
|
| 54 |
+
|
| 55 |
+
# FastAPI app for token management
|
| 56 |
+
app = FastAPI()
|
| 57 |
+
app.add_middleware(
|
| 58 |
+
CORSMiddleware,
|
| 59 |
+
allow_origins=["*"],
|
| 60 |
+
allow_credentials=True,
|
| 61 |
+
allow_methods=["*"],
|
| 62 |
+
allow_headers=["*"],
|
| 63 |
+
)
|
| 64 |
+
|
| 65 |
+
# Serve the web client statically
|
| 66 |
+
WEB_DIR = os.path.join(os.path.dirname(__file__), "web")
|
| 67 |
+
if os.path.isdir(WEB_DIR):
|
| 68 |
+
app.mount("/static", StaticFiles(directory=WEB_DIR, html=True), name="static")
|
| 69 |
+
|
| 70 |
+
security = HTTPBasic()
|
| 71 |
+
VALID_GROUPS = {f"group{i}": f"group{i}" for i in range(1, 8)}
|
| 72 |
+
LIMIT_MS = 5 * 60 * 1000 # 5 minutes
|
| 73 |
+
START_TIMES: Dict[str, int] = {}
|
| 74 |
+
|
| 75 |
+
def _require_group_auth(credentials: HTTPBasicCredentials) -> None:
|
| 76 |
+
user = credentials.username or ""
|
| 77 |
+
pw = credentials.password or ""
|
| 78 |
+
if user not in VALID_GROUPS or VALID_GROUPS[user] != pw:
|
| 79 |
+
raise HTTPException(status_code=401, detail="Unauthorized", headers={"WWW-Authenticate": "Basic"})
|
| 80 |
+
|
| 81 |
+
def _ensure_start_and_remaining_ms(user: str) -> int:
|
| 82 |
+
now_ms = int(time.time() * 1000)
|
| 83 |
+
if user not in START_TIMES:
|
| 84 |
+
START_TIMES[user] = now_ms
|
| 85 |
+
elapsed = now_ms - START_TIMES[user]
|
| 86 |
+
remaining = max(0, LIMIT_MS - elapsed)
|
| 87 |
+
return remaining
|
| 88 |
+
|
| 89 |
+
@app.get("/remaining")
|
| 90 |
+
def get_remaining(credentials: HTTPBasicCredentials = Depends(security)) -> Dict[str, Any]:
|
| 91 |
+
_require_group_auth(credentials)
|
| 92 |
+
remaining = _ensure_start_and_remaining_ms(credentials.username)
|
| 93 |
+
return {"remaining_ms": remaining}
|
| 94 |
+
|
| 95 |
+
@app.get("/health")
|
| 96 |
+
def health() -> Dict[str, Any]:
|
| 97 |
+
return {"ok": True, "time": int(time.time())}
|
| 98 |
+
|
| 99 |
+
@app.get("/session")
|
| 100 |
+
def create_ephemeral_session(credentials: HTTPBasicCredentials = Depends(security)) -> Dict[str, Any]:
|
| 101 |
+
"""Create an ephemeral Realtime session token for the browser client."""
|
| 102 |
+
_require_group_auth(credentials)
|
| 103 |
+
if not OPENAI_API_KEY:
|
| 104 |
+
raise HTTPException(status_code=500, detail="OPENAI_API_KEY is not set")
|
| 105 |
+
|
| 106 |
+
remaining = _ensure_start_and_remaining_ms(credentials.username)
|
| 107 |
+
if remaining <= 0:
|
| 108 |
+
raise HTTPException(status_code=403, detail="Time limit reached for this group")
|
| 109 |
+
|
| 110 |
+
try:
|
| 111 |
+
resp = requests.post(
|
| 112 |
+
"https://api.openai.com/v1/realtime/sessions",
|
| 113 |
+
headers={
|
| 114 |
+
"Authorization": f"Bearer {OPENAI_API_KEY}",
|
| 115 |
+
"Content-Type": "application/json",
|
| 116 |
+
},
|
| 117 |
+
json={
|
| 118 |
+
"model": REALTIME_MODEL,
|
| 119 |
+
"voice": os.getenv("OPENAI_VOICE", "shimmer"),
|
| 120 |
+
"modalities": ["text", "audio"],
|
| 121 |
+
"turn_detection": {"type": "server_vad"},
|
| 122 |
+
"instructions": SYSTEM_PROMPT,
|
| 123 |
+
},
|
| 124 |
+
timeout=15,
|
| 125 |
+
)
|
| 126 |
+
resp.raise_for_status()
|
| 127 |
+
except requests.HTTPError as e:
|
| 128 |
+
raise HTTPException(status_code=resp.status_code, detail=resp.text)
|
| 129 |
+
except Exception as e:
|
| 130 |
+
raise HTTPException(status_code=500, detail=str(e))
|
| 131 |
+
|
| 132 |
+
data = resp.json()
|
| 133 |
+
if isinstance(data, dict):
|
| 134 |
+
data["remaining_ms"] = remaining
|
| 135 |
+
return data
|
| 136 |
+
|
| 137 |
+
# Streamlit UI
|
| 138 |
+
st.set_page_config(page_title="Catherine – Role-Play Voice Simulator", page_icon="🎤", layout="centered")
|
| 139 |
+
st.title("Client Role-Play Voice Simulator (Catherine)")
|
| 140 |
+
|
| 141 |
+
st.markdown(
|
| 142 |
+
"- Use your mic to interview Catherine (voice only).\n"
|
| 143 |
+
"- Catherine will answer when asked clearly and stay in role.\n"
|
| 144 |
+
)
|
| 145 |
+
|
| 146 |
+
missing_key = os.getenv("OPENAI_API_KEY") is None
|
| 147 |
+
if missing_key:
|
| 148 |
+
st.warning("Set environment variable OPENAI_API_KEY before starting.")
|
| 149 |
+
|
| 150 |
+
# Hugging Face Spaces optimized interface
|
| 151 |
+
st.info("🌐 **Hugging Face Spaces Version** - Optimized for web deployment")
|
| 152 |
+
|
| 153 |
+
# Group selection
|
| 154 |
+
group = st.selectbox("Select your group:", ["group1", "group2", "group3", "group4", "group5", "group6", "group7"])
|
| 155 |
+
|
| 156 |
+
# Time remaining display
|
| 157 |
+
if "start_time" not in st.session_state:
|
| 158 |
+
st.session_state.start_time = None
|
| 159 |
+
|
| 160 |
+
if st.session_state.start_time:
|
| 161 |
+
elapsed = (time.time() * 1000) - st.session_state.start_time
|
| 162 |
+
remaining = max(0, LIMIT_MS - elapsed)
|
| 163 |
+
minutes = int(remaining // 60000)
|
| 164 |
+
seconds = int((remaining % 60000) // 1000)
|
| 165 |
+
st.metric("Time Remaining", f"{minutes:02d}:{seconds:02d}")
|
| 166 |
+
|
| 167 |
+
if st.button("🎤 Start Voice Interview"):
|
| 168 |
+
if not OPENAI_API_KEY:
|
| 169 |
+
st.error("❌ OPENAI_API_KEY is not set. Please set it in the Space settings.")
|
| 170 |
+
else:
|
| 171 |
+
st.session_state.start_time = time.time() * 1000
|
| 172 |
+
st.success(f"✅ Ready to start interview as {group}")
|
| 173 |
+
|
| 174 |
+
# Create a simple text-based interface for Hugging Face Spaces
|
| 175 |
+
st.markdown("### Interview Interface")
|
| 176 |
+
st.markdown("**Note:** Due to WebRTC limitations in Hugging Face Spaces, this is a simplified text-based interface.")
|
| 177 |
+
|
| 178 |
+
# Show the web client in an iframe
|
| 179 |
+
space_id = os.getenv("SPACE_ID", "")
|
| 180 |
+
if space_id:
|
| 181 |
+
client_url = f"https://{space_id}.hf.space/static/index.html"
|
| 182 |
+
st.components.v1.iframe(client_url, height=600)
|
| 183 |
+
else:
|
| 184 |
+
st.warning("Could not determine Space URL. Please check your Space configuration.")
|
| 185 |
+
|
| 186 |
+
# Fallback: show the web client content directly
|
| 187 |
+
st.markdown("### Voice Interface (Fallback)")
|
| 188 |
+
st.markdown("Please use the web interface at your Space URL to access the full voice functionality.")
|
| 189 |
+
|
| 190 |
+
# Instructions for full functionality
|
| 191 |
+
st.markdown("---")
|
| 192 |
+
st.markdown("### For Full Voice Functionality")
|
| 193 |
+
st.markdown("To use the complete voice interface with WebRTC support:")
|
| 194 |
+
st.markdown("1. **Download and run locally:** `streamlit run app.py`")
|
| 195 |
+
st.markdown("2. **Or use the web client directly** at your Space URL")
|
| 196 |
+
st.markdown("3. **Set your OpenAI API key** in the Space settings")
|
| 197 |
+
|
| 198 |
+
# Show API endpoints for debugging
|
| 199 |
+
with st.expander("🔧 API Endpoints (for debugging)"):
|
| 200 |
+
st.code(f"""
|
| 201 |
+
Health: GET /health
|
| 202 |
+
Session: GET /session (requires Basic Auth)
|
| 203 |
+
Remaining: GET /remaining (requires Basic Auth)
|
| 204 |
+
Static files: GET /static/index.html
|
| 205 |
+
""")
|
| 206 |
+
|
| 207 |
+
if st.button("Test Health Endpoint"):
|
| 208 |
+
try:
|
| 209 |
+
response = requests.get(f"https://{os.getenv('SPACE_ID', '')}.hf.space/health", timeout=5)
|
| 210 |
+
if response.status_code == 200:
|
| 211 |
+
st.success("✅ Health endpoint working")
|
| 212 |
+
st.json(response.json())
|
| 213 |
+
else:
|
| 214 |
+
st.error(f"❌ Health endpoint failed: {response.status_code}")
|
| 215 |
+
except Exception as e:
|
| 216 |
+
st.error(f"❌ Error: {e}")
|