Spaces:
Running
Running
| import { generateAIContent } from '../utils/aiHelper.js'; | |
| import { extractLanguage, getLanguageName } from '../utils/aiOrchestrator.js'; | |
| import dotenv from "dotenv"; | |
| export const soilHealthRecommendations = async (req, res) => { | |
| dotenv.config(); | |
| const { | |
| soilPH, | |
| organicMatter, | |
| nitrogen, | |
| phosphorus, | |
| potassium, | |
| salinity, | |
| cropType, | |
| } = req.body; | |
| if ( | |
| soilPH === undefined || | |
| organicMatter === undefined || | |
| nitrogen === undefined || | |
| phosphorus === undefined || | |
| potassium === undefined || | |
| salinity === undefined || | |
| !cropType | |
| ) { | |
| return res.status(400).json({ | |
| error: "Missing required inputs: soilPH, organicMatter, nitrogen, phosphorus, potassium, salinity, cropType", | |
| }); | |
| } | |
| const lang = extractLanguage(req); | |
| const langName = getLanguageName(lang); | |
| const langInstruction = lang !== 'en' ? `\n\nRespond STRICTLY in ${langName} language. Translate all fields and values.` : ''; | |
| try { | |
| const prompt = ` | |
| You are an expert soil scientist. | |
| Based on the soil data below: | |
| - pH: ${soilPH} | |
| - Organic Matter (%): ${organicMatter} | |
| - Nitrogen (N): ${nitrogen} | |
| - Phosphorus (P): ${phosphorus} | |
| - Potassium (K): ${potassium} | |
| - Salinity (EC): ${salinity} | |
| - Crop Type: ${cropType} | |
| Provide: | |
| 1. The main current soil issue (1 short line) | |
| 2. Recommended amendments (bullet list; include lime, gypsum, compost, manure, biofertilizer, etc. if relevant) | |
| 3. NPK balancing recommendation (for example: "increase nitrogen slightly", "reduce phosphorus", etc.) | |
| 4. Estimated time for improvement (e.g., "2–4 weeks", "1–2 months") | |
| 5. A short explanation | |
| ⚠️ Respond ONLY in valid JSON with this structure: | |
| { | |
| "current_issue": "", | |
| "recommended_amendments": ["", "", ""], | |
| "npk_adjustment": "", | |
| "expected_improvement_time": "", | |
| "note": "" | |
| }${langInstruction} | |
| `; | |
| const recommendation = await generateAIContent(prompt.trim()); | |
| const formattedRecommendation = recommendation.replace("```json", "").replace("```", "").trim(); | |
| res.status(200).json({ recommendation: formattedRecommendation }); | |
| } catch (err) { | |
| console.error("Error fetching recommendations: ", err); | |
| res.status(500).json({ error: "Failed to fetch recommendations" }); | |
| } | |
| }; | |