Issues

  • datepicker does not work on firefox and safari because they do not support the HTML date input field
  • can not set disabed state for datepicker
  • how to set the number of results

In [3]:
from IPython.display import clear_output, Javascript, display
from nbformat import current

import io
import os, fnmatch
from datetime import datetime
import urllib.request
from urllib.parse import quote
from pprint import pprint
import json
import subprocess

import ipywidgets as widgets
from ipywidgets import Layout, Box, HBox,DatePicker

html_metadata=widgets.HTML(
    value=""
)
from ipyleaflet import (
    Map,
    Marker,
    TileLayer, ImageOverlay,
    Polyline, Polygon, Rectangle, Circle, CircleMarker,
    GeoJSON,
    DrawControl
)

select=widgets.Select(
    options=[''],
    value='',
    # rows=10,
    description='OS:',
    disabled=False
)

widgetStartTime = DatePicker(description="From:", disabled=False,value=datetime(1970,1,1,0,0,0))
widgetEndTime = DatePicker(description="To:", disabled=False,value=datetime.now())
plotButton=widgets.Button(description="Show available products")
useTimeCheckBox=widgets.Checkbox(
    value=False,
    description='Use date',
    disabled=False
)
ile_wynikpw=widgets.BoundedIntText(
value=100,
min=1,
max=100000,
step=1,
description='Number of results:',
disabled=False
)

dc = DrawControl(circle={},rectangle={},polyline={},polygon={}
                ,marker={'shapeOptions':{'color':'#5300FF'}},edit=False)

mission=widgets.Dropdown(
    options=['All','Envisat','Landsat5','Landsat7','Landsat8','Sentinel1','Sentinel2','Sentinel3'],
    description='Mission:',
    value='All',
    disabled=False,
)

instrument=widgets.Dropdown(
    options=['All','Meris','TM','ETM','OLI','OLI_TIRS','TIRS','SAR','MSI','OLCI','SLSTR','SRAL'],
    description='Instrument:',
    disabled=False,
)

punkty=[]


def handle_draw(self, action, geo_json):
    global punkty
    if action=='created':
        punkty.append(geo_json['geometry']['coordinates'])
    elif action=='deleted':
        punkty.remove(geo_json['geometry']['coordinates']) 
        

dc.on_draw(handle_draw)

m=Map(zoom=1)
m.add_control(dc)
wkt=''
layers=[]
lop=[]
def on_button_clicked(b):
    clear_output()
    global punkty,wkt,m,layers,lop
    print (len(punkty))
    for i in m.layers[1:]:        
        m.remove_layer(i)
    
    if useTimeCheckBox.value:
        datetime
        start=widgetStartTime.value.isoformat()
        end=widgetEndTime.value.isoformat()
        tstr="&startDate=%s&completionDate=%s"%(start,end)
        print(tstr)
    else:
        tstr=''
    if len(punkty)>0:
        wkt='&geometry=MULTIPOINT('
        s=[]
        for punkt in punkty:
            s.append('(%f %f)'%(punkt[0],punkt[1]))
        s=",".join(s)
        wkt+=s+')'        
    else:
        wkt=''
    if mission.value!='All':
        col=mission.value+"/"
    else:
        col=''
    if instrument.value!='All':
        ins='&instrument='+instrument.value
    else:
        ins=''      
    request="finder.eocloud.eu/resto/api/collections/"+col+"search.json?_pretty=true&maxRecords=%d"%ile_wynikpw.value+wkt+tstr
    request+=ins
    request="http://"+quote(request,safe="%/:=&?~#+!$,;'@()*[]")
    print(request)        
    with urllib.request.urlopen(request) as response:
        h=response.read()
    h=json.loads(h)
    g=GeoJSON(data=h,hover_style={'fillColor': 'red'})
    layers.append(g)
    m.add_layer(g)
    list_of_products=[]
    lop=[]
    for feature in h['features']:
        lop.append(feature)
        list_of_products.append(";".join([feature['properties']['collection'],
              feature['properties']['instrument'],
              feature['properties']['completionDate'],
              feature['properties']['instrument'],
              feature['properties']['productIdentifier']]))        
    select.options=list_of_products
    

def mission_change(*args):     
    instrument.disabled=False
    if args[0]['new']=='Envisat':
        instrument.options=['MERIS']
    elif args[0]['new']=='Landsat5':
        instrument.options=['TM']
    elif args[0]['new']=='Landsat7':
        instrument.options=['ETM']
    elif args[0]['new']=='Landsat8':
        instrument.options=['All','OLI','OLI_TIRS','TIRS']
    elif args[0]['new']=='Sentinel1':
        instrument.options=['SAR']
    elif args[0]['new']=='Sentinel2':
        instrument.options=['MSI']
    elif args[0]['new']=='Sentinel3':
        instrument.options=['All','OL','SL','SR']
    elif args[0]['new']=='All':
        instrument.options=['All','MERIS','TM','ETM','OLI','OLI_TIRS','TIRS','SAR','MSI','OLCI','SLSTR','SR']
        instrument.value='All'
    
def timeCheck(*args):
    if args[0]['new']:
        widgetStartTime.disabled=False
        widgetEndTime.disabled=False
    else:
        widgetStartTime.disabled=True
        widgetEndTime.disabled=True

def find(pattern, path):
    result = []
    for root, dirs, files in os.walk(path):
        for name in files:
            if fnmatch.fnmatch(name, pattern):
                result.append(os.path.join(root, name))
    return result


def product_select(*args): 
    path1=args[0]['new'].split(';')[-1]
    if path1.upper().endswith('.SEN3'):
        print (path1)
        return 0
    if not path1.upper().endswith('.N1'):        
        plik='*_MTL.txt'
        found=find(plik,path1)
        if found:            #LANDSAT 5,7,8
            path1=found[0]
            print(path1)
            res=subprocess.Popen(['/opt/scripts/metadata.py',path1],stdout=subprocess.PIPE).communicate()
            html_metadata.value=res[0]
        else:
            plik='product-preview.html'            
            found=find(plik,path1)            
            if not found:
                plik='UserProduct_index.html'
                found=find(plik,path1)
                print(found)
            else:
                res=''
                print(found)
                with open(found[0]) as f:
                    for line in f:
                        res+=line
                    f.close()
                html_metadata.value=res
            
                    
    else:       #ENVISAT
        print(path1)
        res=subprocess.Popen(['/opt/scripts/metadata.py',path1],stdout=subprocess.PIPE).communicate()
        html_metadata.value=res[0]
    
#Obsługa eventów
plotButton.on_click(on_button_clicked)
mission.observe(mission_change,names='value')
useTimeCheckBox.observe(timeCheck,names='value')
select.observe(product_select,names='value')

box_layout = Layout(display='flex',
                    flex_flow='column',                    
                    align_items='center',
                    border='solid',                    
                    width='100%')

items=[HBox([ile_wynikpw]),
       HBox([useTimeCheckBox,widgetStartTime,widgetEndTime]),
       widgets.Label(value="Properties:"),
       HBox([mission,instrument]),
       m,
       plotButton,select,
       html_metadata]
box = Box(children=items, layout=box_layout)
ii=0
box



In [ ]:
pr=