# Project export: KissanAi

This document was generated by HackStack to give an AI agent context about a hackathon project. Sections are labeled with their provenance; content marked as truncated was cut to keep this document small.

## Project metadata

- Hackathon: OpenAI Build Week
- Tagline: An AI-powered agricultural intelligence platform helping farmers optimize crop selection, profitability, irrigation, and weather-aware decision making.
- Devpost: https://devpost.com/software/kissanai
- GitHub: https://github.com/msami-ullah-ai/KissanAi
- Video: https://www.youtube.com/embed/l0Y3D29oSMc?enablejsapi=1&hl=en_US&rel=0&start=&version=3&wmode=transparent
- Team: 0 GitHub contributor(s) — 

## Devpost submission (written by the team)

### Inspiration

Agriculture is the backbone of Pakistan's economy, yet many farmers still rely on intuition or fragmented information when making critical decisions about crop selection, irrigation, and resource allocation. We wanted to explore how AI could simplify these decisions by combining weather intelligence, profitability analysis, and optimization into a single platform. KissanAI was built to demonstrate how modern AI can empower farmers with data-driven insights that improve productivity while reducing risk.

### What it does

KissanAI is an AI-powered agricultural intelligence platform that helps farmers make informed farming decisions. It recommends suitable crops based on environmental conditions, forecasts expected profitability, analyzes weather-related risks, provides irrigation recommendations, and optimizes land allocation for maximum returns. The platform presents these insights through an interactive dashboard with easy-to-understand visualizations and exportable reports.

### How we built it

We built the frontend using React, TypeScript, Vite, Tailwind CSS, Recharts, and Framer Motion to create a modern and responsive user experience. The backend is powered by FastAPI, PostgreSQL, SQLAlchemy, Alembic, and Pydantic, providing a scalable REST API architecture. AI-driven analytics workflows combine weather information, crop suitability analysis, profitability estimation, and optimization logic to generate practical recommendations for farmers.

### Challenges we ran into

The biggest challenge was designing a recommendation system that balances multiple agricultural factors simultaneously. Crop suitability, weather conditions, irrigation requirements, and profitability often influence one another, making it difficult to produce recommendations that are both accurate and practical. Another challenge was presenting complex agricultural analytics in a way that remains simple and intuitive for end users.

### Accomplishments we're proud of

We're proud of building an end-to-end AI-powered platform that brings together multiple agricultural intelligence capabilities into a unified system. Instead of solving a single problem, KissanAI provides comprehensive decision support through crop recommendations, profitability forecasting, weather analysis, irrigation intelligence, land allocation optimization, and interactive analytics within one application.

### What we learned

Building KissanAI strengthened our understanding of full-stack AI application development, scalable API design with FastAPI, database modeling using PostgreSQL, and creating intuitive data visualizations with React. More importantly, we learned that effective AI solutions are not just about predictions—they must deliver actionable insights that users can easily understand and trust.

### What's next

for KissanAI Our roadmap includes satellite imagery integration, machine learning-based yield forecasting, GIS-enabled farm visualization, multilingual support for regional farmers, AI-powered seasonal forecasting, market price prediction, and a mobile application. We also plan to incorporate explainable AI techniques so farmers can better understand the reasoning behind every recommendation.

## README (from the GitHub repository)

# KissanAI 🌾

AI-powered agricultural intelligence platform for Punjab farmers featuring crop recommendation, profitability forecasting, weather-risk analysis, irrigation intelligence, and smart land allocation optimization.

Built using React, FastAPI, PostgreSQL, and AI-driven analytics workflows.

---

## Features

* AI crop recommendation engine
* Weather-aware agricultural analysis
* Profitability prediction
* Irrigation intelligence
* Smart land allocation optimization
* Interactive analytics dashboard
* Real-time weather integration
* Recommendation risk analysis
* Exportable reports

---

## Tech Stack

### Frontend

* React
* TypeScript
* Vite
* TailwindCSS
* Recharts
* Framer Motion

### Backend

* FastAPI
* PostgreSQL
* SQLAlchemy
* Alembic
* Pydantic

---

## Project Structure

```bash
KissanAi/
├── backend/
├── frontend/
├── docs/
└── README.md
```

---

## Setup Instructions

### Backend

```bash
cd backend
pip install -r requirements.txt
python -m alembic upgrade head
python scripts/seed_data.py
python -m uvicorn app.main:app --reload
```

