Skip to content

Commit

Permalink
Merge pull request #142 from developmentseed/hotfix/search
Browse files Browse the repository at this point in the history
version 0.11.0
  • Loading branch information
Scisco committed Jan 12, 2016
2 parents 1175020 + 0996e14 commit e58abe1
Show file tree
Hide file tree
Showing 9 changed files with 271 additions and 45 deletions.
2 changes: 2 additions & 0 deletions docs/commands.rst
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,8 @@ Commands

--json Returns a bare JSON response

--geojson Returns a geojson response

-h, --help Show this help message and exit

Download:
Expand Down
8 changes: 6 additions & 2 deletions docs/overview.rst
Original file line number Diff line number Diff line change
Expand Up @@ -36,9 +36,13 @@ Search by latitude and longitude::

$: landsat search --lat 38.9004204 --lon -77.0237117

Search by latitude and longitude with pure json output::
Search by latitude and longitude with pure json output (you should install geojsonio-cli first)::

$: landsat search --lat 38.9004204 --lon -77.0237117 --json
$: landsat search --lat 38.9004204 --lon -77.0237117 --geojson | geojosnio

Show search output on geojsonio::

$: landsat search

Download
++++++++
Expand Down
2 changes: 1 addition & 1 deletion landsat/__init__.py
Original file line number Diff line number Diff line change
@@ -1 +1 @@
__version__ = '0.10.0'
__version__ = '0.11.0'
63 changes: 35 additions & 28 deletions landsat/landsat.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
# Landsat Util
# License: CC0 1.0 Universal

import sys
import argparse
import textwrap
import json
Expand Down Expand Up @@ -62,6 +61,8 @@
--json Returns a bare JSON response
--geojson Returns a geojson response
-h, --help Show this help message and exit
Download:
Expand Down Expand Up @@ -193,6 +194,7 @@ def args_options():
parser_search.add_argument('--lon', type=float, help='The longitude')
parser_search.add_argument('--address', type=str, help='The address')
parser_search.add_argument('--json', action='store_true', help='Returns a bare JSON response')
parser_search.add_argument('--geojson', action='store_true', help='Returns a geojson response')

parser_download = subparsers.add_parser('download',
help='Download images from Google Storage')
Expand Down Expand Up @@ -328,36 +330,43 @@ def main(args):
limit=args.limit,
start_date=args.start,
end_date=args.end,
cloud_max=args.cloud)
cloud_max=args.cloud,
geojson=args.geojson)

if result['status'] == 'SUCCESS':
if args.json:
return json.dumps(result)
if 'status' in result:

if args.latest > 0:
datelist = []
for i in range(0, result['total_returned']):
datelist.append((result['results'][i]['date'], result['results'][i]))
if result['status'] == 'SUCCESS':
if args.json:
return json.dumps(result)

datelist.sort(key=lambda tup: tup[0], reverse=True)
datelist = datelist[:args.latest]
if args.latest > 0:
datelist = []
for i in range(0, result['total_returned']):
datelist.append((result['results'][i]['date'], result['results'][i]))

result['results'] = []
for i in range(0, len(datelist)):
result['results'].append(datelist[i][1])
result['total_returned'] = len(datelist)
datelist.sort(key=lambda tup: tup[0], reverse=True)
datelist = datelist[:args.latest]

else:
v.output('%s items were found' % result['total'], normal=True, arrow=True)
result['results'] = []
for i in range(0, len(datelist)):
result['results'].append(datelist[i][1])
result['total_returned'] = len(datelist)

if result['total'] > 100:
return ['Over 100 results. Please narrow your search', 1]
else:
v.output(json.dumps(result, sort_keys=True, indent=4), normal=True, color='green')
return ['Search completed!']
else:
v.output('%s items were found' % result['total'], normal=True, arrow=True)

if result['total'] > 100:
return ['Over 100 results. Please narrow your search', 1]
else:
v.output(json.dumps(result, sort_keys=True, indent=4), normal=True, color='green')
return ['Search completed!']

