Spaces:
Paused
Paused
| # filename: frontend_pam.py (UPDATED FOR HF INFERENCE API) | |
| import os | |
| import json | |
| import random | |
| import requests | |
| from datetime import datetime | |
| from typing import Dict, Any, Optional | |
| # --- Constants for Data Paths --- | |
| BASE_DIR = os.path.dirname(os.path.abspath(__file__)) | |
| DATA_DIR = os.path.join(BASE_DIR, "data") | |
| APPOINTMENTS_FILE = os.path.join(DATA_DIR, "appointments.json") | |
| RESOURCES_FILE = os.path.join(DATA_DIR, "resources.json") | |
| FOLLOW_UP_FILE = os.path.join(DATA_DIR, "follow_up.json") | |
| PERMISSIONS_FILE = os.path.join(DATA_DIR, "permissions.json") | |
| # --- HuggingFace Inference API Setup --- | |
| HF_API_TOKEN = os.getenv("HF_READ_TOKEN") | |
| HF_HEADERS = {"Authorization": f"Bearer {HF_API_TOKEN}"} | |
| HF_ENDPOINTS = { | |
| "intent": "https://api-inference.huggingface.co/models/typeform/distilbert-base-uncased-mnli", | |
| "sentiment": "https://api-inference.huggingface.co/models/distilbert-base-uncased-finetuned-sst-2-english", | |
| "summarizer": "https://api-inference.huggingface.co/models/google/flan-t5-large", | |
| "chat": "https://api-inference.huggingface.co/models/tiiuae/falcon-7b-instruct" | |
| } | |
| # --- Load JSON Helper --- | |
| def load_json(filepath: str) -> Dict[str, Any]: | |
| try: | |
| with open(filepath, 'r') as f: | |
| return json.load(f) | |
| except FileNotFoundError: | |
| print(f"CRITICAL: Data file not found at: {filepath}") | |
| return {} | |
| except json.JSONDecodeError as e: | |
| print(f"CRITICAL: Failed to decode JSON from {filepath}: {e}") | |
| return {} | |
| # --- Inference API Call Helper --- | |
| def hf_infer(task: str, payload: Any) -> Any: | |
| url = HF_ENDPOINTS.get(task) | |
| if not url: | |
| return {"error": f"Invalid task: {task}"} | |
| response = requests.post(url, headers=HF_HEADERS, json=payload) | |
| if response.status_code != 200: | |
| return {"error": f"HF API Error ({response.status_code})", "details": response.text} | |
| return response.json() | |
| # --- Agent Initialization --- | |
| def load_frontend_agent() -> 'FrontendPAM': | |
| print("Initializing Frontend PAM using HF Inference API...") | |
| data = { | |
| "APPOINTMENTS": load_json(APPOINTMENTS_FILE), | |
| "RESOURCES": load_json(RESOURCES_FILE), | |
| "FOLLOW_UP": load_json(FOLLOW_UP_FILE), | |
| "PERMISSIONS": load_json(PERMISSIONS_FILE) | |
| } | |
| return FrontendPAM(data) | |
| # --- PAM Personality --- | |
| PAM_TONE = ("I am PAM — the cool older sister... [Full description abridged]") | |
| GREETINGS = ["babe", "love", "friend", "girl", "boo", "sweetheart"] | |
| # --- Agent Class --- | |
| class FrontendPAM: | |
| def __init__(self, data: Dict[str, Dict]): | |
| self.APPOINTMENTS = data.get("APPOINTMENTS", {}) | |
| self.PERMISSIONS = data.get("PERMISSIONS", {}) | |
| self.RESOURCES = data.get("RESOURCES", {}) | |
| self.FOLLOW_UP = data.get("FOLLOW_UP", {}) | |
| self.user_id = "user_001" | |
| def respond(self, user_text: str, backend_brief: Optional[str] = None) -> Dict[str, Any]: | |
| if not user_text.lower().startswith("hey pam"): | |
| return {"reply": "Oops, you didn’t say 'Hey Pam'. I only respond to respectful greetings — you know how I am. 💅"} | |
| text = user_text.replace("PAM", "you").replace("pam", "you") | |
| detected_intent = hf_infer("intent", {"inputs": text})[0].get("label", "unknown") | |
| sentiment_result = hf_infer("sentiment", {"inputs": text})[0] | |
| backend_summary = backend_brief or "No backend input provided." | |
| greeting = random.choice(GREETINGS) | |
| for term, allowed in self.PERMISSIONS.items(): | |
| if term in text.lower() and not allowed: | |
| return {"reply": f"That’s something I’m not allowed to help with directly, {greeting}. But I can connect you to a safe resource or provider if you’d like."} | |
| if "appointment" in text.lower(): | |
| appt = self.APPOINTMENTS.get(self.user_id) | |
| if appt: | |
| return {"reply": f"Hey {greeting}, you've got a {appt['type']} scheduled..."} | |
| else: | |
| return {"reply": f"Hey {greeting}, I don’t have any appointments saved..."} | |
| elif any(keyword in text.lower() for keyword in ["cramp", "discharge", "bleed", "smell", "spotting", "fatigue", "mood", "missed"]): | |
| return {"reply": f"Okay {greeting}, I pulled a few resources I think will help..."} | |
| else: | |
| prompt = f"{PAM_TONE}\n... User said: {text}\nPAM:" | |
| chat_output = hf_infer("chat", {"inputs": prompt}) | |
| reply = chat_output[0].get("generated_text", "Sorry love, I didn’t catch that. Try again?").split("PAM:")[-1].strip() | |
| return { | |
| "intent": detected_intent, | |
| "sentiment": sentiment_result, | |
| "summary": backend_summary, | |
| "reply": reply | |
| } |