### Frontend

```bash
cd frontend
npm install
npm run dev
```

---

## API Endpoints

| Method | Endpoint                        |
| ------ | ------------------------------- |
| POST   | `/api/recommendations/generate` |
| GET    | `/api/weather/{district}`       |
| GET    | `/api/health`                   |

---

## Future Roadmap

* Satellite imagery integration
* Machine learning yield forecasting
* Multilingual farmer assistant
* Mobile application
* Historical trend analysis
* AI-powered seasonal forecasting

---

## License

MIT License


## Detected evidence (automated analysis)

Indexed codebase: 112 recognized source files, 292 KB.
- CSS (language) — detected in the code
- FastAPI (technology) — detected in the code
- HTML (language) — detected in the code
- JavaScript (language) — detected in the code
- Python (language) — detected in the code
- React (technology) — detected in the code
- Tailwind CSS (technology) — detected in the code
- TypeScript (language) — detected in the code
- OpenAI (technology) — claimed on Devpost, not found in the code

## Codebase structure (from repository index)

### Files (120 of 122)

```
.gitignore
backend/.env.example
backend/alembic.ini
backend/alembic/env.py
backend/alembic/script.py.mako
backend/alembic/versions/__init__.py
backend/alembic/versions/0001_initial.py
backend/app/__init__.py
backend/app/config.py
backend/app/constants.py
backend/app/core/logging.py
backend/app/core/timing.py
backend/app/database/__init__.py
backend/app/database/base.py
backend/app/database/session.py
backend/app/main.py
backend/app/ml/__init__.py
backend/app/ml/predictor.py
backend/app/ml/risk_analysis.py
backend/app/models/__init__.py
backend/app/models/crop.py
backend/app/models/enums.py
backend/app/models/farm.py
backend/app/models/health.py
backend/app/models/irrigation_alert.py
backend/app/models/land_allocation.py
backend/app/models/profit_analysis.py
backend/app/models/recommendation.py
backend/app/models/user.py
backend/app/models/weather_data.py
backend/app/routes/__init__.py
backend/app/routes/crop.py
backend/app/routes/health.py
backend/app/routes/recommendation.py
backend/app/routes/weather.py
backend/app/schemas/__init__.py
backend/app/schemas/api.py
backend/app/schemas/crop.py
backend/app/schemas/health.py
backend/app/schemas/recommendation.py
backend/app/schemas/weather.py
backend/app/services/__init__.py
backend/app/services/health_service.py
backend/app/services/recommendation_service.py
backend/app/services/weather_service.py
backend/app/utils/__init__.py
backend/app/utils/confidence.py
backend/app/utils/cors.py
backend/app/utils/env.py
backend/app/utils/explanation_engine.py
backend/app/utils/scoring.py
backend/diagnose_backend.py
backend/README.md
backend/requirements.txt
backend/scripts/seed_data.py
frontend/.env.example
frontend/.gitignore
frontend/index.html
frontend/package.json
frontend/postcss.config.js
frontend/src/App.tsx
frontend/src/components/AIChatAssistant.tsx
frontend/src/components/AIConfidenceCard.tsx
frontend/src/components/CropRecommendationCard.tsx
frontend/src/components/dashboard/AlertsFeed.tsx
frontend/src/components/dashboard/AllocationCommandChart.tsx
frontend/src/components/dashboard/CommandPalette.tsx
frontend/src/components/dashboard/RecommendationDrawer.tsx
frontend/src/components/dashboard/RecommendationGrid.tsx
frontend/src/components/dashboard/RecommendationIntelligencePanel.tsx
frontend/src/components/dashboard/TopCommandBar.tsx
frontend/src/components/dashboard/WeatherIntelligencePanel.tsx
frontend/src/components/DashboardHero.tsx
frontend/src/components/DashboardStatCard.tsx
frontend/src/components/DistrictMap.tsx
frontend/src/components/EmptyState.tsx
frontend/src/components/ExplanationPanel.tsx
frontend/src/components/Footer.tsx
frontend/src/components/LandAllocationChart.tsx
frontend/src/components/Navbar.tsx
frontend/src/components/ProfitabilitySummary.tsx
frontend/src/components/ProtectedRoute.tsx
frontend/src/components/RecommendationForm.tsx
frontend/src/components/RecommendationLoader.tsx
frontend/src/components/RiskIndicator.tsx
frontend/src/components/Sidebar.tsx
frontend/src/components/SystemStatusPanel.tsx
frontend/src/components/ToastProvider.tsx
frontend/src/components/WeatherAlertCard.tsx
frontend/src/components/WeatherPanel.tsx
frontend/src/context/AuthContext.tsx
frontend/src/context/HistoryContext.tsx
frontend/src/context/RecommendationContext.tsx
frontend/src/data/landingData.tsx
frontend/src/hooks/useRecommendation.ts
frontend/src/hooks/useToast.ts
frontend/src/hooks/useWeather.ts
frontend/src/layouts/MainLayout.tsx
frontend/src/main.tsx
frontend/src/pages/AnalyticsPage.tsx
frontend/src/pages/DashboardPage.tsx
frontend/src/pages/HistoryPage.tsx
frontend/src/pages/LandingPage.tsx
frontend/src/pages/LoginPage.tsx
frontend/src/pages/RecommendationPage.tsx
frontend/src/pages/RegisterPage.tsx
frontend/src/pages/SettingsPage.tsx
frontend/src/services/api.ts
frontend/src/services/historyService.ts
frontend/src/services/mockRecommendation.ts
frontend/src/services/recommendation.ts
frontend/src/styles/index.css
frontend/src/types/platform.ts
frontend/src/types/recommendation.ts
frontend/src/utils/demoData.ts
frontend/src/utils/pdfExport.ts
frontend/src/vite-env.d.ts
frontend/tailwind.config.js
frontend/tsconfig.json
frontend/tsconfig.node.json
[2 more files omitted for size]
```

