Tina / index.html
KyleAIers's picture
Update index.html
26fba03 verified
Raw History Blame Contribute Delete
9.99 kB
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>HealthyLifePhil - AI Business Chatbot</title>
<!-- React, Tailwind, and Supabase -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/18.2.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.2.0/umd/react-dom.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/7.23.5/babel.min.js"></script>
<script src="https://cdn.tailwindcss.com"></script>
<script src="https://cdn.jsdelivr.net/npm/@supabase/supabase-js@2"></script>
</head>
<body class="bg-slate-950 text-white font-sans">
<div id="root"></div>
<!-- ESM Transformers.js Module Setup -->
<script type="module">
import { pipeline, env } from 'https://cdn.jsdelivr.net/npm/@xenova/transformers@2.14.0';
env.allowLocalModels = false;
window.hfPipeline = pipeline;
</script>
<script type="text/babel">
const { useState, useEffect, useRef } = React;
const SUPABASE_URL = "https://ixntxgqaggkaaekewazu.supabase.co";
const SUPABASE_ANON_KEY = "sb_publishable_7SZ_z5FKbA77vZ04rnJKGQ_zXssCIT0";
const supabase = window.supabase.createClient(SUPABASE_URL, SUPABASE_ANON_KEY);
function App() {
const [messages, setMessages] = useState([
{ sender: "bot", text: "Hello! I am Tina, your HealthyLifePhil AI assistant. Ask me about products, sales, inventory, or business data!" }
]);
const [input, setInput] = useState("");
const [loading, setLoading] = useState(false);
const [status, setStatus] = useState("Ready");
const pipelinesRef = useRef({
sentiment: null,
summary: null,
generate: null
});
const getPipeline = async (task, model) => {
if (!window.hfPipeline) {
throw new Error("AI Library is still initializing. Please wait 3 seconds...");
}
return await window.hfPipeline(task, model);
};
const formatSummaryText = (products, orders, rawSummary) => {
const totalProducts = products ? products.length : 0;
const totalOrders = orders ? orders.length : 0;
let formatted = `πŸ“Š **BUSINESS ANALYTICS SUMMARY**\n`;
formatted += `───────────────────────────\n`;
formatted += `β€’ **Catalog Items:** ${totalProducts} products indexed\n`;
formatted += `β€’ **Transaction Count:** ${totalOrders} order records\n\n`;
formatted += `πŸ“‹ **Key Takeaways & Insights:**\n`;
const sentences = rawSummary.split('.').map(s => s.trim()).filter(s => s.length > 5);
sentences.forEach(sentence => {
formatted += `β€’ ${sentence}.\n`;
});
return formatted;
};
const handleSend = async () => {
if (!input.trim() || loading) return;
const userQuery = input.trim();
const updatedHistory = [...messages, { sender: "user", text: userQuery }];
setMessages(updatedHistory);
setInput("");
setLoading(true);
try {
// 1. GUARDRAIL CHECK (Sentiment + Security Patterns)
setStatus("Running Guardrails Check...");
const maliciousPattern = /(scam|hack|exploit|drop\s+table|delete\s+from|insert\s+into|alter\s+table|<script>|bypass|override|crack)/i;
if (maliciousPattern.test(userQuery)) {
setMessages(prev => [...prev, {
sender: "bot",
text: "πŸ›‘οΈ [Guardrail Triggered]: Request blocked due to security or policy restrictions. Please ask a valid business question."
}]);
setLoading(false);
setStatus("Ready");
return;
}
if (!pipelinesRef.current.sentiment) {
pipelinesRef.current.sentiment = await getPipeline('sentiment-analysis', 'Xenova/distilbert-base-uncased-finetuned-sst-2-english');
}
const sentimentResult = await pipelinesRef.current.sentiment(userQuery);
const isNegative = sentimentResult[0].label === 'NEGATIVE' && sentimentResult[0].score > 0.85;
if (isNegative && /(hate|stupid|bad|useless|dumb|garbage)/i.test(userQuery)) {
setMessages(prev => [...prev, {
sender: "bot",
text: "πŸ›‘οΈ [Guardrail Triggered]: Please keep queries professional and constructive."
}]);
setLoading(false);
setStatus("Ready");
return;
}
// 2. SUPABASE DATA QUERY & SUMMARIZATION
const isBusinessQuery = /(sales|product|inventory|order|business|store|item|stock)/i.test(userQuery);
if (isBusinessQuery) {
setStatus("Fetching Data & Formatting Summary...");
const { data: products } = await supabase.from('products').select('*');
const { data: orders } = await supabase.from('orders').select('*');
const rawDataString = `
Database State:
Products In Stock: ${JSON.stringify(products || [])}
Orders History: ${JSON.stringify(orders || [])}
`;
if (!pipelinesRef.current.summary) {
pipelinesRef.current.summary = await getPipeline('summarization', 'Xenova/distilbart-cnn-6-6');
}
const summaryOutput = await pipelinesRef.current.summary(rawDataString, {
max_new_tokens: 120,
min_new_tokens: 30
});
const cleanFormattedSummary = formatSummaryText(products, orders, summaryOutput[0].summary_text);
const finalBotResponse = `Hello! I retrieved the latest database records for HealthyLifePhil:\n\n${cleanFormattedSummary}`;
setMessages(prev => [...prev, {
sender: "bot",
text: finalBotResponse
}]);
} else {
// 3. CONVERSATIONAL TEXT GENERATION (Using Open Browser Model: LaMini-Flan-T5-77M)
setStatus("Generating Conversational Response...");
if (!pipelinesRef.current.generate) {
pipelinesRef.current.generate = await getPipeline('text2text-generation', 'Xenova/LaMini-Flan-T5-77M');
}
const prompt = `Answer politely as Tina, an AI assistant for HealthyLifePhil: ${userQuery}`;
const genOutput = await pipelinesRef.current.generate(prompt, {
max_new_tokens: 60,
temperature: 0.7
});
let cleanResponse = genOutput[0].generated_text.trim();
if (!cleanResponse || cleanResponse.length < 3) {
cleanResponse = "Hello! I am Tina, your HealthyLifePhil business assistant. Ask me about inventory, sales analytics, or order status!";
}
setMessages(prev => [...prev, {
sender: "bot",
text: cleanResponse
}]);
}
setStatus("Ready");
} catch (err) {
console.error(err);
setMessages(prev => [...prev, {
sender: "bot",
text: `⚠️ Error processing request: ${err.message}`
}]);
setStatus("Failed");
} finally {
setLoading(false);
}
};
return (
<div className="flex h-screen bg-slate-950 text-white">
<div className="w-64 bg-slate-900 p-4 border-r border-slate-800 flex flex-col justify-between hidden md:flex">
<div>
<h1 className="text-md font-bold text-white mb-1">HealthyLifePhil</h1>
<p className="text-xs text-emerald-400">AI Assistant Engine</p>
</div>
<div className="text-xs text-slate-500">Connected to Supabase DB</div>
</div>
<div className="flex-1 flex flex-col">
<header className="p-4 bg-slate-900 border-b border-slate-800 flex justify-between items-center text-sm font-semibold">
<span>Tina β€” Business Analysis Chatbot</span>
<span className="text-xs text-emerald-400">{status}</span>
</header>
<div className="flex-1 p-6 overflow-y-auto space-y-4">
{messages.map((m, index) => (
<div key={index} className={`flex ${m.sender === 'user' ? 'justify-end' : 'justify-start'}`}>
<div className={`p-4 rounded-xl max-w-lg text-sm whitespace-pre-wrap ${
m.sender === 'user' ? 'bg-emerald-600 text-white' : 'bg-slate-800 text-slate-200 border border-slate-700'
}`}>
{m.text}
</div>
</div>
))}
{loading && <div className="text-xs text-emerald-400 italic animate-pulse">Tina is processing request...</div>}
</div>
<div className="p-4 bg-slate-900 border-t border-slate-800 flex gap-2">
<input
type="text"
className="flex-1 p-3 rounded-lg bg-slate-800 border border-slate-700 text-white text-sm focus:outline-none focus:border-emerald-500"
placeholder="Ask about sales, products, inventory, or chat naturally..."
value={input}
onChange={(e) => setInput(e.target.value)}
onKeyDown={(e) => e.key === 'Enter' && handleSend()}
/>
<button
onClick={handleSend}
disabled={loading}
className="bg-emerald-600 hover:bg-emerald-500 px-5 py-2 rounded-lg font-bold text-sm text-black transition-colors disabled:opacity-50"
>
Send
</button>
</div>
</div>
</div>
);
}
const rootElement = document.getElementById('root');
const root = ReactDOM.createRoot(rootElement);
root.render(<App />);
</script>
</body>
</html>