← back to invincible-jha__aumai-farmbrain

Function bodies 25 total

All specs Real LLM only Function bodies
main function · python · L12-L14 (3 LOC)
examples/quickstart.py
def main() -> None:
    """Entry point for the quickstart example."""
    print("aumai-farmbrain quickstart — replace this with real usage.")
SoilAnalysisRequest class · python · L22-L25 (4 LOC)
src/aumai_farmbrain/api.py
class SoilAnalysisRequest(BaseModel):
    """Request body for soil analysis endpoint."""

    soil: SoilProfile
SoilAnalysisResponse class · python · L28-L33 (6 LOC)
src/aumai_farmbrain/api.py
class SoilAnalysisResponse(BaseModel):
    """Response body for soil analysis endpoint."""

    recommendations: list[str]
    suitable_crop_names: list[str]
    disclaimer: str = AGRICULTURAL_DISCLAIMER
CropAdvisoryRequest class · python · L36-L41 (6 LOC)
src/aumai_farmbrain/api.py
class CropAdvisoryRequest(BaseModel):
    """Request body for crop advisory endpoint."""

    crop_name: str
    soil: SoilProfile
    weather: WeatherData | None = None
soil_analysis function · python · L45-L52 (8 LOC)
src/aumai_farmbrain/api.py
def soil_analysis(request: SoilAnalysisRequest) -> SoilAnalysisResponse:
    """Analyse a soil profile and return suitability recommendations."""
    recs = _soil_analyzer.analyze(request.soil)
    suitable = _soil_analyzer.suitable_crops(request.soil)
    return SoilAnalysisResponse(
        recommendations=recs,
        suitable_crop_names=[c.name for c in suitable],
    )
crop_advisory function · python · L56-L64 (9 LOC)
src/aumai_farmbrain/api.py
def crop_advisory(request: CropAdvisoryRequest) -> CropAdvisory:
    """Generate a full crop advisory for the specified crop and soil."""
    crop = _crop_db.by_name(request.crop_name)
    if crop is None:
        raise HTTPException(
            status_code=404,
            detail=f"Crop '{request.crop_name}' not found in database.",
        )
    return _crop_advisor.advise(crop, request.soil, request.weather)
list_crops function · python · L68-L78 (11 LOC)
src/aumai_farmbrain/api.py
def list_crops(season: str | None = None) -> dict[str, object]:
    """List all crops in the database, optionally filtered by season."""
    if season:
        crops = _crop_db.by_season(season)
    else:
        crops = _crop_db.all_crops()
    return {
        "crops": [c.model_dump() for c in crops],
        "total": len(crops),
        "disclaimer": AGRICULTURAL_DISCLAIMER,
    }
Powered by Repobility — scan your code at https://repobility.com
advise function · python · L30-L70 (41 LOC)
src/aumai_farmbrain/cli.py
def advise(crop: str, soil_file: str, weather_file: str | None) -> None:
    """Generate a crop advisory for a given crop and soil profile."""
    db = CropDatabase()
    advisor = CropAdvisor()

    crop_obj = db.by_name(crop)
    if crop_obj is None:
        click.echo(f"Error: Crop '{crop}' not found. Use 'crops --list' to see available crops.", err=True)
        sys.exit(1)

    with open(soil_file) as fh:
        soil = SoilProfile.model_validate(json.load(fh))

    weather: WeatherData | None = None
    if weather_file:
        with open(weather_file) as fh:
            weather = WeatherData.model_validate(json.load(fh))

    advisory = advisor.advise(crop_obj, soil, weather)

    click.echo(f"\n{'='*60}")
    click.echo(f"CROP ADVISORY: {advisory.crop.name.upper()}")
    click.echo(f"{'='*60}")
    click.echo("\nRECOMMENDATIONS:")
    for rec in advisory.recommendations:
        click.echo(f"  - {rec}")

    click.echo("\nFERTILIZER PLAN:")
    for stage, instruction in advisory