### Dependencies

- backend/requirements.txt: alembic@>=1.11.0, fastapi@>=0.110.0, httpx@>=0.27.0, pandas@>=2.0.0, psycopg2-binary@>=2.9.0, pydantic@>=2.0.0, pydantic-settings@>=2.0.0, python-dotenv@>=1.0.0, requests@>=2.31.0, scikit-learn@>=1.3.0, sqlalchemy@>=2.0.0, uvicorn@>=0.26.0
- frontend/package.json: @types/node@^20.14.0, @types/react@^18.3.3, @types/react-dom@^18.3.0, @types/react-router-dom@^5.3.3, @vitejs/plugin-react@^4.3.1, autoprefixer@^10.4.19, axios@^1.5.0, framer-motion@^11.2.0, html2canvas@^1.4.1, jspdf@^2.5.1, lucide-react@^0.523.0, postcss@^8.4.40, react@^18.3.1, react-dom@^18.3.1, react-router-dom@^6.16.0, recharts@^2.9.0, tailwindcss@^3.4.4, typescript@^5.5.4, vite@^5.4.1

### Recent commits (newest first)

- Initial release of KissanAI platform
- Add score breakdown and weather analytics; UI and types sync

## Key source files (fetched from GitHub, selected and truncated for size)

### backend/requirements.txt

```
fastapi>=0.110.0
uvicorn>=0.26.0
python-dotenv>=1.0.0
sqlalchemy>=2.0.0
psycopg2-binary>=2.9.0
requests>=2.31.0
pydantic>=2.0.0
pydantic-settings>=2.0.0
scikit-learn>=1.3.0
pandas>=2.0.0
alembic>=1.11.0
httpx>=0.27.0

```

### frontend/package.json

```
{
  "name": "kissanai-frontend",
  "private": true,
  "version": "0.1.0",
  "type": "module",
  "scripts": {
    "dev": "vite",
    "build": "tsc && vite build",
    "preview": "vite preview"
  },
  "dependencies": {
    "axios": "^1.5.0",
    "framer-motion": "^11.2.0",
    "html2canvas": "^1.4.1",
    "jspdf": "^2.5.1",
    "lucide-react": "^0.523.0",
    "react": "^18.3.1",
    "react-dom": "^18.3.1",
    "react-router-dom": "^6.16.0",
    "recharts": "^2.9.0"
  },
  "devDependencies": {
    "@types/node": "^20.14.0",
    "@types/react": "^18.3.3",
    "@types/react-dom": "^18.3.0",
    "@types/react-router-dom": "^5.3.3",
    "autoprefixer": "^10.4.19",
    "postcss": "^8.4.40",
    "tailwindcss": "^3.4.4",
    "typescript": "^5.5.4",
    "vite": "^5.4.1",
    "@vitejs/plugin-react": "^4.3.1"
  }
}
```

