Beispiel #1
0
 def __init__(self, bot):
     self.mapbox = MapBox(token=get_token())
     self.gbif = GBIF()
     self.ebird = eBirdMap()
     self.typesense = ebl.TypeSenseSearch(api_key="changeMe!")
     self.typesense.connect()
     self.meili = ebl.MeilisearchSearch(api_key="changeMe!")
     self.meili.connect()
     self.map_size = 512
Beispiel #2
0
class TestCombinedGBIF:
    gbif: GBIF = GBIF()
    mapbox: MapBox = MapBox(token=get_token())

    @pytest.mark.vcr("new")
    @pytest.mark.parametrize(
        "taxon_id, tile_ids",
        [
            (
                2493091,
                ((
                    TileID(15, 16826, 10770),
                    TileID(15, 16826, 10771),
                    TileID(15, 16827, 10770),
                    TileID(15, 16827, 10771),
                )),
            ),
        ],
    )
    def test_gbif_mapbox_comp(self, taxon_id, tile_ids):
        mpta = TileArray.from_dict({x: Tile(x) for x in tile_ids})
        gbta = TileArray.from_dict({x: Tile(x) for x in tile_ids})

        mapbox_tiles = self.mapbox.get_tiles(mpta)
        gbif_tiles = self.gbif.get_tiles(taxon_id, gbta)
        c_tiles = mapbox_tiles._composite_layer(gbif_tiles)
        c_tiles.name = "gbif+mapbox"
        final_image = c_tiles._composite_all()
        final_image.save(f"gbif+mapbox-{taxon_id}-final.png")
Beispiel #3
0
class TestMapBox:
    mapbox: MapBox = MapBox(token=get_token())

    @pytest.mark.vcr("new")
    @pytest.mark.parametrize(
        "input_string, output",
        [
            ("Vancouver, Canada", LatLon(-123.116838, 49.279862)),
            ("Vondelpark", LatLon(4.877867, 52.362441)),
        ],
    )
    def test_geocode(self, input_string, output):
        res = self.mapbox.get_geocode(input_string)
        assert res == output

    def test_no_token(self):
        mp = MapBox()
        with pytest.raises(BaseMap.AuthMissingError):
            _ = mp.get_geocode("The Moon")

    @pytest.mark.vcr("new")
    @pytest.mark.parametrize(
        "tid, fmt, style, high_res",
        [
            (TileID(0, 0, 0), "jpg90", "satellite", False),
            (TileID(6, 40, 44), "jpg90", "satellite", True),
            (TileID(2, 2, 2), "jpg90", "satellite", True),
        ],
    )
    def test_get_tiles(self, tid, fmt, style, high_res):
        res = self.mapbox.get_tile(tid,
                                   fmt=fmt,
                                   style=style,
                                   high_res=high_res)

        assert res.resolution == 256 if not high_res else 512
        print("res:", res)
        res.save()
        assert type(res) == Tile

    @pytest.mark.vcr("new")
    @pytest.mark.parametrize(
        "tile_array",
        [
            (
                TileID(15, 16826, 10770),
                TileID(15, 16826, 10771),
                TileID(15, 16827, 10770),
                TileID(15, 16827, 10771),
            ),
        ],
    )
    def test_get_tilearray(self, tile_array):
        res_tiles = self.mapbox.get_tiles(tile_array)
        assert type(res_tiles) == TileArray
        for t in res_tiles.values():
            t.save()
Beispiel #4
0
 def test_no_token(self):
     mp = MapBox()
     with pytest.raises(BaseMap.AuthMissingError):
         _ = mp.get_geocode("The Moon")
