Project

General

Profile

Download (6.64 KB) Statistics
| Branch: | Revision:

git_sitools_idoc / webstatDev / idoc_Maison / webstat / libChart4StatSitools2.py~ @ master

1
#!/usr/bin/env python
2
# -*-coding:utf-8-*-
3

    
4
import sys
5
try:
6
    import random
7
except BaseException:
8
    sys.exit("Import failed in module libStatSitools :\n\trandom module is required")
9
try:
10
    import cairo
11
except BaseException:
12
    sys.exit("Import failed in module libStatSitools :\n\tcairo module is required")
13
try:
14
    import pycha.pie as pie
15
except BaseException:
16
    sys.exit("Import failed in module libStatSitools :\n\tpycha module is required")
17
try:
18
    from datetime import datetime
19
except BaseException:
20
    sys.exit("Import failed in module libStatSitools :\n\tdatetime module is required")
21
try:
22
    import pygal
23
except BaseException:
24
    sys.exit("Import failed in module libStatSitools :\n\tpygal module is required")
25

    
26
from dateutil.relativedelta import relativedelta
27

    
28
home_base = "/home/marc/Projet/idoc_Maison"
29
url_png = "/static/chart/"
30

    
31
time_format_for_by_month = "%Y %m"
32

    
33

    
34
def pie_chart(colors_arg, dico_data, title_chart):
35

    
36
    dataset = create_dataset_from_data(dico_data)
37

    
38
    surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, 1000, 800)
39
    options = {
40
        'axis': {'labelColor': '#ffffff'},
41
        'legend': {'hide': False},
42
        'background': {
43
            'hide': False,
44
            'chartColor': '#ffffff'
45
        },
46
        'colorScheme': colors_arg,
47
        'title': title_chart,
48
    }
49
    chart = pie.PieChart(surface, options)
50
    chart.addDataset(dataset)
51
    chart.render()
52

    
53
    date = add_date()
54
    output = home_base+url_png+title_chart+date+'.png'
55
    tmp = url_png+title_chart+date+'.png'
56
    surface.write_to_png(output)
57
    return tmp
58

    
59

    
60
def random_colors():
61
    green_val = random.randint(80, 255)
62
    red_val = random.randint(20, (green_val - 5))
63
    blue_val = random.randint((red_val - 5), (red_val + 5))
64
    color_to_return = "#" + str(red_val) + str(green_val) + str(blue_val)
65
    return color_to_return
66

    
67

    
68
def add_title_chart(application, is_down_stat, is_access_stat, is_just_total_down, is_by_ips, is_by_user
69
                    , is_by_country, is_by_project, start_date, end_date):
70
    if is_down_stat:
71
        title_chart = "Downloads From "+str(application)
72
        if is_just_total_down:
73
            pass
74
        elif is_by_ips:
75
            title_chart += " By IPs"
76
        elif is_by_user:
77
            title_chart += " By Users"
78
        elif is_by_country:
79
            title_chart += " By Countries"
80
        elif is_by_project:
81
            title_chart += " By Projects"
82
    elif is_access_stat:
83
        title_chart = "Access From "+str(application)
84
    if start_date != "" and end_date != "":
85
        tmp = " Between %s and %s" % (str(start_date.split(" ")[0]), str(end_date.split(" ")[0]))
86
        title_chart += str(tmp)
87
    elif start_date != "" and end_date == "":
88
        tmp = " Since %s" % (str(start_date.split(" ")[0]))
89
        title_chart += str(tmp)
90
    return title_chart
91

    
92

    
93
def create_dataset_from_data(dico_data):
94
    graph_dataset = [(data, [[0, dico_data[data]]]) for data in dico_data]
95
    return graph_dataset
96

    
97

    
98
def add_date():
99
    now = datetime.now()
100
    tmp = str(now).split(" ")
101
    az = tmp[0].split("-")[0]+tmp[0].split("-")[1]+tmp[0].split("-")[2]+tmp[1].split(".")[0].split(":")[0]+tmp[1].\
102
        split(".")[0].split(":")[1]+tmp[1].split(".")[0].split(":")[2]+tmp[1].split(".")[1]
103
    return az
104

    
105

    
106
def svg_chart(dico_data, title_chart):
107

    
108
    pie_chart_pygal = pygal.Pie()
109
    pie_chart_pygal.title = title_chart
110
    date = add_date()
111

    
112
    url_output_svg = url_png+title_chart+date+".svg"
113

    
114
    for data in dico_data:
115
        pie_chart_pygal.add(data, dico_data[data])
116
    output_svg = home_base+url_output_svg
117
    try:
118
        pie_chart_pygal.render_to_file(output_svg)
119
    except BaseException, e:
120
        print 'In svg Exception : ', str(e)
121

    
122
    url_chart_png = png_chart(dico_data, title_chart)
123
    return [url_output_svg, url_chart_png]
124

    
125

    
126
def png_chart(dico_data, title_chart):
127

    
128
    pie_chart_pygal_png = pygal.Pie()
129
    pie_chart_pygal_png.title = title_chart
130
    
131
    date = add_date()
132
    url_output_png = url_png+title_chart+date+".png"
133
    for data in dico_data:
134
        pie_chart_pygal_png.add(data, dico_data[data])
135
    output_png = home_base+url_output_png
136
    try:
137
        pie_chart_pygal_png.render_to_png(output_png)
138
    except BaseException, e:
139
        print 'In PNG Exception : ', str(e)
140
    return url_output_png
141

    
142

    
143
def svg_bar_chart(dico_data, title_chart):
144

    
145
    dates_tmp_not_sorted = []
146
    dates_tmp_str_sorted = []
147
    dates_sorted = []
148
    for date in dico_data.keys():
149
        dates_tmp_not_sorted.append(str(date[1])+"/"+str(date[0]))
150

    
151
    for dd in sorted(dates_tmp_not_sorted, key=lambda d: map(int, d.split('/'))):
152
        dates_tmp_str_sorted.append(dd.split('/')[1]+"/"+dd.split('/')[0][2:])
153

    
154
    date_min = datetime.strptime(dates_tmp_str_sorted[0], "%m/%y")
155
    date_max = datetime.strptime(dates_tmp_str_sorted[len(dates_tmp_str_sorted)-1], "%m/%y")
156

    
157
    for i in range(0, int(diff_month(date_min, date_max)+1)):
158
        t = date_min+relativedelta(months=i)
159
        dates_sorted.append(t)
160
    dico_data2 = {}
161

    
162
    for x in dates_tmp_str_sorted:
163
        date_test = datetime.strptime(str(x), "%m/%y")
164
        dico_data2[date_test] = dico_data[(date_test.month, date_test.year)]
165

    
166
    list_tmp = []
167
    list_tmp2 = []
168
    list_tmp.append("Visits")
169

    
170
    bar_chart = pygal.DateY(x_label_rotation=90, human_readable=True, y_scale=1073741824)
171
    bar_chart.title = title_chart
172
    bar_chart.x_label_format = "%m/%Y"
173
    bar_chart.x_labels = dates_sorted
174
    try:
175
        for data in dates_sorted:
176
            if data not in dico_data2.keys():
177
                dico_data2[data] = 0
178
            list_tmp2.append((data, dico_data2[data]))
179
        list_tmp.append(list_tmp2)
180

    
181
        bar_chart.add(list_tmp[0],  (list_tmp[1][i] for i in range(0, len(list_tmp[1]))))
182
        bar_chart.show_legend = False
183
        date_svg = add_date()
184
        url_output_bar_chart_svg = url_png+"Bar_by_Month_"+date_svg+".svg"
185
        bar_chart.render_to_file(home_base+url_output_bar_chart_svg)
186
        url_output_bar_chart_png = url_bar_chart_png(list_tmp, dates_sorted, title_chart)
187
    except BaseException, e:
188
        print str(e)
189
    return [url_output_bar_chart_svg, url_output_bar_chart_png]
190

    
191

    
192
def url_bar_chart_png(list_data, dates, title):
193
    bar_chart = pygal.DateY(x_label_rotation=90)
194
    bar_chart.title = title
195
    bar_chart.x_label_format = "%m/%Y"
196
    bar_chart.x_labels = dates
197
    bar_chart.add(list_data[0],  (list_data[1][i] for i in range(0, len(list_data[1]))))
198
    # A METTRE POUR CREER LE PNG !
199
    bar_chart.print_values = False
200
    bar_chart.show_legend = False
201
    url_output_png = url_png+"Bar_by_Month_"+add_date()+".png"
202
    bar_chart.render_to_png(home_base+url_output_png)
203
    return url_output_png
204

    
205

    
206
def diff_month(d2, d1):
207
    return (d1.year - d2.year)*12 + d1.month - d2.month