### frontend/src/main.tsx

```typescript
import React from 'react';
import ReactDOM from 'react-dom/client';
import { BrowserRouter } from 'react-router-dom';
import App from './App';
import './styles/index.css';

ReactDOM.createRoot(document.getElementById('root') as HTMLElement).render(
  <React.StrictMode>
    <BrowserRouter>
      <App />
    </BrowserRouter>
  </React.StrictMode>,
);

```

### frontend/src/App.tsx

```typescript
import { Route, Routes, Navigate } from 'react-router-dom';
import LandingPage from './pages/LandingPage';
import DashboardPage from './pages/DashboardPage';
import RecommendationPage from './pages/RecommendationPage';
import AnalyticsPage from './pages/AnalyticsPage';
import HistoryPage from './pages/HistoryPage';
import SettingsPage from './pages/SettingsPage';
import LoginPage from './pages/LoginPage';
import RegisterPage from './pages/RegisterPage';
import MainLayout from './layouts/MainLayout';
import RecommendationProvider from './context/RecommendationContext';
import HistoryProvider from './context/HistoryContext';
import AuthProvider from './context/AuthContext';
import ToastProvider from './components/ToastProvider';
import ProtectedRoute from './components/ProtectedRoute';

function App() {
  return (
    <ToastProvider>
      <AuthProvider>
        <HistoryProvider>
          <RecommendationProvider>
            <MainLayout>
              <Routes>
                <Route path="/" element={<LandingPage />} />
                <Route path="/login" element={<LoginPage />} />
                <Route path="/register" element={<RegisterPage />} />
                <Route path="/dashboard" element={<ProtectedRoute><DashboardPage /></ProtectedRoute>} />
                <Route path="/recommendation" element={<ProtectedRoute><RecommendationPage /></ProtectedRoute>} />
                <Route path="/analytics" element={<ProtectedRoute><AnalyticsPage /></ProtectedRoute>} />
                <Route path="/history" element={<ProtectedRoute><HistoryPage /></ProtectedRoute>} />
                <Route path="/settings" element={<ProtectedRoute><SettingsPage /></ProtectedRoute>} />
                <Route path="*" element={<Navigate to="/" replace />} />
              </Routes>
            </MainLayout>
          </RecommendationProvider>
        </HistoryProvider>
      </AuthProvider>
    </ToastProvider>
  );
}

export default App;

```

### backend/app/main.py

```python
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from sqlalchemy import inspect, text

from .config import AppConfig
from .core.logging import get_logger, setup_logging
from .core.timing import RequestTimingMiddleware
from .database.session import engine
from .routes.crop import router as crop_router
from .routes.health import router as health_router
from .routes.recommendation import router as recommendation_router
from .routes.weather import router as weather_router
from .services.weather_service import WeatherClient

config = AppConfig()
setup_logging(config.log_level)
logger = get_logger("kissanai.startup")


OPENAPI_TAGS = [
    {
        "name": "Health",
        "description": "Operational health checks for the KissanAI backend.",
    },
    {
        "name": "Weather",
        "description": "OpenWeather-backed district weather intelligence.",
    },
    {
        "name": "Recommendations",
        "description": "Single crop recommendation engine and farm decision intelligence.",
    },
    {
        "name": "Deprecated",
        "description": "Retired compatibility endpoints with replacement guidance.",
    },
]


def create_app() -> FastAPI:
    app = FastAPI(
        title="KissanAI Backend",
        version="0.1.0",
        description="FastAPI service for weather-aware crop recommendation intelligence.",
        openapi_tags=OPENAPI_TAGS,
    )
    cors_origins = [origin.strip() for origin in config.cors_origins.split(",") if origin.strip()]
    allow_credentials = "*" not in cors_origins
    
    app.add_middleware(
        RequestTimingMiddleware,
    )
    app.add_middleware(
        CORSMiddleware,
        allow_origins=cors_origins,
        allow_credentials=allow_credentials,
        allow_methods=["*"],
        allow_headers=["*"],
    )
    
    app.include_router(health_router, prefix="/api")
    app.include_router(crop_router, prefix="/api")
    app.include_router(recommendation_router, prefix="/api")
    app.include_router(weather_router, prefix="/api")

    @app.on_event("startup")
    async def startup_checks() -> None:
        logger.info("startup.begin")
        try:
            with engine.connect() as connection:
                connection.execute(text("SELECT 1"))
                existing_tables = set(inspect(connection).get_table_names())
            logger.info("startup.database.connected")
            required_tables = {"users", "farms", "crops", "recommendations"}
            missing_tables = sorted(required_tables - existing_tables)
            if missing_tables:
                logger.warning("startup.database.migrations_missing", extra={"missing_tables": missing_tables})
            else:
                logger.info("startup.database.migrations_verified")
        except Exception as error:
            import traceback
            traceback.print_exc()
            logger.warning("startup.database.unavailable", extra={"error": str(error)})

        try:
            WeatherClient.validate_service()
            logger.info("startup.weather.validated")
        except Exception as error:
            logger.warning("startup.weather.validation_failed", extra={"error": str(error)})

    return app


app = create_app()

```