crops function · python · L76-L89 (14 LOC)
src/aumai_farmbrain/cli.py
def crops(show_list: bool, season: str | None) -> None:
    """List available crops in the database."""
    db = CropDatabase()
    if season:
        crop_list = db.by_season(season)
    else:
        crop_list = db.all_crops()

    click.echo(f"\nAVAILABLE CROPS ({len(crop_list)} total):")
    click.echo(f"{'Name':<30} {'Season':<10} {'Water':<10} {'Days':>6}")
    click.echo("-" * 60)
    for c in crop_list:
        click.echo(f"{c.name:<30} {c.season:<10} {c.water_requirement:<10} {c.growth_days:>6}")
    click.echo(f"\n{AGRICULTURAL_DISCLAIMER}\n")
serve function · python · L95-L102 (8 LOC)
src/aumai_farmbrain/cli.py
def serve(port: int, host: str) -> None:
    """Start the FarmBrain API server."""
    try:
        import uvicorn
    except ImportError:
        click.echo("Error: uvicorn is required to run the server. Install with: pip install uvicorn", err=True)
        sys.exit(1)
    uvicorn.run("aumai_farmbrain.api:app", host=host, port=port, reload=False)
CropDatabase class · python · L77-L102 (26 LOC)
src/aumai_farmbrain/core.py
class CropDatabase:
    """In-memory catalogue of 50+ Indian crops with lookup utilities."""

    def __init__(self) -> None:
        self._crops: list[Crop] = [Crop(**entry) for entry in _RAW_CROPS]  # type: ignore[arg-type]

    def all_crops(self) -> list[Crop]:
        """Return every crop in the database."""
        return list(self._crops)

    def by_name(self, name: str) -> Crop | None:
        """Case-insensitive crop lookup by name."""
        name_lower = name.lower()
        for crop in self._crops:
            if crop.name.lower() == name_lower:
                return crop
        return None

    def by_season(self, season: str) -> list[Crop]:
        """Return crops for a given season (kharif/rabi/zaid)."""
        return [c for c in self._crops if c.season == season.lower()]

    def by_soil_type(self, soil_type: str) -> list[Crop]:
        """Return crops compatible with a specific soil type."""
        soil_lower = soil_type.lower()
        return [c for c in self._cr
all_crops method · python · L83-L85 (3 LOC)
src/aumai_farmbrain/core.py
    def all_crops(self) -> list[Crop]:
        """Return every crop in the database."""
        return list(self._crops)
by_name method · python · L87-L93 (7 LOC)
src/aumai_farmbrain/core.py
    def by_name(self, name: str) -> Crop | None:
        """Case-insensitive crop lookup by name."""
        name_lower = name.lower()
        for crop in self._crops:
            if crop.name.lower() == name_lower:
                return crop
        return None
by_season method · python · L95-L97 (3 LOC)
src/aumai_farmbrain/core.py
    def by_season(self, season: str) -> list[Crop]:
        """Return crops for a given season (kharif/rabi/zaid)."""
        return [c for c in self._crops if c.season == season.lower()]
by_soil_type method · python · L99-L102 (4 LOC)
src/aumai_farmbrain/core.py
    def by_soil_type(self, soil_type: str) -> list[Crop]:
        """Return crops compatible with a specific soil type."""
        soil_lower = soil_type.lower()
        return [c for c in self._crops if any(s.lower() == soil_lower for s in c.soil_types)]
About: code-quality intelligence by Repobility · https://repobility.com
SoilAnalyzer class · python · L120-L214 (95 LOC)
src/aumai_farmbrain/core.py
class SoilAnalyzer:
    """Analyses soil profiles and recommends suitable crops."""

    def __init__(self, crop_db: CropDatabase | None = None) -> None:
        self._db = crop_db or CropDatabase()

    def analyze(self, soil: SoilProfile) -> list[str]:
        """Return agronomic recommendations for the given soil profile."""
        recs: list[str] = []

        # pH
        if soil.ph < _PH_LOW:
            recs.append(
                f"Soil pH {soil.ph:.1f} is acidic. Apply agricultural lime at"
                " 2-4 tonnes/hectare to raise pH to 6.0-7.5 range."
            )
        elif soil.ph > _PH_HIGH:
            recs.append(
                f"Soil pH {soil.ph:.1f} is alkaline. Apply gypsum or sulphur"
                " to lower pH towards 6.0-7.5 range."
            )
        else:
            recs.append(f"Soil pH {soil.ph:.1f} is within the optimal range (6.0-7.5).")

        # Nitrogen
        if soil.nitrogen_ppm < _N_LOW:
            recs.append(
                "Nit
analyze method · python · L126-L193 (68 LOC)
src/aumai_farmbrain/core.py
    def analyze(self, soil: SoilProfile) -> list[str]:
        """Return agronomic recommendations for the given soil profile."""
        recs: list[str] = []

        # pH
        if soil.ph < _PH_LOW:
            recs.append(
                f"Soil pH {soil.ph:.1f} is acidic. Apply agricultural lime at"
                " 2-4 tonnes/hectare to raise pH to 6.0-7.5 range."
            )
        elif soil.ph > _PH_HIGH:
            recs.append(
                f"Soil pH {soil.ph:.1f} is alkaline. Apply gypsum or sulphur"
                " to lower pH towards 6.0-7.5 range."
            )
        else:
            recs.append(f"Soil pH {soil.ph:.1f} is within the optimal range (6.0-7.5).")

        # Nitrogen
        if soil.nitrogen_ppm < _N_LOW:
            recs.append(
                "Nitrogen is LOW. Apply urea (46% N) at 120-150 kg/ha or"
                " incorporate green manure crops like dhaincha."
            )
        elif soil.nitrogen_ppm > _N_HIGH:
            recs.append(
suitable_crops method · python · L195-L214 (20 LOC)
src/aumai_farmbrain/core.py
    def suitable_crops(self, soil: SoilProfile) -> list[Crop]:
        """Return crops compatible with the given soil profile based on type and pH."""
        compatible: list[Crop] = []
        for crop in self._db.all_crops():
            soil_match = any(
                s.lower() == soil.soil_type.lower() for s in crop.soil_types
            )
            if not soil_match:
                continue
            # pH suitability heuristic
            if soil.ph < 5.5 and crop.water_requirement == "high":
                # Rice tolerates acidic; keep it
                compatible.append(crop)
            elif soil.ph < 5.5 and crop.name in ("Rice", "Jute", "Turmeric", "Ginger"):
                compatible.append(crop)
            elif 5.5 <= soil.ph <= 8.0:
                compatible.append(crop)
            elif soil.ph > 8.0 and crop.water_requirement == "low":
                compatible.append(crop)
        return compatible
CropAdvisor class · python · L221-L342 (122 LOC)
src/aumai_farmbrain/core.py
class CropAdvisor:
    """Generates complete crop advisories including fertilizer and irrigation plans."""

    _FERTILIZER_PLANS: dict[str, dict[str, str]] = {
        "rice": {
            "basal": "Apply DAP 50 kg/ha + MOP 25 kg/ha at transplanting.",
            "tillering": "Top-dress urea 30 kg/ha at 21 DAT.",
            "panicle initiation": "Apply urea 30 kg/ha + potassium sulphate 20 kg/ha.",
        },
        "wheat": {
            "basal": "Apply DAP 50 kg/ha + MOP 20 kg/ha at sowing.",
            "crown root initiation": "Top-dress urea 60 kg/ha at CRI stage (20-25 DAS).",
            "jointing": "Apply urea 30 kg/ha at jointing stage.",
        },
        "cotton": {
            "basal": "Apply SSP 150 kg/ha + MOP 25 kg/ha at sowing.",
            "squaring": "Apply urea 40 kg/ha + boron 1 kg/ha at squaring.",
            "boll development": "Top-dress NPK 12:32:16 at 50 kg/ha.",
        },
        "default": {
            "basal": "Apply recommended NPK complex fertili
advise method · python · L268-L342 (75 LOC)
src/aumai_farmbrain/core.py
    def advise(
        self,
        crop: Crop,
        soil: SoilProfile,
        weather: WeatherData | None = None,
    ) -> CropAdvisory:
        """Generate a complete CropAdvisory for the given inputs."""
        recommendations: list[str] = []
        risk_alerts: list[str] = []

        recommendations.append(
            f"{crop.name} is a {crop.season} crop requiring"
            f" {crop.water_requirement} water and {crop.growth_days} days to mature."
        )
        recommendations.append(
            f"Compatible soil types: {', '.join(crop.soil_types)}."
            f" Current soil type is {soil.soil_type}."
        )

        soil_analyzer = SoilAnalyzer()
        recommendations.extend(soil_analyzer.analyze(soil)[:-1])  # strip trailing disclaimer

        # Weather-based recommendations
        if weather is not None:
            if weather.temperature_c > 40:
                risk_alerts.append(
                    f"Extreme heat ({weather.temperature_c}°C) at {wea
Crop class · python · L22-L45 (24 LOC)
src/aumai_farmbrain/models.py
class Crop(BaseModel):
    """Represents an Indian agricultural crop with cultivation metadata."""

    name: str = Field(..., description="Common name of the crop")
    season: str = Field(
        ...,
        description="Growing season: kharif, rabi, or zaid",
        pattern="^(kharif|rabi|zaid)$",
    )
    water_requirement: str = Field(
        ..., description="Water requirement descriptor (low/medium/high)"
    )
    soil_types: list[str] = Field(
        ..., description="Compatible soil types for this crop"
    )
    growth_days: int = Field(
        ..., gt=0, description="Number of days from sowing to harvest"
    )

    @field_validator("season")
    @classmethod
    def validate_season(cls, value: str) -> str:
        """Normalise season to lowercase."""
        return value.lower()
validate_season method · python · L43-L45 (3 LOC)
src/aumai_farmbrain/models.py
    def validate_season(cls, value: str) -> str:
        """Normalise season to lowercase."""
        return value.lower()
SoilProfile class · python · L48-L66 (19 LOC)
src/aumai_farmbrain/models.py
class SoilProfile(BaseModel):
    """Chemical and physical profile of a soil sample."""

    ph: float = Field(..., ge=0.0, le=14.0, description="Soil pH (0-14)")
    nitrogen_ppm: float = Field(
        ..., ge=0.0, description="Available nitrogen in ppm"
    )
    phosphorus_ppm: float = Field(
        ..., ge=0.0, description="Available phosphorus in ppm"
    )
    potassium_ppm: float = Field(
        ..., ge=0.0, description="Available potassium in ppm"
    )
    organic_carbon_pct: float = Field(
        ..., ge=0.0, le=100.0, description="Organic carbon as percentage"
    )
    soil_type: str = Field(
        ..., description="Soil classification (e.g., alluvial, black, red)"
    )
If a scraper extracted this row, it came from Repobility (https://repobility.com)
WeatherData class · python · L69-L82 (14 LOC)
src/aumai_farmbrain/models.py
class WeatherData(BaseModel):
    """Current weather conditions for an agricultural location."""

    location: str = Field(..., description="Location name or coordinates string")
    temperature_c: float = Field(..., description="Current temperature in Celsius")
    humidity_pct: float = Field(
        ..., ge=0.0, le=100.0, description="Relative humidity percentage"
    )
    rainfall_mm: float = Field(
        ..., ge=0.0, description="Recent rainfall in millimetres"
    )
    forecast_days: int = Field(
        default=7, gt=0, le=30, description="Number of forecast days available"
    )
CropAdvisory class · python · L85-L106 (22 LOC)
src/aumai_farmbrain/models.py
class CropAdvisory(BaseModel):
    """Full advisory output for a crop-soil-weather combination."""

    crop: Crop
    soil: SoilProfile
    recommendations: list[str] = Field(
        ..., description="Actionable agronomic recommendations"
    )
    fertilizer_plan: dict[str, str] = Field(
        ..., description="Fertilizer application schedule keyed by stage"
    )
    irrigation_schedule: dict[str, str] = Field(
        ..., description="Irrigation schedule keyed by growth stage"
    )
    risk_alerts: list[str] = Field(
        default_factory=list,
        description="Risk warnings for pests, weather, or soil issues",
    )
    disclaimer: str = Field(
        default=AGRICULTURAL_DISCLAIMER,
        description="Mandatory agricultural advisory disclaimer",
    )