def crea_richiesta_supporto(request): if request.method == 'POST': form = RichiestaSupportoForm(data=request.POST) if form.is_valid(): pk = form.cleaned_data['id_richiesta'] imei = form.cleaned_data['imei'] playerId = form.cleaned_data['playerId'] fo = form.cleaned_data['forza_ordine'] richiestaMaster = Richiesta.objects.get(id=pk) subRichiesta = Richiesta(imei=imei, tipologia=richiestaMaster.tipologia, stato=Richiesta.CREATA, informazioni=richiestaMaster.informazioni, data=richiestaMaster.data, is_supporto=pk, linea_verde_richiesta=False, long=richiestaMaster.long, lat=richiestaMaster.lat, playerId=playerId, forza_ordine=fo) subRichiesta.save() allegati = Allegato.objects.filter(richiesta=richiestaMaster) for fl in allegati: tmp_file = io.BytesIO(fl.file.read()) tmp_file = ContentFile(tmp_file.getvalue()) tmp_file.name = get_file_name(fl.file.name) a = Allegato(file=tmp_file, richiesta=subRichiesta) a.save() response = push_to_nearest(subRichiesta.pk, subRichiesta.tipologia, subRichiesta.lat, subRichiesta.long, Richiesta.RICHIESTA_DA_FO_ALLEGATI) print(response) return HttpResponse(subRichiesta.serialize()) return HttpResponseForbidden()
def draw_graph(rules, rules_to_show): if (len(rules) < rules_to_show): rules_to_show = len(rules) plt.gcf().clear() G1 = nx.DiGraph() color_map = [] N = rules_to_show colors = np.random.rand(N) print(colors) strs = [ 'R0', 'R1', 'R2', 'R3', 'R4', 'R5', 'R6', 'R7', 'R8', 'R9', 'R10', 'R11' ] for i in range(rules_to_show): G1.add_nodes_from(["R" + str(i)]) for a in rules.iloc[i]['antecedents']: G1.add_nodes_from([a]) G1.add_edge(a, "R" + str(i), color=colors[0], weight=2) for c in rules.iloc[i]['consequents']: G1.add_nodes_from([c]) G1.add_edge("R" + str(i), c, color=colors[0], weight=2) for node in G1: found_a_string = False for item in strs: if node == item: found_a_string = True if found_a_string: color_map.append('yellow') else: color_map.append('green') edges = G1.edges() colors = [G1[u][v]['color'] for u, v in edges] weights = [G1[u][v]['weight'] for u, v in edges] pos = nx.spring_layout(G1, scale=1) nx.draw(G1, pos, edges=edges, node_color=color_map, edge_color=colors, width=weights, font_size=16, with_labels=False) for p in pos: # raise text positions pos[p][1] += 0.07 nx.draw_networkx_labels(G1, pos) plt.tight_layout() file4 = io.BytesIO() plt.savefig(file4) file4 = ContentFile(file4.getvalue()) return file4
def perform_image_crop(image_obj, crop_rect=None): img_ext = os.path.splitext(image_obj.name)[1][1:].upper() img_ext = 'JPEG' if img_ext == 'JPG' else img_ext if crop_rect is None: return image_obj image = BytesIO(image_obj.read()) base_image = Image.open(image) tmp_img, tmp_file = base_image.crop(crop_rect), BytesIO() tmp_img.save(tmp_file, format=img_ext) tmp_file = ContentFile(tmp_file.getvalue()) return uploadedfile.InMemoryUploadedFile(tmp_file, None, image_obj.name, image_obj.content_type, tmp_file.tell, None)
def save(self, name, content, save=True): new_content = six.StringIO() content.file.seek(0) thumb = Image.open(content.file) width, height = thumb.size if width > self.field.max_width or height > self.field.max_height: thumb.thumbnail(( self.field.max_width, self.field.max_height ), Image.ANTIALIAS) if self.field.use_thumbnail_aspect_ratio: img = Image.new("RGBA", (self.field.max_width, self.field.max_height), self.field.background_color) img.paste(thumb, ((self.field.max_width - thumb.size[0]) / 2, (self.field.max_height - thumb.size[1]) / 2)) else: img = thumb img_format = self.field.format if self.field.format else thumb.format quality = self.field.quality if self.field.quality else 85 info = img.info.copy() if img_format.upper() == 'JPEG': info['quality'] = quality if self.field.compression: info.update({'compression': self.field.compression}) if 'optimize' in info or 'progressive' in info: #HACK: иначе не сохраняет JPEG maxblock = ImageFile.MAXBLOCK ImageFile.MAXBLOCK = img.size[0] * img.size[1] img.save(new_content, format=img_format, **info) ImageFile.MAXBLOCK = maxblock else: img.save(new_content, format=img_format, **info) new_content = ContentFile(new_content.getvalue()) else: new_content = content super(ResizedImageFieldFile, self).save(name, new_content, save)
def get(self, request, *args, **kwargs): context = self.get_context_data(**kwargs) threshold = request.GET.get('parameter') percentage = float(request.GET.get('percentage')) support = float(request.GET.get('support')) nodes = int(request.GET.get('nodes')) # Read working file data and prepare transactions for # Apriori algorithm file = WFile.objects.get(pk=kwargs['pk']) store_data = pd.read_csv(file.file.path) columns = request.GET.getlist('selected') dataset = [] for _, row in store_data.iterrows(): aux = [] for c in columns: aux.append(c + '=' + row[c]) dataset.append(aux) # A priori algorithm apply: Extraction of frequent itemsets # and association rules oht = OnehotTransactions() oht_ary = oht.fit(dataset).transform(dataset) df = pd.DataFrame(oht_ary, columns=oht.columns_) frequent_itemsets = apriori(df, min_support=support, use_colnames=True) context['frequent_itemsets'] = frequent_itemsets rules = association_rules(frequent_itemsets, metric=threshold, min_threshold=percentage) # rules = association_rules(frequent_itemsets, metric="lift", min_threshold=0.2) context['rules'] = rules # Building of scatter plot of support vs. confidence support = rules.as_matrix(columns=['support']) confidence = rules.as_matrix(columns=['confidence']) for i in range(len(support)): support[i] = support[i] + 0.0025 * (random.randint(1, 10) - 5) confidence[i] = confidence[i] + 0.0025 * (random.randint(1, 10) - 5) plt.gcf().clear() plt.scatter(support, confidence, alpha=0.5, marker="*") plt.xlabel('support') plt.ylabel('confidence') plt.tight_layout() file1 = io.BytesIO() plt.savefig(file1) file1 = ContentFile(file1.getvalue()) # Building of histogram frequency_array = frequent_itemsets[frequent_itemsets['itemsets'].map( len) == 1] total_transactions = len(dataset) histogram_labels = [] histogram_frequency = [] for index, row in frequency_array.iterrows(): histogram_frequency.append(int(row['support'] * total_transactions)) histogram_labels.append(list(row['itemsets'])[0]) histogram_data = [] for i in range(len(histogram_labels)): histogram_data += [ histogram_labels[i] for x in range(histogram_frequency[i]) ] ##### # Create the plot ##### plt.gcf().clear() fig, ax = plt.subplots() # the histogram of the data n, bins, patches = ax.hist(histogram_data) # add a 'best fit' line ax.set_ylabel('Frequency') plt.xticks(histogram_labels, rotation=90, fontsize='x-small') # Tweak spacing to prevent clipping of ylabel fig.tight_layout() file2 = io.BytesIO() plt.savefig(file2) file2 = ContentFile(file2.getvalue()) # Building of heat plot # Convert the input into a 2D dictionary freqMap = {} for line in dataset: for item in line: if not item in freqMap: freqMap[item] = {} for other_item in line: if not other_item in freqMap: freqMap[other_item] = {} freqMap[item][other_item] = freqMap[item].get( other_item, 0) + 1 freqMap[other_item][item] = freqMap[other_item].get( item, 0) + 1 df = DataFrame(freqMap).T.fillna(0) ##### # Create the plot ##### plt.gcf().clear() plt.pcolormesh(df, edgecolors='black') plt.yticks(np.arange(0.5, len(df.index), 1), df.index, fontsize='x-small') plt.xticks(np.arange(0.5, len(df.columns), 1), df.columns, rotation=90, fontsize='x-small') plt.tight_layout() file3 = io.BytesIO() plt.savefig(file3) file3 = ContentFile(file3.getvalue()) # Draw graph for association rules file4 = draw_graph(rules, nodes) print(file1, file2, file3, file4) results = AssociationRules.objects.create() results.scatter.save('scatter.png', file1) results.histogram.save('histogram.png', file2) results.heat_map.save('heat_map.png', file3) results.graph.save('graph.png', file4) context['results'] = results return self.render_to_response(context)