elif result['status'] == 'error':
return [result['message'], 1]

if args.geojson:
return json.dumps(result)

elif result['status'] == 'error':
return [result['message'], 1]
elif args.subs == 'download':
d = Downloader(download_dir=args.dest)
try:
Expand Down Expand Up @@ -459,10 +468,8 @@ def __main__():
global parser
parser = args_options()
args = parser.parse_args()
if args.subs == 'search':
if args.json:
print main(args)
sys.exit(0)
if args.subs == 'search' and (hasattr(args, 'json') or hasattr(args, 'geojson')):
print(main(args))
else:
with timer():
exit(*main(args))
Expand Down
63 changes: 50 additions & 13 deletions landsat/search.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ def __init__(self):
self.api_url = settings.API_URL

def search(self, paths_rows=None, lat=None, lon=None, address=None, start_date=None, end_date=None, cloud_min=None,
cloud_max=None, limit=1):
cloud_max=None, limit=1, geojson=False):
"""
The main method of Search class. It searches Development Seed's Landsat API.
Expand Down Expand Up @@ -56,6 +56,10 @@ def search(self, paths_rows=None, lat=None, lon=None, address=None, start_date=N
integer specigying the maximum results return.
:type limit:
integer
:param geojson:
boolean specifying whether to return a geojson object
:type geojson:
boolean
:returns:
dict
Expand Down Expand Up @@ -98,18 +102,51 @@ def search(self, paths_rows=None, lat=None, lon=None, address=None, start_date=N
result['message'] = r_dict['error']['message']

elif 'meta' in r_dict:
result['status'] = u'SUCCESS'
result['total'] = r_dict['meta']['results']['total']
result['limit'] = r_dict['meta']['results']['limit']
result['total_returned'] = len(r_dict['results'])
result['results'] = [{'sceneID': i['sceneID'],
'sat_type': u'L8',
'path': three_digit(i['path']),
'row': three_digit(i['row']),
'thumbnail': i['browseURL'],
'date': i['acquisitionDate'],
'cloud': i['cloudCoverFull']}
for i in r_dict['results']]
if geojson:
result = {
'type': 'FeatureCollection',
'features': []
}
for r in r_dict['results']:
feature = {
'type': 'Feature',
'properties': {
'sceneID': r['sceneID'],
'row': three_digit(r['row']),
'path': three_digit(r['path']),
'thumbnail': r['browseURL'],
'date': r['acquisitionDate'],
'cloud': r['cloudCoverFull']
},
'geometry': {
'type': 'Polygon',
'coordinates': [
[
[r['upperLeftCornerLongitude'], r['upperLeftCornerLatitude']],
[r['lowerLeftCornerLongitude'], r['lowerLeftCornerLatitude']],
[r['lowerRightCornerLongitude'], r['lowerRightCornerLatitude']],
[r['upperRightCornerLongitude'], r['upperRightCornerLatitude']],
[r['upperLeftCornerLongitude'], r['upperLeftCornerLatitude']]
]
]
}
}

result['features'].append(feature)

else:
result['status'] = u'SUCCESS'
result['total'] = r_dict['meta']['results']['total']
result['limit'] = r_dict['meta']['results']['limit']
result['total_returned'] = len(r_dict['results'])
result['results'] = [{'sceneID': i['sceneID'],
'sat_type': u'L8',
'path': three_digit(i['path']),
'row': three_digit(i['row']),
'thumbnail': i['browseURL'],
'date': i['acquisitionDate'],
'cloud': i['cloudCoverFull']}
for i in r_dict['results']]

return result

Expand Down
1 change: 1 addition & 0 deletions requirements/docker.txt
Original file line number Diff line number Diff line change
Expand Up @@ -7,3 +7,4 @@ homura>=0.1.2
boto>=2.38.0
polyline==1.1
geocoder>=1.5.1
jsonschema==2.5.1
149 changes: 149 additions & 0 deletions tests/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,149 @@

geojson_schema = {
"$schema": "http://json-schema.org/draft-04/schema#",
"id": "http://json-schema.org/geojson/geojson.json#",
"title": "Geo JSON object",
"description": "Schema for a Geo JSON object",
"type": "object",
"required": ["type"],
"properties": {
"crs": {"$ref": "http://json-schema.org/geojson/crs.json#"},
"bbox": {"$ref": "http://json-schema.org/geojson/bbox.json#"}
},
"oneOf": [
{"$ref": "#/definitions/geometry"},
{"$ref": "#/definitions/geometryCollection"},
{"$ref": "#/definitions/feature"},
{"$ref": "#/definitions/featureCollection"}
],
"definitions": {
"position": {
"description": "A single position",
"type": "array",
"minItems": 2,
"items": [ {"type": "number"}, {"type": "number"} ],
"additionalItems": False
},
"positionArray": {
"description": "An array of positions",
"type": "array",
"items": {"$ref": "#/definitions/position"}
},
"lineString": {
"description": "An array of two or more positions",
"allOf": [
{"$ref": "#/definitions/positionArray"},
{"minItems": 2}
]
},
"linearRing": {
"description": "An array of four positions where the first equals the last",
"allOf": [
{"$ref": "#/definitions/positionArray"},
{"minItems": 4}
]
},
"polygon": {
"description": "An array of linear rings",
"type": "array",
"items": {"$ref": "#/definitions/linearRing"}
},
"geometry": {
"$schema": "http://json-schema.org/draft-04/schema#",
"title": "geometry",
"description": "One geometry as defined by GeoJSON",
"type": "object",
"required": ["type", "coordinates"],
"oneOf": [
{
"title": "Point",
"properties": {
"type": {"enum": ["Point"]},
"coordinates": {"$ref": "#/definitions/position"}
}
},
{
"title": "MultiPoint",
"properties": {
"type": {"enum": ["MultiPoint"]},
"coordinates": {"$ref": "#/definitions/positionArray"}
}
},
{
"title": "LineString",
"properties": {
"type": {"enum": ["LineString"]},
"coordinates": {"$ref": "#/definitions/lineString"}
}
},
{
"title": "MultiLineString",
"properties": {
"type": {"enum": [ "MultiLineString" ]},
"coordinates": {
"type": "array",
"items": {"$ref": "#/definitions/lineString"}
}
}
},
{
"title": "Polygon",
"properties": {
"type": {"enum": [ "Polygon" ]},
"coordinates": {"$ref": "#/definitions/polygon"}
}
},
{
"title": "MultiPolygon",
"properties": {
"type": {"enum": ["MultiPolygon"]},
"coordinates": {
"type": "array",
"items": {"$ref": "#/definitions/polygon"}
}
}
}
]
},
"geometryCollection": {
"title": "GeometryCollection",
"description": "A collection of geometry objects",
"required": [ "geometries" ],
"properties": {
"type": {"enum": [ "GeometryCollection" ]},
"geometries": {
"type": "array",
"items": {"$ref": "#/definitions/geometry"}
}
}
},
"feature": {
"title": "Feature",
"description": "A Geo JSON feature object",
"required": [ "geometry", "properties" ],
"properties": {
"type": {"enum": [ "Feature" ]},
"geometry": {
"oneOf": [
{"type": "null"},
{"$ref": "#/definitions/geometry"}
]
},
"properties": {"type": [ "object", "null" ]},
"id": {"FIXME": "may be there, type not known (string? number?)"}
}
},
"featureCollection": {
"title": "FeatureCollection",
"description": "A Geo JSON feature collection",
"required": [ "features" ],
"properties": {
"type": {"enum": [ "FeatureCollection" ]},
"features": {
"type": "array",
"items": {"$ref": "#/definitions/feature"}
}
}
}
}
}

0 comments on commit e58abe1

Please sign in to comment.