Beispiel #5
0
class TestEbird:
    ebird: eBirdMap = eBirdMap()
    mapbox: MapBox = MapBox(token=get_token(), high_res=False)

    @pytest.mark.vcr("new")
    @pytest.mark.parametrize(
        "species_code, expected_bbox",
        [
            (
                "bushti",
                LatLonBBox(
                    -128.796028798097,
                    51.8596628170432,
                    -89.2701562968385,
                    14.126239979566,
                ),
            ),
            (
                "tui1",
                LatLonBBox(
                    -178.203369424671,
                    -28.7802470429875,
                    179.326113654898,
                    -52.691212723642,
                ),
            ),
            (
                "",
                None,
            ),
            (
                "redcro9",
                LatLonBBox(
                    -115.321299536305,
                    43.2077783892461,
                    -113.524668968066,
                    41.9867319031071,
                ),
            ),
        ],
    )
    def test_get_bbox(self, species_code, expected_bbox):
        res = self.ebird.get_bbox(species_code)
        assert res == expected_bbox

    @pytest.mark.vcr("new")
    @pytest.mark.parametrize(
        "species_code",
        [
            "bushti",
        ],
    )
    def test_get_rsid(self, species_code):
        res = self.ebird.get_rsid(species_code)
        assert res

    @pytest.mark.vcr("new")
    @pytest.mark.parametrize(
        "tile_id, rsid",
        [
            (
                TileID(0, 0, 0),
                "RS108970032",
            ),
        ],
    )
    def test_get_tile(self, tile_id, rsid):
        res = self.ebird.download_tile(tile_id, rsid)
        assert res.img

    @pytest.mark.vcr("new")
    @pytest.mark.parametrize(
        "species_code, expected_ids",
        [(
            "tui1",
            [(4, 15, 9), (4, 15, 10), (4, 0, 9), (4, 0, 10)],
        )],
    )
    def test_get_tiles(self, species_code, expected_ids):
        res = self.ebird.get_tiles(species_code)
        print("res:\n", res)
        for x in res:
            for t in x.values():
                t.save()

        for e in res:
            for x in e:
                assert tuple(x) in expected_ids

    @pytest.mark.vcr("new")
    @pytest.mark.parametrize(
        "species_code, size, no_data",
        [
            ("tui1", 512, False),
            ("bushti", 512, False),
            ("pilwoo", 512, False),
            ("inirai1", 512, False),
            ("bkpwar", 512, False),
            ("baleag", 512, False),
            ("grycat", 512, False),
            ("kinpen1", 512, False),
            ("carchi", 512, False),
            ("arcter", 512, False),
            ("dodo1", 512, True),
            ("pifgoo", 512, False),
        ],
    )
    def test_map_final(self, species_code, size, no_data):
        res, res_no_data = self.ebird.make_map(species_code, self.mapbox, size)
        assert res_no_data == no_data
        res.save(f"final-ebird-{species_code}_{size}.png")
Beispiel #6
0
class TestFullMapGBIF:
    gbif: GBIF = GBIF()
    mapbox: MapBox = MapBox(token=get_token())

    @pytest.mark.vcr("new")
    @pytest.mark.parametrize(
        "taxon_id",  # , expected_bbox",
        [
            (
                2493091,
                # (
                #     (
                #     TileID(15, 16826, 10770),
                #     TileID(15, 16826, 10771),
                #     TileID(15, 16827, 10770),
                #     TileID(15, 16827, 10771)
                #     )
                # ),
            ),
            (5228134, ),
        ],
    )
    def test_get_bbox_latlon(self, taxon_id):
        bbox = self.gbif.get_bbox(taxon_id)
        print(bbox)

    @pytest.mark.vcr("new")
    @pytest.mark.parametrize(
        "input_species, map_size",
        [
            ("Bushtit", 512),
            ("Bushtit", 1024),
            ("Inaccessible Island Rail", 512),
            ("Inaccessible Island Rail", 1024),
            ("Carolina Chickadee", 512),
        ],
    )
    def test_final_range_map_normal(self, input_species, map_size):
        species, taxon_key = self.gbif.lookup_species(input_species)
        range_map = generate_gbif_mapbox_range(taxon_key, self.gbif,
                                               self.mapbox, map_size)
        assert range_map.size == (map_size, map_size)
        range_map.save(f"test_final_range_map-{map_size}-{taxon_key}.png")

    @pytest.mark.vcr("new")
    @pytest.mark.parametrize(
        "input_species, map_size",
        [
            ("Tui", 512),
            ("Hawaiian Hawk", 512),
            ("Bald Eagle", 1024),
            ("Aptenodytes forsteri", 1024),
            ("Eudyptula minor", 512),
        ],
    )
    def test_final_range_map_antimeridian(self, input_species, map_size):
        species, taxon_key = self.gbif.lookup_species(input_species)
        print("taxon_key", taxon_key)
        range_map = generate_gbif_mapbox_range(taxon_key, self.gbif,
                                               self.mapbox, map_size)
        assert range_map.size == (map_size, map_size)
        range_map.save(f"test_final_range_map-{map_size}-{taxon_key}.png")
Beispiel #7
0
from pathlib import Path

import pytest
from static_maps.geo import LatLonBBox, LatLon
from static_maps.mapper import (
    GBIF,
    BaseMap,
    MapBox,
    get_token,
    generate_gbif_mapbox_range,
    eBirdMap,
)
from static_maps.tiles import Tile, TileArray, TileID
from static_maps.imager import Image

mapbox = MapBox(token=get_token())
gbif = GBIF()


class TestMapBox:
    mapbox: MapBox = MapBox(token=get_token())

    @pytest.mark.vcr("new")
    @pytest.mark.parametrize(
        "input_string, output",
        [
            ("Vancouver, Canada", LatLon(-123.116838, 49.279862)),
            ("Vondelpark", LatLon(4.877867, 52.362441)),
        ],
    )
    def test_geocode(self, input_string, output):
