Package: azure-agrifood-farming
Azure FarmBeats client library for PythonFarmBeats is a B2B PaaS offering from Microsoft that makes it easy for AgriFood companies to build intelligent digital agriculture solutions on Azure. FarmBeats allows users to acquire, aggregate, and process agricultural data from various sources (farm equipment, weather, satellite) without the need to invest in deep data engineering resources.  Customers can build SaaS solutions on top of FarmBeats and leverage first class support for model building to generate insights at scale.Use FarmBeats client library for Python to do the following.Create & update parties, farms, fields, seasonal fields and boundaries.Ingest satellite and weather data for areas of interest.Ingest farm operations data covering tilling, planting, harvesting and application of farm inputs.Source code|Package (PyPi)|API reference documentation|Product documentation|ChangelogGetting startedPrerequisitesTo use this package, you must have:Azure subscription -Create a free accountAzure FarmBeats resource -Install FarmBeats3.6 or later -Install PythonInstall the packageInstall the Azure FarmBeats client library for Python withpip:pipinstallazure-agrifood-farmingAuthenticate the clientTo use anAzure Active Directory (AAD) token credential,
provide an instance of the desired credential type obtained from theazure-identitylibrary.To authenticate with AAD, you must firstpipinstallazure-identityand
enable AAD authentication on your FarmBeats resource. If you followed theinstallation docswhen creating the FarmBeats
resource, this is already covered.After setup, you can choose which type ofcredentialfrom azure.identity to use.
As an example,DefaultAzureCredentialcan be used to authenticate the client:Set the values of the client ID, tenant ID, and client secret of the AAD application as environment variables:
AZURE_CLIENT_ID, AZURE_TENANT_ID, AZURE_CLIENT_SECRETUse the returned token credential to authenticate the client:fromazure.agrifood.farmingimportFarmBeatsClientfromazure.identityimportDefaultAzureCredentialcredential=DefaultAzureCredential()client=FarmBeatsClient(endpoint="https://<my-account-name>.farmbeats.azure.net",credential=credential)Key conceptsBasic understanding of below terms will help to get started with FarmBeats client library.Farm HierarchyFarm hierarchy is a collection of below entities.Party - is the custodian of all the agronomic data.Farm - is a logical collection of fields and/or seasonal fields. They do not have any area associated with them.Field - is a multi-polygon area. This is expected to be stable across seasons.Seasonal field - is a multi-polygon area. To define a seasonal boundary we need the details of area (boundary), time (season) and crop. New seasonal fields are expected to be created for every growing season.Boundary - is the actual multi-polygon area expressed as a geometry (in geojson). It is normally associated with a field or a seasonal field. Satellite, weather and farm operations data is linked to a boundary.Cascade delete - Agronomic data is stored hierarchically with party as the root. The hierarchy includes Party -> Farms -> Fields -> Seasonal Fields -> Boundaries -> Associated data (satellite, weather, farm operations). Cascade delete refers to the process of deleting any node and its subtree.ScenesScenes refers to images normally ingested using satellite APIs. This includes raw bands and derived bands (Ex: NDVI). Scenes may also include spatial outputs of an inference or AI/ML model (Ex: LAI).Farm OperationsFam operations includes details pertaining to tilling, planting, application of pesticides & nutrients, and harvesting. This can either be manually pushed into FarmBeats using APIs or the same information can be pulled from farm equipment service providers like John Deere.ExamplesCreate a PartyOnce you have authenticated and created the client object as shown in theAuthenticate the clientsection, you can create a party within the FarmBeats resource like this:fromazure.identityimportDefaultAzureCredentialfromazure.agrifood.farmingimportFarmBeatsClientcredential=DefaultAzureCredential()client=FarmBeatsClient(endpoint="https://<my-account-name>.farmbeats.azure.net",credential=credential)party_id="party-1"party=client.parties.create_or_update(party_id=party_id,party={"name":party_name,"description":party_description})Create a Farmfromazure.identityimportDefaultAzureCredentialfromazure.agrifood.farmingimportFarmBeatsClientcredential=DefaultAzureCredential()client=FarmBeatsClient(endpoint="https://<my-account-name>.farmbeats.azure.net",credential=credential)party_id="party-1"# Using party from previous examplefarm=client.farms.create_or_update(party_id=party_id,farm_id="farm-1",farm={"name":farm_name,"description":farm_description})Create a SeasonCreating a Season object, spanning from April to August of 2021.fromazure.identityimportDefaultAzureCredentialfromazure.agrifood.farmingimportFarmBeatsClientcredential=DefaultAzureCredential()client=FarmBeatsClient(endpoint="https://<my-account-name>.farmbeats.azure.net",credential=credential)season_id="contoso-season"season_name="contoso-season-name"season_description="contoso-season-description"year="2021"start_date_time="2021-01-01T20:08:10.137Z"end_date_time="2021-06-06T20:08:10.137Z"season=client.seasons.create_or_update(season_id=season_id,season={"name":season_name,"year":year,"startDateTime":start_date_time,"endDateTime":end_date_time,"description":season_description})Create a BoundaryCreating a Boundary for the Seasonal Field created in the preceding example.fromazure.identityimportDefaultAzureCredentialfromazure.agrifood.farmingimportFarmBeatsClientcredential=DefaultAzureCredential()client=FarmBeatsClient(endpoint="https://<my-account-name>.farmbeats.azure.net",credential=credential)party_id="party-1"boundary_id="boundary-1"boundary=client.boundaries.create_or_update(party_id=party_id,boundary_id=boundary_id,boundary={"geometry":{"type":"Polygon","coordinates":[[[73.70457172393799,20.545385304358106],[73.70457172393799,20.545385304358106],[73.70448589324951,20.542411534243367],[73.70877742767334,20.541688176010233],[73.71023654937744,20.545083911372505],[73.70663166046143,20.546992723579137],[73.70457172393799,20.545385304358106],]]},"status":"<string>","name":"<string>","description":"<string>"})Ingest Satellite ImageryTriggering a Satellite Data Ingestion job for the boundary created above,
to ingest Leaf Area Index data for the month of January 2020.
This is a Long Running Operation (also called a 'Job'), and returns
a Poller object. Calling the.result()method on the poller object
waits for the operation to terminate, and returns the final status.fromazure.identityimportDefaultAzureCredentialfromazure.agrifood.farmingimportFarmBeatsClientfromisodate.tzinfoimportUtcfromdatetimeimportdatetimecredential=DefaultAzureCredential()client=FarmBeatsClient(endpoint="https://<my-account-name>.farmbeats.azure.net",credential=credential)party_id="party-1"boundary_id="westlake-boundary-1"start_date_time="2021-01-01T20:08:10.137Z"end_date_time="2021-06-06T20:08:10.137Z"# Queue the jobsatellite_job_poller=client.scenes.begin_create_satellite_data_ingestion_job(job_id=job_id,job={"boundaryId":boundary_id,"endDateTime":end_date_time,"partyId":party_id,"startDateTime":start_date_time,"provider":"Microsoft","source":"Sentinel_2_L2A","data":{"imageNames":["NDVI"],"imageFormats":["TIF"],"imageResolution":[10]},"name":"<string>","description":"<string>"})# Wait for the job to terminatesatellite_job=satellite_job_poller.result()job_status=satellite_job_poller.status()Get Ingested Satellite ScenesQuerying for the scenes created by the job in the previous example.fromazure.identityimportDefaultAzureCredentialfromazure.agrifood.farmingimportFarmBeatsClientfromdatetimeimportdatetimecredential=DefaultAzureCredential()client=FarmBeatsClient(endpoint="https://<my-account-name>.farmbeats.azure.net",credential=credential)party_id="party-1"boundary_id="boundary-1"scenes=client.scenes.list(party_id=party_id,boundary_id=boundary_id,start_date_time=start_date_time,end_date_time=end_date_time,provider="Microsoft",source="Sentinel_2_L2A")forsceneinscenes:bands=[image_file["name"]forimage_fileinscene["imageFiles"]]bands_str=", ".join(bands)print(f"Scene has the bands{bands_str}")TroubleshootingGeneralThe FarmBeats client will raise exceptions defined in [Azure Core][azure_core] if you call.raise_for_status()on your responses.LoggingThis library uses the standardlogginglibrary for logging.
Basic information about HTTP sessions (URLs, headers, etc.) is logged at INFO
level.Detailed DEBUG level logging, including request/response bodies and unredacted
headers, can be enabled on a client with thelogging_enablekeyword argument:importsysimportloggingfromazure.identityimportDefaultAzureCredentialfromazure.agrifood.farmingimportFarmBeatsClient# Create a logger for the 'azure' SDKlogger=logging.getLogger('azure')logger.setLevel(logging.DEBUG)# Configure a console outputhandler=logging.StreamHandler(stream=sys.stdout)logger.addHandler(handler)endpoint="https://<my-account-name>.farmbeats.azure.net"credential=DefaultAzureCredential()# This client will log detailed information about its HTTP sessions, at DEBUG levelclient=FarmBeatsClient(endpoint=endpoint,credential=credential,logging_enable=True)Similarly,logging_enablecan enable detailed logging for a single call,
even when it isn't enabled for the client:client.crops.get(crop_id="crop_id",logging_enable=True)Next stepsAdditional documentationFor more extensive documentation on the FarmBeats, see theFarmBeats documentationon docs.microsoft.com.ContributingThis project welcomes contributions and suggestions. Most contributions require you to agree to a Contributor License Agreement (CLA) declaring that you have the right to, and actually do, grant us the rights to use your contribution. For details, visitcla.microsoft.com.When you submit a pull request, a CLA-bot will automatically determine whether you need to provide a CLA and decorate the PR appropriately (e.g., label, comment). Simply follow the instructions provided by the bot. You will only need to do this once across all repos using our CLA.This project has adopted theMicrosoft Open Source Code of Conduct. For more information see theCode of Conduct FAQor contactopencode@microsoft.comwith any additional questions or comments.Release History1.0.0b2 (2023-02-23)Features AddedAdding clients for Sensor Integration which includes crud operations on DeviceDataModels, Devices, SensorDataModels, Sensors, SensorMappings, SensorPartnerIntegration and get Sensor events.Adding new APIs for STAC search and get featureAdding breedingMethods and Measurements as part of Crop EntityAdding geographicIdentifier as part of Season EntityAdding trait, relativeMeasurements and treatments as part of CropVariety EntityAdding type, crs, centroid and bbox(bounding box of the geometry) as part of Boundary EntityAdding Source field in Farmer, Farm, Field, Seasonal Field, Boundary, Crop, Crop variety, Season and AttachmentCreatedBy and ModifiedBy in all entitiesMeasure renamed to measurements in Prescription & CropAcreage renamed to area in BoundaryGet Feature and Search Feature APIs for Sentinel 2 L2A and Sentinel 2 L1C STAC collectionsAdding Weather Data APIs to fetch IBM weather dataBreaking ChangesRemoving primaryBoundaryId & boundaryIds from Field and Seasonal FieldRemoving isPrimary flag from BoundaryRemoving avgYields from Seasonal FieldRenaming Farmer to PartyRenaming CropVariety to CropProductUpdated dependency from azure-core<2.0.0,>=1.2.2 to azure-core<2.0.0,>=1.24.0Other ChangesPython 2.7 is no longer supported. Please use Python version 3.6 or later.1.0.0b1 (2021-05-25)This is the initial release of the Azure AgriFood Farming library.