Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 22 additions & 5 deletions netlify/functions/classify-crisis.cjs
Original file line number Diff line number Diff line change
Expand Up @@ -69,25 +69,42 @@ Post to analyze:
${textToAnalyze}
"""

Respond with ONLY one word: LOW, MEDIUM, or HIGH. No explanation, no punctuation, nothing else.`;
Respond ONLY with a raw JSON object formatted exactly like this, with no markdown formatting or code blocks:
{
"riskLevel": "HIGH",
"reason": "Brief explanation of why this risk level was chosen"
}`;

const result = await model.generateContent(prompt);
const rawText = result?.response?.text()?.trim().toUpperCase() || 'LOW';
let rawText = result?.response?.text()?.trim() || '';

// Safely strip potential markdown code blocks
if (rawText.startsWith('```')) {
rawText = rawText.replace(/^```(json)?\n?/, '').replace(/\n?```$/, '').trim();
}

let parsedResult = { riskLevel: 'LOW', reason: '' };
try {
parsedResult = JSON.parse(rawText);
} catch (parseError) {
console.error('Failed to parse JSON from AI:', rawText);
}

const VALID_LEVELS = ['LOW', 'MEDIUM', 'HIGH'];
const riskLevel = VALID_LEVELS.includes(rawText) ? rawText : 'LOW';
const riskLevel = VALID_LEVELS.includes(parsedResult.riskLevel?.toUpperCase()) ? parsedResult.riskLevel.toUpperCase() : 'LOW';
const reason = parsedResult.reason || '';

return {
statusCode: 200,
headers: { ...corsHeaders, 'Content-Type': 'application/json' },
body: JSON.stringify({ riskLevel }),
body: JSON.stringify({ riskLevel, reason }),
};
} catch (error) {
console.error('Crisis classification error:', error);
return {
statusCode: 500,
headers: { ...corsHeaders, 'Content-Type': 'application/json' },
body: JSON.stringify({ error: 'Classification failed', riskLevel: 'LOW' }),
body: JSON.stringify({ error: 'Classification failed', riskLevel: 'LOW', reason: '' }),
};
}
};
73 changes: 73 additions & 0 deletions src/components/EmergencyModal.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
import React from 'react';
import { X, AlertTriangle } from 'lucide-react';
import { QUICK_HELPLINES } from '../utils/constants';

interface EmergencyModalProps {
isOpen: boolean;
onClose: () => void;
}

export function EmergencyModal({ isOpen, onClose }: EmergencyModalProps) {
if (!isOpen) return null;

return (
<div className="fixed inset-0 z-50 flex items-center justify-center p-4 sm:p-6 bg-black/60 backdrop-blur-sm animate-fade-in">
<div className="bg-white dark:bg-gray-900 rounded-2xl shadow-2xl w-full max-w-2xl max-h-[90vh] overflow-hidden flex flex-col relative animate-scale-up border-t-8 border-red-600 dark:border-red-500">

{/* Header */}
<div className="flex items-center justify-between p-5 border-b border-gray-100 dark:border-gray-800 bg-red-50 dark:bg-red-950/20">
<div className="flex items-center gap-3 text-red-600 dark:text-red-500">
<AlertTriangle className="h-7 w-7" />
<h2 className="text-xl sm:text-2xl font-bold">Immediate Support Needed?</h2>
</div>
<button
onClick={onClose}
className="p-2 rounded-full hover:bg-red-100 dark:hover:bg-red-900/50 text-gray-500 dark:text-gray-400 transition-colors focus:outline-none focus:ring-2 focus:ring-red-500"
aria-label="Close modal"
>
<X className="h-6 w-6" />
</button>
</div>

{/* Body */}
<div className="p-5 sm:p-6 overflow-y-auto">
<p className="text-gray-700 dark:text-gray-300 text-base mb-6 font-medium leading-relaxed">
We noticed your story mentions signs of urgent distress. Your safety is our top priority. Please do not hesitate to reach out to these free, confidential, and 24/7 helplines right now.
</p>

<div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
{QUICK_HELPLINES.map((helpline, idx) => {
const Icon = helpline.icon;
return (
<a
key={idx}
href={`tel:${helpline.number.split(' / ')[0]}`}
className="flex items-start gap-4 p-4 rounded-xl border border-gray-200 dark:border-gray-700 hover:border-red-300 dark:hover:border-red-800 bg-gray-50 dark:bg-gray-800/50 hover:bg-red-50 dark:hover:bg-red-900/20 transition-all group"
>
<div className="p-2 rounded-lg bg-red-100 dark:bg-red-900/40 text-red-600 dark:text-red-400 group-hover:scale-110 transition-transform">
<Icon className="h-5 w-5" />
</div>
<div>
<h3 className="font-bold text-gray-900 dark:text-white text-sm">{helpline.title}</h3>
<p className="text-red-600 dark:text-red-400 font-extrabold text-lg tracking-wide my-0.5">{helpline.number}</p>
<p className="text-xs text-gray-500 dark:text-gray-400">{helpline.description}</p>
</div>
</a>
);
})}
</div>
</div>

{/* Footer */}
<div className="p-4 border-t border-gray-100 dark:border-gray-800 bg-gray-50 dark:bg-gray-800/50 flex justify-end">
<button
onClick={onClose}
className="px-6 py-2.5 bg-gray-200 dark:bg-gray-700 hover:bg-gray-300 dark:hover:bg-gray-600 text-gray-800 dark:text-gray-200 font-semibold rounded-lg transition-colors focus:outline-none focus:ring-2 focus:ring-gray-400"
>
I understand, close
</button>
</div>
</div>
</div>
);
}
61 changes: 7 additions & 54 deletions src/pages/Resources.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -113,56 +113,7 @@ const SAFETY_GUIDE: SafetySection[] = [
],
},
];
const QUICK_HELPLINES = [
{
icon: Phone,
title: "Women's Helpline",
number: "1091 / 181",
description: "24/7 support for women in distress",
},
{
icon: AlertTriangle,
title: "Emergency Response",
number: "112",
description: "National emergency assistance",
},
{
icon: Heart,
title: "Child Helpline",
number: "1098",
description: "Support for children in need",
},
{
icon: Globe,
title: "Cyber Crime Helpline",
number: "1930",
description: "Report cyber fraud, online harassment, and digital abuse",
},
{
icon: Heart,
title: "Ambulance Services",
number: "108",
description: "Emergency medical assistance",
},
{
icon: Shield,
title: "Police",
number: "100",
description: "Immediate law enforcement assistance",
},
{
icon: AlertTriangle,
title: "Fire Services",
number: "101",
description: "Fire and rescue emergency services",
},
{
icon: Heart,
title: "Kiran Mental Health Helpline",
number: "1800-599-0019",
description: "24/7 mental health and emotional support",
},
];
import { QUICK_HELPLINES } from "../utils/constants";
function Accordion({
title,
children,
Expand Down Expand Up @@ -512,10 +463,12 @@ export default function Resources() {
</section>

<section className="grid gap-8 md:grid-cols-2">
<div className="rounded-3xl bg-pink-900 p-8 text-white shadow-2xl">
<div className="mb-6 flex items-center gap-3 border-b border-pink-700 pb-3">
<Shield className="h-8 w-8 text-pink-300" />
<h2 className="text-2xl font-bold">Personal Safety Hub</h2>
<div className="rounded-3xl border border-pink-200 bg-pink-50 p-8 shadow-2xl dark:border-gray-700 dark:bg-gray-800">
<div className="mb-6 flex items-center gap-3 border-b border-pink-300 pb-3 dark:border-gray-700">
<Shield className="h-8 w-8 text-rose-600 dark:text-rose-400" />
<h2 className="text-2xl font-bold text-gray-900 dark:text-white">
Personal Safety Hub
</h2>
</div>

<div className="space-y-4">
Expand Down
37 changes: 30 additions & 7 deletions src/pages/ShareStory.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { useNavigate } from 'react-router-dom';
import { toast } from 'react-hot-toast';
import { auth } from '../lib/firebase';
import { Edit, Trash2, CheckSquare, Loader2, Sparkles } from 'lucide-react';
import { EmergencyModal } from '../components/EmergencyModal';
import { User } from 'firebase/auth';

// Firebase imports
Expand Down Expand Up @@ -104,6 +105,7 @@ function resolveMediaItem(entry: string | MediaItem): MediaItem {
}

export default function ShareStory() {
const [showEmergencyModal, setShowEmergencyModal] = useState(false);
const [title, setTitle] = useState('');
const [content, setContent] = useState('');
const [selectedTags, setSelectedTags] = useState<string[]>([]);
Expand Down Expand Up @@ -426,19 +428,25 @@ export default function ShareStory() {

try {
// Add a new document to Firestore
const riskLevel = await classifyPostRisk(title, storyText);
const classification = await classifyPostRisk(title, storyText);

await addDoc(collection(db, 'stories'), {
title,
content: storyText,
tags: selectedTags,
author_id: user.uid,
media_urls: mediaUrls,
risk_level: riskLevel,
risk_level: classification.riskLevel,
risk_reason: classification.reason,
classified_at: new Date().toISOString(),
created_at: serverTimestamp(),
});

toast.success('Your story has been shared successfully');
if (classification.riskLevel === 'HIGH') {
setShowEmergencyModal(true);
} else {
toast.success('Your story has been shared successfully');
}

// Fetch the updated stories list
fetchMyStories();
Expand Down Expand Up @@ -889,22 +897,37 @@ export default function ShareStory() {
</ul>
)}
</div>
<EmergencyModal
isOpen={showEmergencyModal}
onClose={() => {
setShowEmergencyModal(false);
toast.success('Your story has been shared successfully');
}}
/>
</div>
);
}

async function classifyPostRisk(title: string, content: string): Promise<string> {
interface CrisisClassification {
riskLevel: string;
reason: string;
}

async function classifyPostRisk(title: string, content: string): Promise<CrisisClassification> {
try {
const response = await fetch('/.netlify/functions/classify-crisis', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ title, content }),
});
if (!response.ok) return 'LOW';
if (!response.ok) return { riskLevel: 'LOW', reason: '' };
const data = await response.json();
return data.riskLevel || 'LOW';
return {
riskLevel: data.riskLevel || 'LOW',
reason: data.reason || ''
};
} catch {
return 'LOW';
return { riskLevel: 'LOW', reason: '' };
}
}

Expand Down
52 changes: 52 additions & 0 deletions src/utils/constants.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
import { Phone, AlertTriangle, Heart, Globe, Shield } from "lucide-react";

export const QUICK_HELPLINES = [
{
icon: Phone,
title: "Women's Helpline",
number: "1091 / 181",
description: "24/7 support for women in distress",
},
{
icon: AlertTriangle,
title: "Emergency Response",
number: "112",
description: "National emergency assistance",
},
{
icon: Heart,
title: "Child Helpline",
number: "1098",
description: "Support for children in need",
},
{
icon: Globe,
title: "Cyber Crime Helpline",
number: "1930",
description: "Report cyber fraud, online harassment, and digital abuse",
},
{
icon: Heart,
title: "Ambulance Services",
number: "108",
description: "Emergency medical assistance",
},
{
icon: Shield,
title: "Police",
number: "100",
description: "Immediate law enforcement assistance",
},
{
icon: AlertTriangle,
title: "Fire Services",
number: "101",
description: "Fire and rescue emergency services",
},
{
icon: Heart,
title: "Kiran Mental Health Helpline",
number: "1800-599-0019",
description: "24/7 mental health and emotional support",
},
];
Loading