Beispiel #8
0
class GeoCog(commands.Cog):
    def __init__(self, bot):
        self.mapbox = MapBox(token=get_token())
        self.gbif = GBIF()
        self.ebird = eBirdMap()
        self.typesense = ebl.TypeSenseSearch(api_key="changeMe!")
        self.typesense.connect()
        self.meili = ebl.MeilisearchSearch(api_key="changeMe!")
        self.meili.connect()
        self.map_size = 512

    def find_species_from_name(self, arg, backend):
        try:
            r = backend.name_to_codes(arg, "all")
            return r
        except Exception:
            return None

    @commands.command(
        brief="Gets a lat/lon from an address, or vice versa.",
        help="Gets a lat/lon from an address, or vice versa. Mapbox version",
        usage="[query]",
    )
    async def geocode(self, ctx, *, arg):
        res = self.mapbox.get_geocode(arg)
        await ctx.send(res)

    @commands.command(
        brief="Gets a test range map.",
        help="Gets a test range map. Just Bushtits from GBIF.",
        usage="[query]",
    )
    async def gbifmap(self, ctx, *, arg):
        print("~~~~~~~~~~~~~^^~~~~~~~~~~~~~~~")
        print("gbifmap: ", arg)
        scientific_name, taxon_id = self.gbif.lookup_species(arg)
        if all((scientific_name, taxon_id)):
            start = datetime.now()
            result = generate_gbif_mapbox_range(taxon_id, self.gbif,
                                                self.mapbox, self.map_size)
            dur = datetime.now() - start
            if result is None:
                embed = discord.Embed(
                    title="Error:",
                    description="Range map creation failed.",
                    color=0xFF0000,
                )
                await ctx.send(embed=embed)
            desc = f"Source: GBIF, Mapbox. GBIF taxon id: {taxon_id}.\nDebug: {dur.seconds}s"
            gbif_url = f"https://www.gbif.org/species/{taxon_id}"
            embed = discord.Embed(title=scientific_name,
                                  description=desc,
                                  url=gbif_url,
                                  color=0x007F00)
            file = discord.File(result.asbytes(), filename=f"{taxon_id}.png")
            await ctx.send(file=file, embed=embed)
        else:
            embed = discord.Embed(title="Error:",
                                  description=f"Lookup of {arg} failed.",
                                  color=0xFF0000)
            await ctx.send(embed=embed)

    @commands.command(
        brief="Test GBIF species lookup.",
        help="Test GBIF species lookup.",
        usage="[query]",
    )
    async def glookup(self, ctx, *, arg):
        scientific_name, taxon_id = self.gbif.lookup_species(arg)
        if all((scientific_name, taxon_id)):
            await ctx.send(f"{arg} -> {scientific_name}, id: {taxon_id}.")
        else:
            await ctx.send("Lookup failed.")

    @commands.command(
        brief="Gets a lat/lon from an address, or vice versa.",
        help="Gets a lat/lon from an address, or vice versa. Mapbox version",
        usage="[query]",
    )
    async def ebirdmap(self, ctx, *, arg):
        ab = randint(0, 1)
        backend = [self.typesense, self.meili][ab]
        backend_name = ["typesense", "meili"][ab]
        res = self.find_species_from_name(arg, backend)
        res_img = None
        if res:
            print("res:", res, backend_name)
            species_code = res["species_code"]
            common_name = res["name"]
            scientific_name = res["scientific_name"]
            title = f"{common_name} (_{scientific_name}_)."
            ebird_url = f"{self.ebird.species_url}{species_code}"
            try:
                start = datetime.now()
                res_img, no_data = self.ebird.make_map(species_code,
                                                       self.mapbox, 512)
                img = res_img.asbytes()
                if not no_data:
                    res_img.save(f"geocog-ebird-{species_code}.png")
                    end = datetime.now()
                    desc = "Source: eBird, Mapbox."
                    desc += f"\nDebug: generated in: {(end - start).seconds}s. Search: {backend_name}."
                    embed = discord.Embed(title=title,
                                          url=ebird_url,
                                          description=desc,
                                          color=0x7F007F)
                    file = discord.File(img, filename=f"{species_code}.png")
                else:
                    desc = "**No data on eBird**.\nSource: eBird, Mapbox."
                    desc += f"\nDebug: no data, Search: {backend_name}."
                    embed = discord.Embed(title=title,
                                          url=ebird_url,
                                          description=desc,
                                          color=0x7F0000)
                    file = discord.File(img, filename=f"{species_code}.png")

            except Exception:
                traceback.print_exc()
                pass

        if res_img:
            await ctx.send(file=file, embed=embed)
        elif not res:
            embed = discord.Embed(title="Error:",
                                  description=f"Lookup of {arg} failed.",
                                  color=0xFF0000)
            await ctx.send(embed=embed)
        else:
            embed = discord.Embed(
                title="Error:",
                description="Range map creation failed.",
                color=0xFF0000,
            )
            await ctx.send(embed=embed)