Spaces:
Runtime error

flora / src /components /AddPlantDialog.tsx
Pavankumardns's picture
hugging face
ae02946
Raw History Blame Contribute Delete
11.6 kB
import { useState, useRef } from "react";
import { Button } from "@/components/ui/button";
import {
Dialog,
DialogContent,
DialogDescription,
DialogHeader,
DialogTitle,
DialogTrigger,
} from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/components/ui/select";
import { useToast } from "@/hooks/use-toast";
import { useUser } from "@clerk/clerk-react";
import { Leaf, Loader2, Upload, Camera } from "lucide-react";
interface AddPlantDialogProps {
onPlantAdded: () => void;
}
const AddPlantDialog = ({ onPlantAdded }: AddPlantDialogProps) => {
const { user } = useUser();
const { toast } = useToast();
const fileInputRef = useRef<HTMLInputElement>(null);
const [open, setOpen] = useState(false);
const [isSubmitting, setIsSubmitting] = useState(false);
const [isAnalyzing, setIsAnalyzing] = useState(false);
const [selectedImage, setSelectedImage] = useState<string | null>(null);
const [detectedHealth, setDetectedHealth] = useState<any>(null);
const [formData, setFormData] = useState({
name: "",
type: "",
location: "Garden",
health: "healthy",
});
const plantTypes = [
"Tomato", "Rose", "Orchid", "Herb", "Vegetable", "Fruit Tree",
"Flower", "Succulent", "Fern", "Palm", "Cactus", "Other"
];
const handleImageSelect = async (e: React.ChangeEvent<HTMLInputElement>) => {
const file = e.target.files?.[0];
if (!file) return;
if (file.size > 16 * 1024 * 1024) {
toast({
title: "File too large",
description: "Please select an image smaller than 16MB",
variant: "destructive",
});
return;
}
const reader = new FileReader();
reader.onload = async (event) => {
const imageData = event.target?.result as string;
setSelectedImage(imageData);
// Automatically analyze the plant
await analyzePlantHealth(imageData);
};
reader.readAsDataURL(file);
};
const analyzePlantHealth = async (imageData: string) => {
setIsAnalyzing(true);
try {
const formData = new FormData();
formData.append("image_data", imageData);
formData.append("model_type", "plant");
const response = await fetch("http://localhost:5000/predict", {
method: "POST",
body: formData,
});
const data = await response.json();
if (response.ok && !data.error) {
setDetectedHealth(data);
// Auto-fill form with detected data
setFormData(prev => ({
...prev,
type: data.plant,
name: prev.name || `${data.plant} Plant`,
health: data.disease.toLowerCase().includes("healthy") ? "healthy" : "diseased",
}));
toast({
title: "Plant Analyzed",
description: `Detected: ${data.plant} - ${data.disease}`,
});
}
} catch (error) {
toast({
title: "Analysis Failed",
description: "Could not analyze plant. You can still add it manually.",
variant: "destructive",
});
} finally {
setIsAnalyzing(false);
}
};
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
if (!user?.id) {
toast({
title: "Error",
description: "You must be logged in to add plants",
variant: "destructive",
});
return;
}
if (!formData.name || !formData.type) {
toast({
title: "Error",
description: "Please fill in all required fields",
variant: "destructive",
});
return;
}
if (!selectedImage) {
toast({
title: "Error",
description: "Please upload a plant image",
variant: "destructive",
});
return;
}
setIsSubmitting(true);
try {
const response = await fetch("http://localhost:5000/plants", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
userId: user.id,
name: formData.name,
type: formData.type,
location: formData.location,
health: formData.health,
disease: detectedHealth?.disease || (formData.health === "healthy" ? "healthy" : null),
confidence: detectedHealth?.confidence,
imageUrl: selectedImage,
addedDate: new Date().toISOString(),
nextWatering: new Date(Date.now() + 24 * 60 * 60 * 1000).toISOString(), // Tomorrow
}),
});
if (response.ok) {
toast({
title: "Success",
description: `${formData.name} added to your garden!`,
});
setFormData({
name: "",
type: "",
location: "Garden",
health: "healthy",
});
setSelectedImage(null);
setDetectedHealth(null);
setOpen(false);
onPlantAdded();
} else {
throw new Error("Failed to add plant");
}
} catch (error) {
toast({
title: "Error",
description: "Failed to add plant. Please try again.",
variant: "destructive",
});
} finally {
setIsSubmitting(false);
}
};
return (
<Dialog open={open} onOpenChange={setOpen}>
<DialogTrigger asChild>
<Button variant="hero-outline" className="w-full justify-start" size="sm">
<Leaf className="w-4 h-4" />
Add New Plant
</Button>
</DialogTrigger>
<DialogContent className="sm:max-w-[425px]">
<DialogHeader>
<DialogTitle>Add New Plant</DialogTitle>
<DialogDescription>
Add a plant to your garden manually. Fill in the details below.
</DialogDescription>
</DialogHeader>
<form onSubmit={handleSubmit} className="space-y-4 mt-4">
{/* Image Upload */}
<div className="space-y-2">
<Label>Plant Image *</Label>
{!selectedImage ? (
<div
onClick={() => fileInputRef.current?.click()}
className="border-2 border-dashed border-border rounded-lg p-8 text-center cursor-pointer hover:border-flora-green hover:bg-secondary/50 transition-all"
>
<Upload className="w-8 h-8 mx-auto mb-2 text-muted-foreground" />
<p className="text-sm font-medium mb-1">Click to upload plant image</p>
<p className="text-xs text-muted-foreground">
AI will analyze plant health automatically
</p>
</div>
) : (
<div className="space-y-2">
<div className="relative rounded-lg overflow-hidden border border-border">
<img
src={selectedImage}
alt="Selected plant"
className="w-full h-48 object-cover"
/>
{isAnalyzing && (
<div className="absolute inset-0 bg-black/50 flex items-center justify-center">
<Loader2 className="w-8 h-8 animate-spin text-white" />
</div>
)}
</div>
{detectedHealth && (
<div className="p-3 rounded-lg bg-flora-green/10 border border-flora-green/20">
<p className="text-sm font-medium text-flora-green">
✓ Detected: {detectedHealth.plant} - {detectedHealth.disease}
</p>
<p className="text-xs text-muted-foreground mt-1">
Confidence: {detectedHealth.confidence}
</p>
</div>
)}
<Button
type="button"
variant="outline"
size="sm"
onClick={() => {
setSelectedImage(null);
setDetectedHealth(null);
}}
className="w-full"
>
Change Image
</Button>
</div>
)}
<input
ref={fileInputRef}
type="file"
accept="image/*"
onChange={handleImageSelect}
className="hidden"
/>
</div>
<div className="space-y-2">
<Label htmlFor="name">Plant Name *</Label>
<Input
id="name"
placeholder="e.g., My Tomato Plant"
value={formData.name}
onChange={(e) => setFormData({ ...formData, name: e.target.value })}
required
/>
</div>
<div className="space-y-2">
<Label htmlFor="type">Plant Type *</Label>
<Select
value={formData.type}
onValueChange={(value) => setFormData({ ...formData, type: value })}
required
>
<SelectTrigger>
<SelectValue placeholder="Select plant type" />
</SelectTrigger>
<SelectContent>
{plantTypes.map((type) => (
<SelectItem key={type} value={type}>
{type}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
<div className="space-y-2">
<Label htmlFor="location">Location</Label>
<Input
id="location"
placeholder="e.g., Garden, Balcony, Indoor"
value={formData.location}
onChange={(e) => setFormData({ ...formData, location: e.target.value })}
/>
</div>
<div className="space-y-2">
<Label htmlFor="health">Health Status</Label>
<Select
value={formData.health}
onValueChange={(value) => setFormData({ ...formData, health: value })}
disabled={!!detectedHealth}
>
<SelectTrigger>
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="healthy">Healthy</SelectItem>
<SelectItem value="needs_attention">Needs Attention</SelectItem>
<SelectItem value="diseased">Diseased</SelectItem>
</SelectContent>
</Select>
{detectedHealth && (
<p className="text-xs text-muted-foreground">
Auto-detected from image analysis
</p>
)}
</div>
<div className="flex gap-2 pt-4">
<Button
type="button"
variant="outline"
onClick={() => setOpen(false)}
className="flex-1"
disabled={isSubmitting}
>
Cancel
</Button>
<Button
type="submit"
variant="hero"
className="flex-1"
disabled={isSubmitting}
>
{isSubmitting ? (
<>
<Loader2 className="w-4 h-4 animate-spin" />
Adding...
</>
) : (
"Add Plant"
)}
</Button>
</div>
</form>
</DialogContent>
</Dialog>
);
};
export default AddPlantDialog;