Commit 25608314 authored by Emmanuel René Huchim Puc's avatar Emmanuel René Huchim Puc

Merge branch 'images_map' into dev

parents 5e2a6943 a24b08c7
......@@ -28,5 +28,14 @@
</span>
</a>
</li>
<li>
<a class="treeview " href="#" onclick="window.history.back();">
<i class="fa fa-backward"></i>
<span>Back</span>
<span class="pull-right-container">
<span class="label label-primary pull-right"></span>
</span>
</a>
</li>
</ul>
</div>
\ No newline at end of file
......@@ -231,13 +231,13 @@ def to_if(name):
#-----------------------------------------------
def best_unit_size(bytes_size):
"""
Obtenga un tamaño en bytes y conviértalo en el mejor prefijo IEC para facilitar la lectura.
Obtenga un tamano en bytes y conviertalo en el mejor prefijo IEC para facilitar la lectura.
Devuelva un diccionario con tres pares de claves / valores:
"s" - (flotador) Tamaño del camino convertido a la mejor unidad para una fácil lectura
"s" - (flotador) Tamano del camino convertido a la mejor unidad para una facil lectura
"u" - (str) El prefijo (IEC) para s (de bytes (2 ^ 0) a YiB (2 ^ 80))
"b" - (int / long) El tamaño original en bytes
"b" - (int / long) El tamano original en bytes
"""
for exp in range(0, 90 , 10):
......
......@@ -26,11 +26,36 @@ body
height: 550px; /*should be the same height as the images*/
}
.listImg{
z-index: 4;
}
.listImg ul{
list-style: none;
padding: 0px;
margin: 0px;
cursor: pointer;
}
.listImg ul li:hover{
background: #87CEFA;
}
.listImg ul .active{
color:red
}
.list {
max-height: 220px;
overflow: auto;
}
.img-comp-img {
position: absolute;
width: auto;
height: auto;
overflow:hidden;
z-index: 2;
}
.img-comp-img img {
......
// set defaults http://localhost:8000/reports/tiles/2z68/T14QMG/20190127/10/230/569.png
MAPBOX_ACCESS_TOKEN = 'pk.eyJ1IjoibWFwYm94IiwiYSI6ImNpejY4NXVycTA2emYycXBndHRqcmZ3N3gifQ.rJcFIG214AriISLbB6B5aw';
// Create layers
var imagelayer;
var mapbox = new ol.layer.Tile({
source: new ol.source.XYZ({
url:'https://api.tiles.mapbox.com/v4/mapbox.light/{z}/{x}/{y}.png?access_token='+MAPBOX_ACCESS_TOKEN
})
});
// create map
var map = new ol.Map({
target: 'minimap',
layers: [mapbox],
view: new ol.View({
center: ol.proj.fromLonLat([-99.19, 19.61]),
zoom: 4,
minZoom:4,
maxZoom: 14
})
});
//addLayer
function addImageLayer(labelDate) {
map.removeLayer(imagelayer)
var xyz = new ol.layer.Tile({
opacity: 0.5,
source: new ol.source.XYZ({
projection: 'EPSG:3857',
url: '/reports/tiles/'+purchase_id+'/'+zone+'/'+labelDate+'/{z}/{x}/{-y}.png',
tilePixelRatio: 2,
minZoom: 9,
maxZoom: 14
})
});
imagelayer = xyz;
map.addLayer(xyz);
$.ajax({
type: 'POST',
dataType: "json",
data: {'purchase_id': purchase_id, 'report': zone, 'date': labelDate},
url: '/reports/tiles/tileinfo',
success: function (data) {
var extent = ol.proj.transformExtent(data.boundingBox, 'EPSG:4326', 'EPSG:3857');
map.getView().fit(extent, {duration: 800})
},
error: function(data) {
console.error("request error: ", {'msg': 'tile info request failed'});
}
});
}
......@@ -13,9 +13,6 @@ var reportImg = activePoints[0];
// mostrar imagen al dar click en los puntos
document.getElementById("myChart").onclick = function (evt) {
if (slider != false) {
deleteComparisons()
}
stop();
console.log("on click")
......@@ -32,6 +29,7 @@ document.getElementById("myChart").onclick = function (evt) {
//console.log(firstPoint)
//console.log(firstPoint._datasetIndex) //indice de la clase a la que pertenece (vegetación, agua, etc.)
var label = myChart.data.labels[firstPoint._index];
addImageLayer(label)
console.log("label: ")
console.log(label)
//console.log(myChart.legend.legendItems[firstPoint._datasetIndex].text) //nombre de la capa a la que pertenece (vegetación, agua, etc.)
......@@ -44,8 +42,6 @@ document.getElementById("myChart").onclick = function (evt) {
});
var imagePoint = activePoints[imageNumber];
oldLabel = label.slice(0, 4) + "/" + label.slice(4, 6) + "/" + label.slice(6);
document.getElementById("satImageSecond").src = "../../static/reports/tmpImages/repsat_test_dev/" + image_path + label + "_TCI_60m.jpg"
updateImage(imagePoint);
//updateImage(firstPoint);
//alert("{{ IMAGE_PATH }}"+label+"_TCI_60m.jpg");
......@@ -62,10 +58,6 @@ function play() {
// $(".next").hide();
// $(".prev").hide();
// $("#showImage").addClass('col-lg-offset-1');
if (slider == false) {
document.getElementById("titleMap").innerHTML = oldLabel + " vs " + oldLabel;
initComparisons()
}
playImages = setInterval(function () { next(); }, 4000);
}
......@@ -79,8 +71,13 @@ function scl_on(imagePoint) {
// $(".prev").show();
}
function scl_stop() {
console.log("scl off!!")
function open_big_image(image) {
console.log("Opening big image")
console.log("image:")
console.log(image)
image_big = image.replace("/thumbnails", "");
console.log(image_big)
window.open(image_big)
// $(".next").show();
// $(".prev").show();
}
......@@ -128,11 +125,8 @@ function updateImage(imagePoint) {
label = imagePoint;
reportImg = imagePoint;
titleLabel = label.slice(0, 4) + "/" + label.slice(4, 6) + "/" + label.slice(6);
if (slider != false) {
document.getElementById("titleMap").innerHTML = oldLabel + " vs " + titleLabel;
}else{
document.getElementById("titleMap").innerHTML = titleLabel;
}
document.getElementById("titleSCL").innerHTML = titleLabel
document.getElementById("satImage").src = "../../static/reports/tmpImages/repsat_test_dev/" + image_path + label + "_TCI_60m.jpg"
......@@ -174,11 +168,11 @@ function change(newType) {
let img, imgWidth=0, slider=false, clicked=0;
function initComparisons() {
$("#showSecondImage").show()
setTimeout(function() {
// $("#showSecondImage").show()
// setTimeout(function() {
img = document.getElementsByClassName("img-comp-overlay")[0];
compareImages(img);
});
//});
// setTimeout(function(){
// img = document.getElementsByClassName("img-comp-overlay")[0];
// compareImages(img);
......@@ -194,7 +188,7 @@ function compareImages(img) {
img.style.width = ((imgWidth / 2)) + 15 + "px";
/*create slider:*/
slider = document.createElement("DIV");
slider.setAttribute("class", "img-comp-slider col-lg-offset-1 col-md-offset-1 col-xs-offset-2");
slider.setAttribute("class", "img-comp-slider col-lg-offset-2 col-md-offset-2 col-xs-offset-2");
/*insert slider*/
img.parentElement.insertBefore(slider, img);
/*position the slider in the middle:*/
......@@ -265,9 +259,44 @@ function deleteComparisons(){
window.removeEventListener("mousemove", slideMove);
window.removeEventListener("touchmove", slideMove);
$(".img-comp-slider").remove();
$("#showSecondImage").hide()
slider= false;
}
//deleteComparisons();
//initComparisons();
function selectImage1(date, element) {
$("#imageListFirst li").removeClass("active");
element.classList.add("active");
let label = date.toString();
label = label.slice(0, 4) + "/" + label.slice(4, 6) + "/" + label.slice(6);
document.getElementById("titleImageFirst").innerHTML = label;
document.getElementById("satImageFirst").src = "../../static/reports/tmpImages/repsat_test_dev/" + image_path + date + "_TCI_60m.jpg"
}
function selectImage2(date,element) {
$("#imageListSecond li").removeClass("active");
element.classList.add("active");
let label = date.toString();
label = label.slice(0, 4) + "/" + label.slice(4, 6) + "/" + label.slice(6);
document.getElementById("titleImageSecond").innerHTML = label;
document.getElementById("satImageSecond").src = "../../static/reports/tmpImages/repsat_test_dev/" + image_path + date + "_TCI_60m.jpg"
}
$('.nav-tabs a').on('shown.bs.tab', function (evt) {
let tab = $(evt.target).text();
if(tab == "Comparison"){
initComparisons()
}
});
$('.nav-tabs a').on('hide.bs.tab', function (evt) {
let tab = $(evt.target).text();
if (tab == "Comparison") {
deleteComparisons();
}
if (tab == "Images") {
stop();
}
});
......@@ -5,6 +5,8 @@
<link rel="stylesheet" href="{% static 'catalog/css/body.css' %}" type="text/css">
<link rel="stylesheet" href="{% static 'reports/css/scldata.css' %}" type="text/css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://cdn.rawgit.com/openlayers/openlayers.github.io/master/en/v5.3.0/css/ol.css" type="text/css">
<script src="https://cdn.rawgit.com/openlayers/openlayers.github.io/master/en/v5.3.0/build/ol.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.19/css/jquery.dataTables.min.css"/>
<script type="text/javascript" src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script>
{% endblock %}
......@@ -160,7 +162,7 @@
</div>
<div class="box-body">
<div id="openchart" class="chart">
<canvas id="myChart" style="height: 574px"></canvas>
<canvas id="myChart" style="height: 594px"></canvas>
</div>
</div>
<!-- /.box-body -->
......@@ -171,91 +173,125 @@
</div>
<!-- /.col (LEFT) -->
<div class="col-md-4">
<!-- ****************** Imagen satelital -->
<div class="nav-tabs-custom" id="tabs">
<ul class="nav nav-tabs">
<li ><a href="#images" data-toggle="tab">Images</a></li>
<li><a href="#compared" data-toggle="tab">Comparison</a></li>
<li><a href="#classification" data-toggle="tab">SCL</a></li>
<li class="active"><a href="#map" data-toggle="tab">Map</a></li>
</ul>
<div class="tab-content" style="padding: 0px">
<div class="tab-pane" id="images">
<div class="box box-danger">
<div class="box-header with-border">
<div class="pull-left">
<button type="button" id="play" class="btn btn-block btn-primary btn-xs" style=""
onclick="play()">
<button type="button" id="play" class="btn btn-block btn-primary btn-xs" style="" onclick="play()">
<i class="fa fa-play"></i> Play
</button>
<button type="button" id="stop" class="btn btn-block btn-primary btn-xs"
style="display: none; margin: 0px;" onclick="stop()">
<button type="button" id="stop" class="btn btn-block btn-primary btn-xs" style="display: none; margin: 0px;"
onclick="stop()">
<i class="fa fa-stop"></i> Stop
</button>
</div>
<!-- <h3 class="box-title" id="titleMap">{{dafaultLabel}} - {{defaultDataSet}}</h3> -->
<h3 class="box-title" id="titleMap" style="margin-left: -40px;">{{ defaultDataSet }}</h3>
<div class="box-tools pull-right">
<button type="button" class="btn btn-box-tool" data-widget="collapse"><i
class="fa fa-minus"></i>
</button>
<!-- <button type="button" class="btn btn-box-tool" data-widget="remove" onclick="stop()"><i
class="fa fa-times"></i></button> -->
</div>
<div class="box-body">
<div class="row img-comp-container">
<div class="col-lg-10 col-md-9 col-xs-10 col-lg-offset-1 col-md-offset-1 col-xs-offset-2"
style="padding: 0px 0px 0px 42px;">
<img onclick="open_big_image(this.src)" width="375" id="satImage" src="../../static/reports/tmpImages/repsat_test_dev/{{ IMAGE_PATH }}{{ dafaultLabel }}_TCI_60m.jpg"
style="margin-left: auto; margin-right: auto; display: block;">
</div>
</div>
</div>
<!-- /.box-body -->
</div>
</div>
<!-- /.tab-pane -->
<div class="tab-pane" id="compared">
<div class="box box-danger">
<div class="box-header with-border">
<h3 class="box-title" id="titleImageFirst">{{ defaultDataSet }}</h3>
<h3 class="box-title"> vs </h3>
<h3 class="box-title" id="titleImageSecond">{{ defaultDataSet }}</h3>
</div>
<div class="box-body">
<div class="row img-comp-container">
<div class="col-lg-1 col-md-1 col-xs-1 prev" style="display: none">
<i class="glyphicon glyphicon-chevron-left" onclick="prev()"></i>
<div class="col-lg-3 col-md-2 col-xs-2 listImg">
<label>Image 1</label>
<div class="list">
<ul id="imageListFirst">
{% for label in labels %}
{% if label == labels.0 %}
<li class="active" onclick="selectImage1({{label}}, this)">{{ label }}</li>
{% else %}
<li onclick="selectImage1({{label}}, this)">{{ label }}</li>
{% endif %}
{% endfor %}
</ul>
</div>
<label>Image 2</label>
<div class="list">
<ul id="imageListSecond">
{% for label in labels %}
{% if label == labels.1 %}
<li class="active" onclick="selectImage2({{label}}, this)">{{ label }}</li>
{% else %}
<li onclick="selectImage2({{label}}, this)">{{ label }}</li>
{% endif %}
{% endfor %}
</ul>
</div>
<div class="col-lg-10 col-md-9 col-xs-10 col-lg-offset-1 col-md-offset-1 col-xs-offset-2 img-comp-img" id="showImage" style="padding: 0px 0px 0px 30px;">
<!-- <img onclick="window.open(this.src)" id="satImage" src="../../static/reports/tmpImages/repsat_test_dev/{{ IMAGE_PATH }}{{ dafaultLabel }}_TCI_60m.jpg"
style="margin-left: auto; margin-right: auto; display: block;"> -->
<img onclick="window.open(this.src)" width="375" id="satImage" src="../../static/reports/tmpImages/repsat_test_dev/{{ IMAGE_PATH }}{{ dafaultLabel }}_TCI_60m.jpg"
style="margin-left: auto; margin-right: auto; display: block;">
</div>
<div class="col-lg-10 col-md-9 col-xs-10 col-lg-offset-1 col-md-offset-1 col-xs-offset-2 img-comp-img img-comp-overlay" id="showSecondImage" style="padding: 0px 0px 0px 30px; display: none">
<!-- <img onclick="window.open(this.src)" id="satImage" src="../../static/reports/tmpImages/repsat_test_dev/{{ IMAGE_PATH }}{{ dafaultLabel }}_TCI_60m.jpg"
style="margin-left: auto; margin-right: auto; display: block;"> -->
<img onclick="window.open(this.src)" width="375" id="satImageSecond" src="../../static/reports/tmpImages/repsat_test_dev/{{ IMAGE_PATH }}{{ dafaultLabel }}_TCI_60m.jpg"
<div class="col-lg-10 col-md-9 col-xs-10 col-lg-offset-2 col-md-offset-1 col-xs-offset-2 img-comp-img" id="showImage"
style="padding: 0px 0px 0px 42px;">
<img onclick="open_big_image(this.src)" width="375" id="satImageSecond" src="../../static/reports/tmpImages/repsat_test_dev/{{ IMAGE_PATH }}{{labels.1}}_TCI_60m.jpg"
style="margin-left: auto; margin-right: auto; display: block;">
</div>
<div class="col-lg-1 col-md-1 col-xs-1 next" style="display: none">
<i class="glyphicon glyphicon-chevron-right" onclick="next()"></i>
<div class="col-lg-10 col-md-9 col-xs-10 col-lg-offset-2 col-md-offset-1 col-xs-offset-2 img-comp-img img-comp-overlay"
id="showSecondImage" style="padding: 0px 0px 0px 42px;">
<img onclick="open_big_image(this.src)" width="375" id="satImageFirst" src="../../static/reports/tmpImages/repsat_test_dev/{{ IMAGE_PATH }}{{labels.0}}_TCI_60m.jpg"
style="margin-left: auto; margin-right: auto; display: block;">
</div>
</div>
</div>
<!-- /.box-body -->
</div>
<!-- *********************** FIN imagen satelital ******************-->
<!-- ************************ SCL **********************-->
</div>
<!-- /.tab-pane -->
<div class="tab-pane" id="classification">
<div class="box box-danger">
<div class="box-header with-border">
<h3 class="box-title" id="titleMap">Scene Classification Map - {{ defaultDataSet }}</h3>
<h3 class="box-title" >Scene Classification Map - </h3>
<h3 class="box-title" id="titleSCL">{{ defaultDataSet }}</h3>
<div class="box-tools pull-right">
<!-- <div class="box-tools pull-right">
<button type="button" class="btn btn-box-tool" data-widget="collapse"><i
class="fa fa-minus"></i>
</button>
</div>
</div> -->
</div>
<div class="box-body">
<div class="row">
<div class="col-lg-1 col-md-1 col-xs-1 prev" style="display: none">
<i class="glyphicon glyphicon-chevron-left" onclick="prev()"></i>
</div>
<div class="col-lg-10 col-md-9 col-xs-10 col-lg-offset-1" id="showImageSCL" style="position: relative; height: 580px;">
<div class="col-lg-10 col-md-9 col-xs-10 col-lg-offset-1" id="showImageSCL" style="position: relative; height: 550px; padding: 0px 0px 0px 42px;">
<img onclick="window.open(this.src)" class="img-responsive" id="scl_saturated"
width="400px"
width="375"
height="400px" src="../../static/reports/tmpImages/repsat_test_dev/{{ SCL_PATH }}{{ dafaultLabel }}_SCL_60m_saturated.png"
style="position: absolute; top: 0; z-index:1;">
<img onclick="window.open(this.src)" class="img-responsive" id="scl_shadows"
width="400px"
width="375"
height="400px" src="../../static/reports/tmpImages/repsat_test_dev/{{ SCL_PATH }}{{ dafaultLabel }}_SCL_60m_shadows.png"
style="position: absolute; top: 0; z-index:1;">
<img onclick="window.open(this.src)" class="img-responsive" id="scl_cloud_shadows"
width="400px"
width="375"
height="400px" src="../../static/reports/tmpImages/repsat_test_dev/{{ SCL_PATH }}{{ dafaultLabel }}_SCL_60m_cloud_shadows.png"
style="position: absolute; top: 0; z-index:1;">
<img onclick="window.open(this.src)" class="img-responsive" id="scl_vegetation"
width="400px"
width="375"
height="400px" src="../../static/reports/tmpImages/repsat_test_dev/{{ SCL_PATH }}{{ dafaultLabel }}_SCL_60m_vegetation.png"
style="position: absolute; top: 0; z-index:1;">
<img onclick="window.open(this.src)" class="img-responsive" id="scl_not-vegetated"
width="400px"
width="375"
height="400px" src="../../static/reports/tmpImages/repsat_test_dev/{{ SCL_PATH }}{{ dafaultLabel }}_SCL_60m_not-vegetated.png"
style="position: absolute; top: 0; z-index:1;">
<img onclick="window.open(this.src)" class="img-responsive" id="scl_water"
......@@ -263,7 +299,7 @@
height="400px" src="../../static/reports/tmpImages/repsat_test_dev/{{ SCL_PATH }}{{ dafaultLabel }}_SCL_60m_water.png"
style="position: absolute; top: 0; z-index:1;">
<img onclick="window.open(this.src)" class="img-responsive" id="scl_unclassified"
width="400px"
width="375"
height="400px" src="../../static/reports/tmpImages/repsat_test_dev/{{ SCL_PATH }}{{ dafaultLabel }}_SCL_60m_unclassified.png"
style="position: absolute; top: 0; z-index:1;">
<img onclick="window.open(this.src)" class="img-responsive" id="scl_cloud_medium_probability"
......@@ -271,28 +307,40 @@
height="400px" src="../../static/reports/tmpImages/repsat_test_dev/{{ SCL_PATH }}{{ dafaultLabel }}_SCL_60m_cloud_medium_probability.png"
style="position: absolute; top: 0; z-index:1;">
<img onclick="window.open(this.src)" class="img-responsive" id="scl_cloud_high_probability"
width="400px"
width="375"
height="400px" src="../../static/reports/tmpImages/repsat_test_dev/{{ SCL_PATH }}{{ dafaultLabel }}_SCL_60m_cloud_high_probability.png"
style="position: absolute; top: 0; z-index:1;">
<img onclick="window.open(this.src)" class="img-responsive" id="scl_thin_cirrus"
width="400px"
width="375"
height="400px" src="../../static/reports/tmpImages/repsat_test_dev/{{ SCL_PATH }}{{ dafaultLabel }}_SCL_60m_thin_cirrus.png"
style="position: absolute; top: 0; z-index:1;">
<img onclick="window.open(this.src)" class="img-responsive" id="scl_snow"
width="400px"
width="375"
height="400px" src="../../static/reports/tmpImages/repsat_test_dev/{{ SCL_PATH }}{{ dafaultLabel }}_SCL_60m_snow.png"
style="position: absolute; top: 0; z-index:1;">
</div>
<div class="col-lg-1 col-md-1 col-xs-1 next" style="display: none">
<i class="glyphicon glyphicon-chevron-right" onclick="next()"></i>
</div>
</div>
<!-- /.box-body -->
</div>
</div>
<!-- /.tab-pane -->
<div class="tab-pane active" id="map">
<div class="box box-danger">
<div class="box-header with-border">
<h3 class="box-title">Map</h3>
</div>
<div class="box-body" style="max-height: 550px;">
<div id="minimap" style="height: 550px"></div>
</div>
<!-- /.box-body -->
</div>
<!-- ****************************** FIN SCL *********************** -->
<!-- /.box -->
</div>
<!-- /.tab-pane -->
</div>
<!-- /.tab-content -->
</div>
</div>
</div>
<!-- /.row -->
......@@ -397,6 +445,7 @@
let image_path = "{{IMAGE_PATH}}";
let scl_path = "{{SCL_PATH}}";
let zone = "{{ zone }}"
let purchase_id = "{{ purchaseID }}"
let platform = "{{ platform }}";
let productLevel = "{{ productLevel }}";
let startDate = "{{ startDate }}";
......@@ -418,4 +467,5 @@
</script>
<script type="text/javascript" src="{% static 'reports/js/reportImg.js' %}"></script>
<script type="text/javascript" src="{% static 'reports/js/reportPdf.js' %}"></script>
<script type="text/javascript" src="{% static 'reports/js/minimap.js' %}"></script>
{% endblock %}
......@@ -126,6 +126,15 @@
</span>
</a>
</li>
<li>
<a class="treeview " href="#" onclick="window.history.back();">
<i class="fa fa-backward"></i>
<span>Back</span>
<span class="pull-right-container">
<span class="label label-primary pull-right"></span>
</span>
</a>
</li>
</ul>
</div>
<!-- form-group-->
......
......@@ -10,6 +10,7 @@
</span>
</a>
</li>
<li class="treeview">
<a href="#">
<i class="fa fa-file-archive-o"></i>
......@@ -134,7 +135,25 @@
</span>
</a>
</li>
<li>
<a class="treeview submenu" href="../../static/reports/tmpImages/repsat_test_dev/{{ request.user.email }}/{{ purchaseID }}/{{ zone }}.pdf" id="downloadPdf">
<i class="fa fa-file-pdf-o"></i>
<span>Export to PDF v2</span>
<span class="pull-right-container">
<span class="label label-primary pull-right"></span>
</span>
</a>
</li>
</ul>
</li>
<li>
<a class="treeview " href="#" onclick="window.history.back();">
<i class="fa fa-backward"></i>
<span>Back</span>
<span class="pull-right-container">
<span class="label label-primary pull-right"></span>
</span>
</a>
</li>
</ul>
</div>
\ No newline at end of file
......@@ -8,5 +8,7 @@ urlpatterns = [
url(r'^(?P<purchase_id>(\d+))/(?P<report>[\w\-]+)$', views.report_L2ASCL, name='report'),
url(r'^$', views.Reports, name='reports'),
url(r'^ws/process_progress$', views.wsProcessProgress, name='wsProcessProgress'),
url(r'^tiles/(?P<purchase_id>(\d+))/(?P<report>[\w\-]+)/(?P<date>[0-9]+)/(?P<z>[0-9]+)/(?P<x>[0-9]+)/(?P<y>[0-9]+).png$',
views.tiles, name='tile'),
url(r'^tiles/tileinfo$', views.tileinfo, name='tileinfo'),
]
......@@ -3,12 +3,16 @@ from __future__ import unicode_literals
import json
import os
import xml.etree.ElementTree as ET
# Create your views here.
from collections import OrderedDict
from django.core.paginator import Paginator
from django.http import HttpResponse, Http404
from django.http import HttpResponse, Http404, JsonResponse
from django.shortcuts import render, render_to_response
from fpdf import FPDF
from django.views.decorators.csrf import csrf_exempt
from GeoInt_SIDT.tasks import add
from catalog.models import Purchase
......@@ -30,35 +34,47 @@ USERS_PATH = config['PATHS']['PATH_USERS']
def report_L2ASCL(request, report, purchase_id):
reporteDir = report.replace('_sclData', '')
path = USERS_PATH + request.user.email + '/' + purchase_id + '/'
if os.path.isfile(path + reporteDir + '.pdf'):
pass
else:
##########################################
# Generador de pdfs #
##########################################
PDFGenerator(path, reporteDir)
##########################################
# Generador de pdfs #
##########################################
image_path = request.user.email + "/" + purchase_id + "/" + "out/" + reporteDir + "/TCI/thumbnails/"
SCL_path = request.user.email + "/" + purchase_id + "/" + "out/" + reporteDir + "/SCL/"
reporteDir = report.replace('_sclData','')
image_path = request.user.email + "/" + purchase_id + "/" + "out/"+reporteDir+"/TCI/thumbnails/"
SCL_path = request.user.email + "/" + purchase_id + "/" + "out/"+reporteDir+"/SCL/"
print(image_path)
absolute_path = USERS_PATH + request.user.email + "/" + purchase_id + "/out"
folders = os.listdir(path=absolute_path)
json_route= USERS_PATH + request.user.email + "/" + purchase_id + "/"
folders = os.listdir(absolute_path)
json_route = USERS_PATH + request.user.email + "/" + purchase_id + "/"
for file in os.listdir(path=json_route):
for file in os.listdir(json_route):
if file.endswith("_sclData.json") and not file.endswith("merge_out_sclData.json"):
with open(USERS_PATH + request.user.email + "/" + purchase_id + "/" + file) as f:
json_data = OrderedDict(json.load(f))
if len(json_data)==0:
if len(json_data) == 0:
if file[:6] in folders:
folders.remove(file[:6])
with open(USERS_PATH + request.user.email + "/" + purchase_id + "/findProducts.json") as p:
dataProduct = json.load(p)
startDate = str(dataProduct['startDate'])[:4] +'-'+ str(dataProduct['startDate'])[4:6]+'-'+ str(dataProduct['startDate'])[6:8]
endDate = str(dataProduct['endDate'])[:4] +'-'+ str(dataProduct['endDate'])[4:6]+'-'+ str(dataProduct['endDate'])[6:8]
startDate = str(dataProduct['startDate'])[:4] + '-' + str(dataProduct['startDate'])[4:6] + '-' + str(
dataProduct['startDate'])[6:8]
endDate = str(dataProduct['endDate'])[:4] + '-' + str(dataProduct['endDate'])[4:6] + '-' + str(
dataProduct['endDate'])[6:8]
with open(USERS_PATH + request.user.email + "/" + purchase_id + "/" + report + ".json") as f:
json_data = OrderedDict(json.load(f))
if len(json_data)==0:
if len(json_data) == 0:
graphData = ""
defaultLabel=""
defaultDataset=""
defaultLabel = ""
defaultDataset = ""
folders.remove(reporteDir)
else:
......@@ -101,24 +117,32 @@ def report_L2ASCL(request, report, purchase_id):
graphData['data'] = data
label = graphData['data']['labels'][0]
defaultLabel = graphData['data']['labels'][0]
defaultDataset = label[0:4]+"/"+label[4:6]+"/"+label[6:]
#defaultDataset = graphData['data']['datasets'][0]['label']
defaultDataset = label[0:4] + "/" + label[4:6] + "/" + label[6:]
# defaultDataset = graphData['data']['datasets'][0]['label']
# print(settings.BASE_URL)
# graphData['options']['responsive']=True
# graphData['options']['maintainAspectRatio']=False
# print(json.dumps(graphData).encode("utf-8"))
return render(request, 'L2ASCL_data.html', {"graphData": json.dumps(graphData),"name":"foo", "report_name": "SCL Image Classification Data(Km²)", "startDate": startDate,"endDate": endDate,"clouds": dataProduct['clouds'], "platform": dataProduct['platform'],"productLevel": dataProduct['productLevel'] ,"IMAGE_PATH": image_path, "SCL_PATH" : SCL_path, 'dafaultLabel': defaultLabel, 'defaultDataSet': defaultDataset, "folders" : folders,"zone":reporteDir })
return render(request, 'L2ASCL_data.html', {"graphData": json.dumps(graphData), "name": "foo",
"report_name": "SCL Image Classification Data(Km²)",
"startDate": startDate, "endDate": endDate,
"clouds": dataProduct['clouds'], "platform": dataProduct['platform'],
"productLevel": dataProduct['productLevel'], "IMAGE_PATH": image_path,
"SCL_PATH": SCL_path, 'dafaultLabel': defaultLabel,
'defaultDataSet': defaultDataset, "folders": folders,
"zone": reporteDir, "purchaseID": purchase_id, "labels": graphData['data']['labels']})
# -------------------------------------------------------------------------------def Reports(request):
def Reports(request):
progress = 0
productList = []
size = 0
folders=[]
zip =""
folders = []
zip = ""
product_list = Purchase.objects.values('id', 'productList', 'aggreg_date', 'search__clouds', 'search__startDate',
'search__endDate', 'search__process_id__name', 'search__search_name').filter(
user_id=request.user.id, purchased=1)
......@@ -158,29 +182,29 @@ def Reports(request):
final_size = str(round(size, 2)) + " MB"
initial_folder = "."
absolute_path = USERS_PATH + request.user.email + "/" +str(producto['id'])+ "/out"
absolute_path = USERS_PATH + request.user.email + "/" + str(producto['id']) + "/out"
if not os.path.exists(absolute_path):
print("folder out noes not exists")
else:
folders = os.listdir(path=absolute_path)
print(folders)
if len(folders)==0:
initial_folder="../#"
folders = os.listdir(absolute_path)
if len(folders) == 0:
initial_folder = "../#"
else:
initial_folder = folders.pop(0)+"_sclData"
initial_folder = folders.pop(0) + "_sclData"
zip_path = USERS_PATH + request.user.email + "/" +str(producto['id'])
#print(zip_path)
zip_path = USERS_PATH + request.user.email + "/" + str(producto['id'])
# print(zip_path)
#"../ static / reports / tmpImages / repsat_test_dev / umorales @ centrogeo.edu.mx / "+str(producto['id']) / myzip.zip"
# "../ static / reports / tmpImages / repsat_test_dev / umorales @ centrogeo.edu.mx / "+str(producto['id']) / myzip.zip"
wkt = USERS_PATH + request.user.email + "/" + str(producto['id']) + "/findProducts.json"
with open(wkt, 'r') as jsonfile:
polygon = json.load(jsonfile)
for file in os.listdir(path=zip_path):
for file in os.listdir(zip_path):
if file.endswith(".zip"):
zip = zip_path+"/"+file
zip = zip_path + "/" + file
productList.append({
"search_name": producto['search__search_name'],
"process": producto['search__process_id__name'],
......@@ -192,8 +216,8 @@ def Reports(request):
"purchase_id": producto['id'],
"progress": progress,
"log_info": log,
"initial_folder" :initial_folder,
"zip" : zip,
"initial_folder": initial_folder,
"zip": zip,
"polygon": polygon['wkt'],
})
size = 0
......@@ -201,9 +225,8 @@ def Reports(request):
log_info = ""
progress = 0
initial_folder = ""
zip =""
wkt =""
zip = ""
wkt = ""
return render(request, 'Reports.html', {"productList": productList})
......@@ -215,7 +238,8 @@ def wsProcessProgress(request):
productList2 = []
product_list = Purchase.objects.values('id', 'productList', 'aggreg_date', 'search__clouds',
'search__startDate', 'search__endDate',
'search__process_id__name', 'progress').filter(user_id=request.user.id, purchased=1)
'search__process_id__name', 'progress').filter(user_id=request.user.id,
purchased=1)
for producto in product_list:
log_info = USERS_PATH + request.user.email + "/" + str(producto['id']) + "/L2ASCL_AreaProcessing.log"
......@@ -236,9 +260,9 @@ def wsProcessProgress(request):
if 'Finalizing...' in open(log_info).read():
progress = 100
#item = Purchase.objects.get(pk=producto['id'])
#item.progress = progress
#item.save()
# item = Purchase.objects.get(pk=producto['id'])
# item.progress = progress
# item.save()
productList2.append({
"purchase_id": producto['id'],
......@@ -259,9 +283,115 @@ def wsProcessProgress(request):
else:
raise Http404
# tiles
def tiles(request, purchase_id, report, date, z, x, y):
absolute_path = USERS_PATH + request.user.email + '/' + purchase_id + '/out'
tile_folder = '/' + report + '/tiles' + '/' + date + '_TCI_60m'
image = '/' + z + '/' + x + '/' + y + '.png'
image_path = absolute_path + tile_folder + image
if not os.path.exists(image_path):
# raise Http404
return HttpResponse(None, content_type="image/png")
image = open(image_path, "rb").read()
return HttpResponse(image, content_type="image/png")
# read a xml file with tiles info to display and return that info
@csrf_exempt
def tileinfo(request):
if request.is_ajax():
req = dict(request.POST)
absolute_path = USERS_PATH + request.user.email + '/' + req['purchase_id'][0] + '/out'
resource_path = '/' + req['report'][0] + '/tiles' + '/' + req['date'][0] + '_TCI_60m/tilemapresource.xml'
tree = ET.parse(absolute_path + resource_path)
bounding_box = tree.find('BoundingBox')
sets = [set.get('order') for set in tree.findall('TileSets/TileSet')]
origin = tree.find('Origin')
return JsonResponse({
'boundingBox': [
float(bounding_box.get('minx')),
float(bounding_box.get('miny')),
float(bounding_box.get('maxx')),
float(bounding_box.get('maxy'))
],
'zoom': {
'max': int(max(sets)),
'min': int(min(sets))
},
'origin': [float(origin.get('x')), float(origin.get('y'))],
'projection': tree.find('SRS').text
})
else:
raise Http404
# ------------------------------------------------------------------------
# def tareas():
# result = add.apply_async((2, 1), countdown=3)
# result.get()
# return render_to_response('reports_table.html', {"result": result.get()})
def PDFGenerator(path, reporteDir):
class PDF(FPDF):
def header(self):
#self.image('logo.jpg')
# Arial bold 15
self.set_font('Arial', 'B', 15)
# Move to the right
self.cell(80)
# Title
self.cell(30, 10, 'Title', 1, 0, 'C')
# Line break
self.ln(20)
def imagenes(self):
#################################################################################
# check https://developers.google.com/chart/image/docs/making_charts #
# check https://developers.google.com/chart/image/docs/chart_params#gcharts_cht #
# cht = type #
# chd = data values #
# chl = labels #
#################################################################################
url = "http://chart.apis.google.com/chart" \
"?cht=p3" \
"&chd=t:60,40" \
"&chs=500x200" \
"&chl=Hello|World" \
"&.png"
self.image(url)
# Arial bold 15
self.set_font('Arial', 'B', 15)
# Move to the right
self.cell(80)
# Title
self.cell(30, 10, 'Title', 1, 0, 'C')
# Line break
self.ln(20)
# Page footer
def footer(self):
# Position at 1.5 cm from bottom
self.set_y(-15)
# Arial italic 8
self.set_font('Arial', 'I', 8)
# Page number
self.cell(0, 10, 'Page ' + str(self.page_no()) + '/{nb}', 0, 0, 'C')
# Instantiation of inherited class
pdf = PDF()
pdf.alias_nb_pages()
pdf.add_page()
pdf.set_font('Times', '', 12)
for i in range(1, 5):
pdf.imagenes()
pdf.output(path + reporteDir + '.pdf', 'F')
\ No newline at end of file
......@@ -8,6 +8,7 @@
<script src="{% static 'js/Chart.min.js' %}"></script>
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.19/css/jquery.dataTables.min.css"/>
<script type="text/javascript" src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script>
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.7.2/css/all.css" integrity="sha384-fnmOCqbTlWIlj8LyTjo7mOUStjsKC4pOpQbqyi7RrhN7udi9RwhKkMHpvLbHG9Sr" crossorigin="anonymous">
{% endblock %}
{% block messages %}
......@@ -125,7 +126,6 @@
<li class="active">User profile</li>
</ol>
</section>
<section class="content">
<div class="row">
......@@ -136,137 +136,73 @@
<div class="col-md-9">
<div class="nav-tabs-custom">
<ul class="nav nav-tabs">
<li class="active"><a href="#activity" data-toggle="tab">Activity</a></li>
<!--li><a href="#timeline" data-toggle="tab">Timeline</a></li>
<li><a href="#settings" data-toggle="tab">Settings</a></li-->
<li class="active"><a href="#timeline" data-toggle="tab">Most Recent</a></li>
<li><a href="#stats" data-toggle="tab">Stats</a></li>
<!--li><a href="#settings" data-toggle="tab">Settings</a></li-->
</ul>
<div class="tab-content">
<div class="active tab-pane" id="activity">
<!-- Post -->
<div class="post">
<div class="user-block">
<img class="img-circle img-bordered-sm"
src="{% static 'users/images/user_default.png' %}"
alt="user image">
<span class="username">
<a href="#">Jonathan Burke Jr.</a>
<a href="#" class="pull-right btn-box-tool"><i class="fa fa-times"></i></a>
</span>
<span class="description">Shared publicly - 7:30 PM today</span>
</div>
<!-- /.user-block -->
<p>
Lorem ipsum represents a long-held tradition for designers,
typographers and the like. Some people hate it and argue for
its demise, but others ignore the hate as they create awesome
tools to help create filler text for everyone from bacon lovers
to Charlie Sheen fans.
</p>
</div>
<!-- /.post -->
<div class="tab-content" style="min-height: 668px;">
</div>
<!-- /.tab-pane -->
<div class="tab-pane" id="timeline">
<div class=" active tab-pane" id="timeline" style="overflow-y:auto; ">
<!-- The timeline -->
<ul class="timeline timeline-inverse">
{% for product in productList|slice:":4" %}
<!-- timeline time label -->
<li class="time-label">
<span class="bg-red">
10 Feb. 2014
{{ product.purchase_date }}
</span>
</li>
<!-- /.timeline-label -->
<!-- timeline item -->
<li>
<i class="fa fa-envelope bg-blue"></i>
<i class="fa fa-cart-arrow-down bg-green-active"></i>
<div class="timeline-item">
<span class="time"><i class="fa fa-clock-o"></i> 12:05</span>
<h3 class="timeline-header"><a href="#">Support Team</a> sent you an email</h3>
<span class="time">
{% if product.initial_folder != "." %}
Ready
{% else %}
In process
{% endif %}
</a>
</span>
<div class="timeline-body">
Etsy doostang zoodles disqus groupon greplin oooj voxy zoodles,
weebly ning heekya handango imeem plugg dopplr jibjab, movity
jajah plickers sifteo edmodo ifttt zimbra. Babblely odeo kaboodle
quora plaxo ideeli hulu weebly balihoo...
</div>
<div class="timeline-footer">
<a class="btn btn-primary btn-xs">Read more</a>
<a class="btn btn-danger btn-xs">Delete</a>
</div>
<h3 class="timeline-header no-border">You bought
<br>Process: <b>{{ product.process }}</b>
<br>Area: <b>{{ product.search_name }}</b>
<br>Size: <b>{{ product.size }}</b>
</h3>
</div>
</li>
<!-- END timeline item -->
<!-- timeline item -->
<li>
<i class="fa fa-user bg-aqua"></i>
<div class="timeline-item">
<span class="time"><i class="fa fa-clock-o"></i> 5 mins ago</span>
{% endfor %}
<h3 class="timeline-header no-border"><a href="#">Sarah Young</a> accepted your
friend request
</h3>
</div>
<li>
<i class="fa fa-clock-o bg-gray"></i>
</li>
<!-- END timeline item -->
<!-- timeline item -->
<!--li>
<i class="fa fa-comments bg-yellow"></i>
</ul>
<div class="timeline-item">
<span class="time"><i class="fa fa-clock-o"></i> 27 mins ago</span>
</div>
<!-- /.tab-pane -->
<h3 class="timeline-header"><a href="#">Jay White</a> commented on your post
</h3>
<div class="tab-pane" id="stats">
<div class="timeline-body">
Take me to your leader!
Switzerland is small and neutral!
We are more like Germany, ambitious and misunderstood!
<div class="chart">
<strong>Today {% now "jS F Y" %}</strong>
<!-- Sales Chart Canvas -->
<div>
<canvas id="salesChart" style="height: 142px; width: 814px;" width="814"
height="142"></canvas>
</div>
<div class="timeline-footer">
<a class="btn btn-warning btn-flat btn-xs">View comment</a>
</div>
<div>
<hr>
</div>
</li-->
<!-- END timeline item -->
<!-- timeline time label -->
<li class="time-label">
<span class="bg-green">
3 Jan. 2014
</span>
</li>
<!-- /.timeline-label -->
<!-- timeline item -->
<li>
<i class="fa fa-camera bg-purple"></i>
<div class="timeline-item">
<span class="time"><i class="fa fa-clock-o"></i> 2 days ago</span>
<h3 class="timeline-header"><a href="#">Mina Lee</a> uploaded new photos</h3>
<div class="container">
<h3 class="box-title" id="purchases_in">Purchases Per Month</h3>
<div id="mostrar">
<div class="timeline-body">
<img src="http://placehold.it/150x100" alt="..." class="margin">
<img src="http://placehold.it/150x100" alt="..." class="margin">
<img src="http://placehold.it/150x100" alt="..." class="margin">
<img src="http://placehold.it/150x100" alt="..." class="margin">
</div>
</div>
</li>
<!-- END timeline item -->
<li>
<i class="fa fa-clock-o bg-gray"></i>
</li>
</ul>
</div>
<!-- /.tab-pane -->
<div class="tab-pane" id="settings">
<form class="form-horizontal">
<div class="form-group">
......@@ -331,45 +267,12 @@
<!-- /.col -->
</div>
<!-- /.row -->
</section>
<!-- /.content -->
</div>
<footer class=" page-footer font-small special-color-dark pt-5" style="bottom: 0; position: absolute">
<!-- Footer Elements -->
<div class="container">
<!-- Social buttons
<ul class="list-unstyled list-inline text-center">
<li class="list-inline-item">
<a class="btn-floating btn-fb mx-1">
<i class="fa fa-faceboo"> </i>
</a>
</li>
<li class="list-inline-item">
<a class="btn-floating btn-tw mx-1">
<i class="fa fa-twitter"> </i>
</a>
</li>
<li class="list-inline-item">
<a class="btn-floating btn-gplus mx-1">
<i class="fa fa-google-plus"> </i>
</a>
</li>
<li class="list-inline-item">
<a class="btn-floating btn-li mx-1">
<i class="fa fa-linkedin"> </i>
</a>
</li>
<li class="list-inline-item">
<a class="btn-floating btn-dribbble mx-1">
<i class="fa fa-dribbble"> </i>
</a>
</li>
</ul>
<!-- Social buttons -->
</div>
<!-- Footer Elements -->
<section>
<footer class=" page-footer font-small special-color-dark pt-5">
<!-- Copyright -->
<div class="footer-copyright text-center py-3">© 2019 Copyright:
......@@ -379,6 +282,9 @@
</footer>
</section>
</div>
{% if messages %}
<div class="container col-md-2 col-lg-2 col-xs-2 col-sm-2" style="bottom: 0; right: 0;position: absolute">
{% for message in messages %}
......@@ -447,56 +353,6 @@
});
/*$(document).ready(function () {
var table = $('#example').DataTable
({
"ajax": data,
language:
{
"sProcessing": "Procesando...",
"sLengthMenu": "Mostrar _MENU_ registros",
"sZeroRecords": "No se encontraron resultados",
"sEmptyTable": "Ningún dato disponible en esta tabla",
"sInfo": "Mostrando registros del _START_ al _END_ de un total de _TOTAL_ registros",
"sInfoEmpty": "Mostrando registros del 0 al 0 de un total de 0 registros",
"sInfoFiltered": "(filtrado de un total de _MAX_ registros)",
"sInfoPostFix": "",
"sSearch": "Buscar:",
"sUrl": "",
"sInfoThousands": ",",
"sLoadingRecords": "Cargando...",
"oPaginate":
{
"sFirst": "Primero",
"sLast": "Último",
"sNext": "Siguiente",
"sPrevious": "Anterior"
},
"oAria":
{
"sSortAscending": ": Activar para ordenar la columna de manera ascendente",
"sSortDescending": ": Activar para ordenar la columna de manera descendente"
}
},
responsive:
{
details:
{
type: 'column',
target: 'tr'
}
},
columnDefs:
[{
className: 'control',
orderable: false,
targets: 0
}],
order: [1, 'asc']
});
});*/
// mostrar imagen al dar click en los puntos
document.getElementById("salesChart").onclick = function (evt) {
// activePoints = myChart.getElementsAtEvent(evt);
......@@ -511,44 +367,91 @@
$.ajax({
type: 'POST',
dataType: "json",
data: {'title': label},
url: '../administration/ws/report_table',
data: {'title': label, "user_id": $('#user_id').val()},
url: '../../users/ws/report_table',
success: function (data) {
console.log(data);
$('#mostrar').empty();
$('#mostrar').append("<table class=\"table table-hover\" id=\"example\">" +
"<thead>" +
"<tr>" +
"<th class=\"text-center\">User ID</th>" +
"<th class=\"text-center\">User</th>" +
"<th class=\"text-center\">E-Mail</th>" +
"<th class=\"text-center\">Purchases</th>" +
"<th class=\"text-center\">Storage</th>" +
"<th class=\"text-center\">Downloads in process</th>" +
"<th class=\"text-center\">Zone</th>" +
"<th class=\"text-center\">Process</th>" +
"<th class=\"text-center\">Purchase Date</th>" +
"<th class=\"text-center\">Start Date</th>" +
"<th class=\"text-center\">End Date</th>" +
"</tr>" +
"</thead>" +
"<tbody id=\"tbody\" class=\"text-center\">");
$.each(data, function (key, val) {
$("#tbody").append("<tr>" +
"<td>" + val['user_id'] + "</td>" +
"<td>" + val['username'] + "</td>" +
"<td>" + val['email'] + "</td>" +
"<td>" + val['purchases'] + "</td>" +
"<td>" + val['storage'] + "</td>" +
"<td>" + val['in_process'] + "</td>" +
"<td>" + val['search_name'] + "</td>" +
"<td>" + val['process'] + "</td>" +
"<td>" + val['purchase_date'] + "</td>" +
"<td>" + val['startDate'] + "</td>" +
"<td>" + val['endDate'] + "</td>" +
"</tr>"
);
});
$('#mostrar').append("</tbody>" +
"</table>");
$('#example').DataTable({});
$('#example').DataTable({"pageLength": 5});
}
});
};
var ctx = document.getElementById("salesChart").getContext('2d');
var myChart = new Chart(ctx, {
type: 'line',
data: {
labels: [
{% for dates in dates %}
"{{ dates.date }}",
{% endfor %}
],
datasets: [{
label: 'Sales',
data: [
{% for dates in dates %}
{{ dates.quantity }},
{% endfor %}
],
backgroundColor: [
'rgba(255, 99, 132, 0.2)',
'rgba(54, 162, 235, 0.2)',
'rgba(255, 206, 86, 0.2)',
'rgba(75, 192, 192, 0.2)',
'rgba(153, 102, 255, 0.2)',
'rgba(255, 159, 64, 0.2)'
],
borderColor: [
'rgba(255,99,132,1)',
'rgba(54, 162, 235, 1)',
'rgba(255, 206, 86, 1)',
'rgba(75, 192, 192, 1)',
'rgba(153, 102, 255, 1)',
'rgba(255, 159, 64, 1)'
],
borderWidth: 1
}]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
});
</script>
{% endblock %}
\ No newline at end of file
{% load staticfiles %}
{% for data in user_data %}
<div class="col-md-3">
<div class="col-md-3">
{% for data in user_data %}
<!-- Profile Image -->
<div class="box box-primary">
<div class="box-body box-profile">
<br>
<img class="profile-user-img img-responsive img-circle"
src="{% static 'users/images/user_default.png' %}"
alt="User profile picture">
<h3 class="profile-username text-center">{{ data.user_fullname }}</h3>
<input type="hidden" id="user_id" value="{{ data.user_id }}">
<p class="text-muted text-center">Software Engineer</p>
<ul class="list-group list-group-unbordered">
<li class="list-group-item">
<b>Searches</b> <a class="pull-right">{{ data.searches }}</a>
<i class="fa fa-search margin-r-5"></i> <b>Searches</b> <a
class="pull-right">{{ data.searches }}</a>
</li>
<li class="list-group-item">
<b>Purchases</b> <a class="pull-right">{{ data.purchases }}</a>
<i class="fa fa-shopping-cart margin-r-5"></i> <b>Purchases</b> <a
class="pull-right">{{ data.purchases }}</a>
</li>
<li class="list-group-item">
<b>In Process</b> <a class="pull-right">{{ data.in_process }}</a>
<i class="fa fa-download margin-r-5"></i> <b>In Process</b> <a
class="pull-right">{{ data.in_process }}</a>
</li>
<li class="list-group-item">
<i class="fa fa-pie-chart margin-r-5"></i> <b>Disk usage</b> <a
class="pull-right">{{ data.size }}</a>
</li>
</ul>
......@@ -28,48 +37,33 @@
<!-- /.box-body -->
</div>
<!-- /.box -->
{% endfor %}
<div>
<br>
</div>
<!-- About Me Box -->
<div class="box box-primary">
<div class="box-header with-border">
<h3 class="box-title">About Me</h3>
<h3 class="box-title">Searches</h3>
</div>
<!-- /.box-header -->
<div class="box-body">
<strong><i class="fa fa-book margin-r-5"></i> Education</strong>
<p class="text-muted">
B.S. in Computer Science from the University of Tennessee at Knoxville
</p>
<hr>
<strong><i class="fa fa-map-marker margin-r-5"></i> Location</strong>
<p class="text-muted">Malibu, California</p>
<hr>
<strong><i class="fa fa-pencil margin-r-5"></i> Skills</strong>
<p>
<span class="label label-danger">UI Design</span>
<span class="label label-success">Coding</span>
<span class="label label-info">Javascript</span>
<span class="label label-warning">PHP</span>
<span class="label label-primary">Node.js</span>
</p>
<hr>
<strong><i class="fa fa-file-text-o margin-r-5"></i> Notes</strong>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam fermentum enim neque.</p>
<ul class="list-group list-group-unbordered">
{% for data in user_searches %}
<li class="list-group-item">
<i class="fa fa-map-marker margin-r-5"></i> <b>{{ data.search_name }}</b> <a
class="pull-right">{{ data.count }}</a>
</li>
{% endfor %}
</ul>
</div>
<!-- /.box-body -->
</div>
<!-- /.box -->
</div>
{% endfor %}
\ No newline at end of file
<div><br></div>
</div>
......@@ -28,5 +28,14 @@
</span>
</a>
</li-->
<li>
<a class="treeview " href="#" onclick="window.history.back();">
<i class="fa fa-backward"></i>
<span>Back</span>
<span class="pull-right-container">
<span class="label label-primary pull-right"></span>
</span>
</a>
</li>
</ul>
</div>
\ No newline at end of file
......@@ -26,5 +26,6 @@ from users import views
urlpatterns = [
url(r'^$', views.Users, name='users'),
url(r'^(?P<user_id>(\d+))/$', views.User_id, name='user_id'),
url(r'^ws/report_table$', views.wsPurchasesPM, name='wsPurchasesPM'),
]
# + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
import calendar
import os
from django.contrib.auth.models import User
from django.db.models import Count
from django.http import HttpResponse, Http404
from django.shortcuts import render
# Create your views here.
import json
from django.views.decorators.csrf import csrf_exempt
from catalog.models import Search, Purchase
dirname = os.path.dirname(__file__)
configfile = os.path.join(dirname, '../config/config.json')
with open(configfile, 'r') as f:
config = json.load(f)
USERS_PATH = config['PATHS']['PATH_NAS']
PATH_USERS = config['PATHS']['PATH_USERS']
size_sentinel = 0
size_repsat = 0
# -------------------------------------------
def Users(request):
user_data = []
user_statics = []
user_searches = []
user = User.objects.get(pk=request.user.id)
searches = Search.objects.filter(user_id=user.id)
......@@ -15,39 +35,306 @@ def Users(request):
purchases = Purchase.objects.filter(user_id=user.id)
in_process = Purchase.objects.filter(user_id=user.id).exclude(progress=100)
bytes_size = 0
for path, directories, files in os.walk(USERS_PATH + "repsat_test_dev/" + user.email):
for filename in files:
bytes_size += os.lstat(os.path.join(path, filename)).st_size
for directory in directories:
bytes_size += os.lstat(os.path.join(path, directory)).st_size
bytes_size += os.path.getsize(USERS_PATH + "repsat_test_dev/" + user.email)
size_repsat = best_unit_size(bytes_size)
user_data.append({
"user_fullname": user.first_name+" "+user.last_name,
"user_id": user.id,
"user_fullname": user.first_name + " " + user.last_name,
"searches": searches.count(),
"purchases": purchases.count(),
"in_process": in_process.count(),
"size": size_repsat,
})
user_statics.append({
"user_fullname": user.first_name + " " + user.last_name,
"searches": searches.count(),
"purchases": purchases.count(),
"in_process": in_process.count(),
for search in Search.objects.values('search_name').filter(user_id=user.id).annotate(
count=Count('search_name')).order_by('-count')[:6]:
user_searches.append({
"search_name": search['search_name'],
"count": search['count'],
})
progress = 0
productList = []
size = 0
product_list = Purchase.objects.values('id', 'productList', 'aggreg_date', 'search__clouds', 'search__startDate',
'search__endDate', 'search__process_id__name', 'search__search_name').filter(
user_id=user.id, purchased=1).order_by('-aggreg_date')
for producto in product_list:
log_info = PATH_USERS + user.email + "/" + str(producto['id']) + "/L2ASCL_AreaProcessing.log"
#####################################################
# progress bar #
#####################################################
if os.stat(log_info).st_size == 0:
progress = 0
else:
if 'Linking Products...' in open(log_info).read():
progress = 20
if 'Merging Images...' in open(log_info).read():
progress = 40
if 'Deleting Images...' in open(log_info).read():
progress = 50
if 'Extracting SCL information...' in open(log_info).read():
progress = 60
if 'Finalizing...' in open(log_info).read():
progress = 100
with open(log_info, 'r') as myfile:
log = myfile.read().replace('\n', '')
for p in json.loads(producto['productList']):
size = size + float(p['info']['size'][:-3])
if size > 1000:
size2 = size / 1000
final_size = str(round(size2, 2)) + " GB"
else:
final_size = str(round(size, 2)) + " MB"
productList.append({
"search_name": producto['search__search_name'],
"process": producto['search__process_id__name'],
"purchase_date": producto['aggreg_date'],
"startDate": producto['search__startDate'],
"endDate": producto['search__endDate'],
"clouds": producto['search__clouds'],
"size": final_size,
"progress": progress,
"log_info": log,
})
size = 0
final_size = 0
log_info = ""
progress = 0
# lista de meses #
month_lst = [
{'quantity': 0, 'date': 'January'},
{'quantity': 0, 'date': 'February'},
{'quantity': 0, 'date': 'March'},
{'quantity': 0, 'date': 'April'},
{'quantity': 0, 'date': 'May'},
{'quantity': 0, 'date': 'June'},
{'quantity': 0, 'date': 'July'},
{'quantity': 0, 'date': 'August'},
{'quantity': 0, 'date': 'September'},
{'quantity': 0, 'date': 'October'},
{'quantity': 0, 'date': 'November'},
{'quantity': 0, 'date': 'December'}]
return render(request,'User_profile.html',{"user_data" : user_data} )
for date in Purchase.objects.filter(purchased=True, user_id=user.id).extra(
{'month': "Extract(month from aggreg_date)"}).values_list(
'month').annotate(Count('id')):
date_name = calendar.month_name[int(date[0])]
#----------------------------------------------------------------------
def User_id(request,user_id):
for month in month_lst:
if month['date'] == date_name:
month['quantity'] = date[1]
# print(month_lst)
return render(request, 'User_profile.html', {"user_data": user_data, "productList": productList, "dates": month_lst,
'user_searches': user_searches})
# ----------------------------------------------------------------------
def User_id(request, user_id):
user_data = []
user_searches = []
user = User.objects.get(pk=user_id)
searches = Search.objects.filter(user_id=user.id)
purchases = Purchase.objects.filter(user_id=user.id).order_by('aggreg_date')
purchases = Purchase.objects.filter(user_id=user.id)
in_process = Purchase.objects.filter(user_id=user.id).exclude(progress=100)
bytes_size = 0
for path, directories, files in os.walk(USERS_PATH + "repsat_test_dev/"+user.email):
for filename in files:
bytes_size += os.lstat(os.path.join(path, filename)).st_size
for directory in directories:
bytes_size += os.lstat(os.path.join(path, directory)).st_size
bytes_size += os.path.getsize(USERS_PATH + "repsat_test_dev/"+user.email)
size_repsat = best_unit_size(bytes_size)
user_data.append({
"user_fullname": user.first_name+" "+user.last_name,
"user_id": user.id,
"user_fullname": user.first_name + " " + user.last_name,
"searches": searches.count(),
"purchases": purchases.count(),
"in_process": in_process.count(),
"size": size_repsat,
})
for search in Search.objects.values('search_name').filter(user_id=user.id).annotate(
count=Count('search_name')).order_by('-count')[:6]:
user_searches.append({
"search_name": search['search_name'],
"count": search['count'],
})
progress = 0
productList = []
size = 0
product_list = Purchase.objects.values('id', 'productList', 'aggreg_date', 'search__clouds', 'search__startDate',
'search__endDate', 'search__process_id__name', 'search__search_name').filter(
user_id=user.id, purchased=1).order_by('-aggreg_date')
for producto in product_list:
log_info = PATH_USERS + user.email + "/" + str(producto['id']) + "/L2ASCL_AreaProcessing.log"
#####################################################
# progress bar #
#####################################################
if os.stat(log_info).st_size == 0:
progress = 0
else:
if 'Linking Products...' in open(log_info).read():
progress = 20
if 'Merging Images...' in open(log_info).read():
progress = 40
if 'Deleting Images...' in open(log_info).read():
progress = 50
if 'Extracting SCL information...' in open(log_info).read():
progress = 60
if 'Finalizing...' in open(log_info).read():
progress = 100
with open(log_info, 'r') as myfile:
log = myfile.read().replace('\n', '')
for p in json.loads(producto['productList']):
size = size + float(p['info']['size'][:-3])
if size > 1000:
size2 = size / 1000
final_size = str(round(size2, 2)) + " GB"
else:
final_size = str(round(size, 2)) + " MB"
productList.append({
"search_name": producto['search__search_name'],
"process": producto['search__process_id__name'],
"purchase_date": producto['aggreg_date'],
"startDate": producto['search__startDate'],
"endDate": producto['search__endDate'],
"clouds": producto['search__clouds'],
"size": final_size,
"progress": progress,
"log_info": log,
})
size = 0
final_size = 0
log_info = ""
progress = 0
# lista de meses #
month_lst = [
{'quantity': 0, 'date': 'January'},
{'quantity': 0, 'date': 'February'},
{'quantity': 0, 'date': 'March'},
{'quantity': 0, 'date': 'April'},
{'quantity': 0, 'date': 'May'},
{'quantity': 0, 'date': 'June'},
{'quantity': 0, 'date': 'July'},
{'quantity': 0, 'date': 'August'},
{'quantity': 0, 'date': 'September'},
{'quantity': 0, 'date': 'October'},
{'quantity': 0, 'date': 'November'},
{'quantity': 0, 'date': 'December'}]
for date in Purchase.objects.filter(purchased=True, user_id=user.id).extra(
{'month': "Extract(month from aggreg_date)"}).values_list(
'month').annotate(Count('id')):
date_name = calendar.month_name[int(date[0])]
for month in month_lst:
if month['date'] == date_name:
month['quantity'] = date[1]
# print(month_lst)
return render(request, 'User_profile.html', {"user_data": user_data, "productList": productList, "dates": month_lst,
'user_searches': user_searches})
# ---------------------------------------------------------
@csrf_exempt
def wsPurchasesPM(request):
if request.is_ajax():
table_data = []
data = Purchase.objects.values('user_id', 'search__endDate', 'search__startDate', 'aggreg_date',
'search__process_id__name', 'search__search_name').filter(
user_id=request.POST.get('user_id'), purchased=True,
aggreg_date__month=to_if(request.POST.get('title'))).order_by('aggreg_date')
for producto in data:
table_data.append({
"search_name": producto['search__search_name'],
"process": producto['search__process_id__name'],
"purchase_date": str(producto['aggreg_date'])[:10],
"startDate": str(producto['search__startDate'])[:10],
"endDate": str(producto['search__endDate'])[:10],
})
return HttpResponse(json.dumps(table_data))
# return HttpResponse({'table_data':table_data})
else:
raise Http404
# ----------------------------------------------------------------------
def to_if(name):
if name == "January":
return 1
elif name == "February":
return 2
elif name == "March":
return 3
elif name == "April":
return 4
elif name == "May":
return 5
elif name == "June":
return 6
elif name == "July":
return 7
elif name == "August":
return 8
elif name == "September":
return 9
elif name == "October":
return 10
elif name == "November":
return 11
elif name == "December":
return 12
else:
raise ValueError
# -----------------------------------------------
def best_unit_size(bytes_size):
"""
Obtenga un tamano en bytes y conviertalo en el mejor prefijo IEC para facilitar la lectura.
Devuelva un diccionario con tres pares de claves / valores:
"s" - (flotador) Tamano del camino convertido a la mejor unidad para una facil lectura
"u" - (str) El prefijo (IEC) para s (de bytes (2 ^ 0) a YiB (2 ^ 80))
"b" - (int / long) El tamano original en bytes
"""
for exp in range(0, 90, 10):
bu_size = abs(bytes_size) / pow(2.0, exp)
if int(bu_size) < 2 ** 10:
unit = {0: "bytes", 10: "KB", 20: "MB", 30: "GB", 40: "TB", 50: "PB",
60: "EB", 70: "ZB", 80: "YB"}[exp]
break
return str(round(bu_size, 2)) + " " + unit
return render(request,'User_profile.html',{"user_data" : user_data} )
\ No newline at end of file
# ------------------------------------------------
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment