Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Views tracking #142

Closed
wants to merge 41 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
41 commits
Select commit Hold shift + click to select a range
c186189
Testing
Apr 24, 2014
ccaec90
Increased timeout to capture visualization clearly
Apr 24, 2014
9382e00
Implemented Staic ImageLookup,fixed missing label issues in tree_map …
Apr 24, 2014
ebe1e62
Fix update_viz base url issue
benjaminleichter Apr 30, 2014
20d21d6
Updated previous_page conditions to include beta
benjaminleichter Apr 30, 2014
f74b012
Removed stray console.log()
benjaminleichter May 1, 2014
a11e9e9
Fixed highlight box overflow issue
benjaminleichter May 5, 2014
d4a11fe
Cleaning up directory
benjaminleichter May 5, 2014
12c6a3e
Merge pull request #114 from cid-harvard/highlight
benjaminleichter May 5, 2014
aa8daae
Fixed tour / spotlight buttons
benjaminleichter May 5, 2014
7b6b6d2
Adding d3plus 1.2.4
romsson May 6, 2014
bc1ef1a
Boilerplate for new app (ex: scatterplot)
romsson May 6, 2014
824d774
Progress on new scatterplot app
romsson May 6, 2014
ee4f953
implemented generate log files,input list of urls,export option and S…
May 7, 2014
3176a1e
Fixed #110
romsson May 7, 2014
b3866f9
Added placeholders for ranking app
romsson May 7, 2014
b0519de
Progress on ranking app
romsson May 7, 2014
f2263cd
Fixed footerInner overflow issue
benjaminleichter May 7, 2014
ae7b644
Progress on rankings app
romsson May 7, 2014
ccdf129
Merge pull request #126 from cid-harvard/footer
benjaminleichter May 7, 2014
420117f
First version of rankings
romsson May 7, 2014
854a6a7
Misc fixes for rankings
romsson May 7, 2014
e1c1b18
ungrouped viz buttons in trade flow tab
benjaminleichter May 7, 2014
7703424
Added space to TF viz buttons
benjaminleichter May 7, 2014
c5570f1
fixed #50 (menu margins)
benjaminleichter May 8, 2014
84721aa
Fixed #16
benjaminleichter May 8, 2014
c05874f
Restored body background color
benjaminleichter May 9, 2014
5a8d86f
Add icons for #120 and fixed #128
benjaminleichter May 9, 2014
90263ec
Fixes #136
makmanalp May 9, 2014
dfee7b1
Merge branch '2digit_product_code_url_fix' into beta
makmanalp May 9, 2014
019f3da
Revert "Merge branch '2digit_product_code_url_fix' into beta"
makmanalp May 9, 2014
0e0ba33
Update html headers
romsson May 12, 2014
2f7bc1c
Progress on rankings
romsson May 12, 2014
3707ca8
Fixed #133 and adde new icons
benjaminleichter May 12, 2014
f3c6650
Re-fixed #31
romsson May 12, 2014
00c22b9
Merge branch 'beta' into Phase2_Mindteck
makmanalp May 12, 2014
a9a8c16
Progress on scatterplot app
romsson May 13, 2014
45ee5a1
Updates
romsson May 13, 2014
2b5a78f
Replaced stacked_controls container
benjaminleichter May 13, 2014
92639c7
merge branch 'beta' into Phase2_Mindteck
romsson May 13, 2014
1beb7e3
Views tracking with redis, saves a timestamp, image url and title.
makmanalp May 14, 2014
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions django_files/atlas/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,7 @@ def render_to_response(self, context, **kwargs):
(r'^api/$', 'observatory.views.api'),
(r'^api/apps/$', 'observatory.views.api_apps'),
(r'^api/data/$', 'observatory.views.api_data'),
(r'^api/views/$', 'observatory.views.api_views'),

# Story #####
(r'^generate_png/$','observatory.views.generate_png'),
Expand Down
21 changes: 18 additions & 3 deletions django_files/manage.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,24 @@
#!/usr/bin/env python
import os, sys
#Importing optparse
import optparse


if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "atlas.settings")

parser = optparse.OptionParser("usage: %prog [options] arg1 arg2")
parser.add_option("-F", "--data-file", dest="filename",
default="None", type="string",
help="specify filename to run on")

(options, args) = parser.parse_args()
filename = options.filename

if filename != "None":
sys.argv[2] = filename

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "atlas.settings")

from django.core.management import execute_from_command_line
from django.core.management import execute_from_command_line

execute_from_command_line(sys.argv)
execute_from_command_line(sys.argv)
121 changes: 104 additions & 17 deletions django_files/observatory/management/commands/generate_svg.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,9 @@
from django.conf import settings
# App specific
from observatory.models import *
import logging
logger = logging.getLogger(__name__)
import optparse

# Setup the path constants

Expand Down Expand Up @@ -47,14 +50,16 @@ class Command( BaseCommand ):
help = 'Generate the JSON & SVG data for all permutations of the data set'

def handle(self, *args, **options):
# Setup the product classifications -> years mapping
#product_classifications = { "Sitc4": Sitc4_cpy.objects.values_list( "year", flat=True ).distinct().order_by( '-year' ),
# "Hs4": Hs4_cpy.objects.values_list( "year", flat=True ).distinct().order_by( '-year' ) }
product_classifications = { "Sitc4": [ 2010 ],

if args == ():
# Setup the product classifications -> years mapping
#product_classifications = { "Sitc4": Sitc4_cpy.objects.values_list( "year", flat=True ).distinct().order_by( '-year' ),
# "Hs4": Hs4_cpy.objects.values_list( "year", flat=True ).distinct().order_by( '-year' ) }
product_classifications = { "Sitc4": [ 2010 ],
"Hs4": [ 2010 ] }

# Get the different "Product Classifications" and loop over them
for p_classification, p_classification_years in product_classifications.items():
# Get the different "Product Classifications" and loop over them
for p_classification, p_classification_years in product_classifications.items():
# Debug
self.stdout.write( "Handling Product Classification: %s" % ( p_classification ) )
self.stdout.write( "\n" )
Expand Down Expand Up @@ -97,7 +102,7 @@ def handle(self, *args, **options):

# Setup the file name
file_name = app_name + "_" + language[0]['code'] + "_" + p_classification.lower() + "_" + trade_flow + "_" + country['name_3char'].lower() + "_" + product_file_bit + "_" + str( p_classification_year )

extra_store_file = "_" + language[0]['code'] + "_" + p_classification.lower() + "_" + trade_flow + "_" + country['name_3char'].lower() + "_" + product_file_bit + "_" + str( p_classification_year )
# We only want to do the below for data that doesn't already exist
if ( os.path.exists( settings.DATA_FILES_PATH + "/" + file_name + ".svg" ) is False ):
# Call the save_json and let it handle it at this point
Expand All @@ -113,22 +118,93 @@ def handle(self, *args, **options):

# Let us now remove the json file since we don't want it anymore
os.remove( settings.DATA_FILES_PATH + "/" + file_name + ".json" )
# Let us now remove the extra store file since we don't want it anymore
if extra_store_file:
os.remove( settings.DATA_FILES_PATH + "/" + extra_store_file + ".store" )
else:
# We have already generated the data for this permutation
self.stdout.write( 'There was a problem with retrieving the JSON data set. Skipping ...' )
self.stdout.write( "\n" )

logger.error("There was a problem with retrieving the JSON data set. Skipping ...")
# We should wait for a bit before the next one
time.sleep( 10 )
else:
# We have already generated the data for this permutation
self.stdout.write( 'Data already exists. Skipping ...' )
self.stdout.write( "\n" )
logger.info("Data already exists. Skipping ......")
#The script that generates the URLs should support a list of URL as input
else:
# Read the data from the file
file = open(args[0], "r")
url_file = file.read()
#Close file
file.close()
#Converting file-data to array
for url_list in url_file.split('\n'):
# Build the API JSON Data URL
api_url = url_list
#Setup the page url
page_url = url_list
# Debug
self.stdout.write( 'Processing API Request URL --> "%s"' % api_url )
self.stdout.write( "\n" )
try:
# Split the array to get the parts we want
full_url = url_list.split('explore/')
#Check Url valid or what
if full_url != ['']:
# Split the array to get the parts we want
url_and_session_parameters= full_url[1].split('/?')
if len(url_and_session_parameters) == 2:
# Split the array to get the parts we want
session_parameter = url_and_session_parameters[1].split('&')
# Split the array to get the parts we want
lang = session_parameter[0].split('=')
product_classification = session_parameter[1].split('=')
language = lang[1]
p_classification = product_classification[1]
else:
language = "en"
p_classification = "hs4"
# Split the array to get the parts we want
url_parameter= url_and_session_parameters[0].split('/')
app_name =url_parameter[0]
del url_parameter[0]
url_map = '_'.join(url_parameter)
# Setup the file name
file_name = app_name + "_" + language + "_" + p_classification + "_" + url_map
# We only want to do the below for data that doesn't already exist
if ( os.path.exists( settings.DATA_FILES_PATH + "/" + file_name + ".svg" ) is False ):
# Call the save_json and let it handle it at this point
return_code = self.save_json( api_url, file_name + ".json" )
# Check the return code before proceeding
if ( return_code is True ):
# Call the generate SVG method
self.save_svg( page_url, file_name + ".svg" )

# Let us break after one for now
#import sys
#sys.exit( 0 )

# Call the generate PNG method
self.save_png( file_name)

# Let us now remove the json file since we don't want it anymore
os.remove( settings.DATA_FILES_PATH + "/" + file_name + ".json" )
else:
# We have already generated the data for this permutation
self.stdout.write( 'There was a problem with retrieving the JSON data set. Skipping ...' )
self.stdout.write( "\n" )
logger.error('There was a problem with retrieving the JSON data set. Skipping ...')
# We should wait for a bit before the next one
time.sleep( 10 )
else:
# We have already generated the data for this permutation
self.stdout.write( 'Data already exists. Skipping ...' )
self.stdout.write( "\n" )
logger.info("Data already exists. Skipping ......")
except:
self.stdout.write( 'Invalid url format' )
self.stdout.write( "\n" )
logger.error("Invalid url format")

def save_json( self, api_url, file_name ):
# Wrap everything in a try block
try:
Expand All @@ -149,22 +225,27 @@ def save_json( self, api_url, file_name ):
# We seem to have run in to problems, degrade gracefully
self.stdout.write( "There was an URLLIB Error processing the HTTP request ..." )
self.stdout.write( "\n" )
logger.error("There was an URLLIB Error processing the HTTP request ...")
print exc
except httplib.HTTPException, exc:
# We seem to have run in to problems, degrade gracefully
self.stdout.write( "There was an HTTP Error processing the HTTP request ..." )
self.stdout.write( "\n" )
logger.error("There was an HTTP Error processing the HTTP request ...")
print exc
except IOError, exc:
# We seem to have run in to problems, degrade gracefully
self.stdout.write( "There was an IO Error processing the HTTP request ..." )
self.stdout.write( "\n" )
logger.error('There was an IO Error processing the HTTP request ...')
print exc

# Return false at this point, since we should not come here
return False

def save_svg( self, page_url, file_name ):

logger.info("Creating Visulization - " + file_name)
# Let us setup the phantomjs script arguments
phantom_arguments = [ settings.PHANTOM_JS_EXECUTABLE, settings.PHANTOM_JS_SCRIPT, settings.DATA_FILES_PATH + "/" + file_name, page_url ]

Expand All @@ -177,8 +258,13 @@ def save_svg( self, page_url, file_name ):
phantom_execute = Popen( phantom_arguments )

# Get the output data from the phantomjs execution
execution_results = phantom_execute.communicate()

try:
execution_results = phantom_execute.communicate()
return True
except:
self.stdout.write( "RunTime Error" )
self.stdout.write( "\n" )
return False
# Print the stdout data
print execution_results[0]

Expand Down Expand Up @@ -211,14 +297,13 @@ def save_svg( self, page_url, file_name ):

# Close the file now
svgFile.close()

def save_png( self, file_name ):
# Get the SVG data
svg_file = open( settings.DATA_FILES_PATH + "/" + file_name + ".svg", "r" )
svg_data = svg_file.read()

# Create the blank image surface
img = cairo.ImageSurface( cairo.FORMAT_ARGB32, 750, 480 )
img = cairo.ImageSurface( cairo.FORMAT_ARGB32, settings.EXPORT_IMAGE_WIDTH, settings.EXPORT_IMAGE_HEIGHT )

# Get the context
ctx = cairo.Context( img )
Expand All @@ -228,4 +313,6 @@ def save_png( self, file_name ):
handler.render_cairo( ctx )

# Create the final png image
final_png = img.write_to_png( settings.DATA_FILES_PATH + "/" + file_name + ".png" )
final_png = img.write_to_png( settings.DATA_FILES_PATH + "/" + file_name + ".png" )

logger.info("SVG and PNG Created")
23 changes: 17 additions & 6 deletions django_files/observatory/management/commands/store_static.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,8 @@
from django.conf import settings
# App specific
from observatory.models import *

import logging
logger = logging.getLogger(__name__)
# Create the store static command
class Command( BaseCommand ):
help = 'Generate the JSON & SVG data for provided url'
Expand Down Expand Up @@ -46,6 +47,8 @@ def handle(self, *args, **options):
os.remove( static_json_data )

def save_svg( self, page_url, file_name ):

logger.info("Creating Visulization - " + file_name)
# Let us setup the phantomjs script arguments
phantom_arguments = [ settings.PHANTOM_JS_EXECUTABLE, settings.PHANTOM_JS_SCRIPT, settings.DATA_FILES_PATH + "/" + file_name, page_url ]

Expand All @@ -58,10 +61,16 @@ def save_svg( self, page_url, file_name ):
phantom_execute = Popen( phantom_arguments )

# Get the output data from the phantomjs execution
execution_results = phantom_execute.communicate()

try:
execution_results = phantom_execute.communicate()
return True
except:
self.stdout.write( "RunTime Error" )
self.stdout.write( "\n" )
logger.error( "RunTime Error")
return False
# Print the stdout data
#print execution_results[0]
print execution_results[0]

# Wait until the SVG file is actually generated
while ( os.path.exists( settings.DATA_FILES_PATH + "/" + file_name ) != True ):
Expand Down Expand Up @@ -92,13 +101,13 @@ def save_svg( self, page_url, file_name ):

# Close the file now
svgFile.close()

def save_png( self, file_name ):
# Get the SVG data
svg_file = open( settings.DATA_FILES_PATH + "/" + file_name + ".svg", "r" )
svg_data = svg_file.read()
# Create the blank image surface
img = cairo.ImageSurface( cairo.FORMAT_ARGB32, 750, 480 )
img = cairo.ImageSurface( cairo.FORMAT_ARGB32, settings.EXPORT_IMAGE_WIDTH, settings.EXPORT_IMAGE_HEIGHT )

# Get the context
ctx = cairo.Context( img )
Expand All @@ -109,3 +118,5 @@ def save_png( self, file_name ):

# Create the final png image
final_png = img.write_to_png( settings.DATA_FILES_PATH + "/" + file_name + ".png" )

logger.info("SVG and PNG Created")
Loading