### frontend/postcss.config.js

```javascript
export default {
  plugins: {
    tailwindcss: {},
    autoprefixer: {},
  },
};

```

### frontend/vite.config.ts

```typescript
import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';

export default defineConfig({
  plugins: [react()],
  server: {
    port: 4173,
    open: true,
  },
});

```

### frontend/index.html

```html
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>KissanAI</title>
    <meta
      name="description"
      content="KissanAI Punjab Agricultural Decision Intelligence System"
    />
  </head>
  <body class="bg-[#07170d] text-white">
    <div id="root"></div>
    <script type="module" src="/src/main.tsx"></script>
  </body>
</html>

```

### frontend/tailwind.config.js

```javascript
import type { Config } from 'tailwindcss';

export default {
  content: ['./index.html', './src/**/*.{ts,tsx}'],
  theme: {
    extend: {
      colors: {
        forest: '#0B3D24',
        mint: '#A8F0C6',
        olive: '#6B8E23',
        meadow: '#1E5D3E',
        pine: '#0A2A18',
      },
      boxShadow: {
        glow: '0 20px 70px rgba(10, 73, 39, 0.25)',
      },
      backgroundImage: {
        'hero-gradient': 'radial-gradient(circle at top left, rgba(168,240,198,0.25), transparent 35%), linear-gradient(180deg, rgba(16,38,18,0.95), rgba(5,15,8,0.95))',
      },
    },
  },
  plugins: [],
} satisfies Config;

```

### backend/diagnose_backend.py

```python
#!/usr/bin/env python3
"""Diagnostic script for KissanAI backend wiring.
Run: python diagnose_backend.py
"""
import sys
import traceback
from importlib import import_module

from sqlalchemy import text

MODULES = [
    "app.main",
    "app.routes.crop",
    "app.routes.health",
    "app.services.crop_service",
    "app.services.health_service",
    "app.database",
    "app.database.session",
    "app.models.crop",
    "app.models.farm",
    "app.schemas.crop",
]

success = True

print("\n== Import checks ==")
for mod in MODULES:
    try:
        import_module(mod)
        print(f"OK: imported {mod}")
    except Exception as e:
        success = False
        print(f"ERROR importing {mod}: {e}")
        traceback.print_exc()

print("\n== Database connection check ==")
try:
    from app.database import engine
    with engine.connect() as conn:
        conn.execute(text("SELECT 1"))
    print("OK: database connection established (SELECT 1)")
except Exception as e:
    success = False
    print(f"ERROR: database connection failed: {e}")
    traceback.print_exc()

print("\n== FastAPI route registration check ==")
try:
    from app.main import app
    # List registered routes
    paths = []
    for r in app.routes:
        path = getattr(r, "path", None)
        if path:
            paths.append((path, getattr(r, "methods", None)))
    print(f"Found {len(paths)} routes registered on app")
    for p, m in paths:
        print(f" - {p}  methods={m}")
    endpoint_present = any(
        p == "/api/crops/recommend" or p.endswith("/crops/recommend") or "/crops/recommend" in p
        for p, _ in paths
    )
    print("/crops/recommend registered:", endpoint_present)
    if not endpoint_present:
        success = False
except Exception as e:
    success = False
    print(f"ERROR checking FastAPI routes: {e}")
    traceback.print_exc()

print("\n== Summary ==")
if success:
    print("ALL CHECKS PASSED")
    sys.exit(0)
else:
    print("SOME CHECKS FAILED - see above for tracebacks")
    sys.exit(2)

```

[99 more indexed source files omitted to keep this export small. The full file list is in the Codebase structure section above.]