<commit_before># import time
import os.path
from io import BytesIO
import base64
from collections import namedtuple
# import numpy as np
import pandas as pd
# import matplotlib.pyplot as plt
from flask import Blueprint, request, render_template, send_file, jsonify  # , make_response
from flask_wtf import csrf, FlaskForm as BaseForm
# from wtforms import SubmitField, StringField, BooleanField
# from wtforms.validators import DataRequired


class Bot(object):
	r""" Bot Class """

	def __init__(self):
		self.df = None

	def read(self, filename):
		if os.path.isfile('db/{}.csv'.format(filename)): # check if file exists
			try:
				self.df = pd.read_csv('db/{}.csv'.format(filename))  # read dataset file
				return self.df
			except Exception as e:
				print('Exception - read dataset:', str(e))
		return None

	def plot(self, format, col):
		r""" :type 1 = image, 2 = data"""
		if self.df is not None and col in self.df.columns:
			ploter = self.df[[col]].plot(figsize=(6, 4), fontsize=10)
			# fig, ax = plt.subplots(1)
			fig = ploter.get_figure()
			img = BytesIO()
			fig.savefig(img, format='png', dpi=100, transparent=True, edgecolor='k', bbox_inches='tight')  # facecolor='w'
			img.seek(0)
			if format == 1: return img
			if format == 2: return base64.b64encode(img.getvalue()).decode('UTF-8')
		return None

	def commands(self, line):
		# cmd = request.form['command']
		cmds = line.strip().split(' ') # .lower()
		print('cmds', cmds)

		if len(cmds) == 0:
			return None

		cmd = cmds[0].lower()
		rt = None

		try:
			if cmd == 'help':
				rt = """Available commands:<br />
				<code>load dataset_name</code> - load the dataset.<br />
				<code>ds info</code> - show the dataset information.<br />
				<code>plot column_name</code> - plot the dataset column.<br />
				<code>calc</code> - do a basic arithmetic operation.<br />
				"""

			if cmd == 'load':
				if self.read(cmds[1]) is not None:
					rt = 'Data Set (Rows, Columns): <code>' + str(self.df.shape) + '</code>'
				else:
					rt = 'Data Set doesn\'t exist.'

			if cmd == 'ds':
				if cmds[1] == 'info':
					if self.df is not None:
						rt = 'Data Set Summary:<pre><code>' + str(self.df.describe()) + '</code></pre></p>'
					else:
						rt = 'Load some dataset first: <code>load dataset_name</code>'

			if cmd == 'plot':
				data = self.plot(2, cmds[1])
				if data is not None:
					rt = '<img src="data:image/png;base64,{}" width="533" height="355" alt="Image Placeholder">'.format(data)
				else:
					rt = 'Sorry, this column <code>' + cmds[1] + '</code> doesn\'t exist.'

		except Exception as e:
			print('Exception - command:', str(e))
			rt = 'Sorry, this command syntax is wrong, check: <code>help</code>'

		finally:
			pass

		if cmd == 'calc':
			rt = str(eval(' '.join(cmds[1:])))

		if rt is None:
			rt = 'Sorry, I don\'t understand what you said, type: <code>help</code>'

		rt = '<img src="/static/img/dab.png" height="25"/>' \
				 '<div class="bubble"><code>&gt; ' + line + '</code><br /><br />' + rt + '</div>'

		return rt


bot = Bot()
pbbot = Blueprint('pbbot', __name__)


'''
@pbbot.route('/plot/<col>')
def plot(col): # http://0.0.0.0:5050/plot/Balance
	img = bot.plot(1, col)
	if img is not None:
		return send_file(img, mimetype='image/png')
'''

@pbbot.route('/echo/', methods=['GET'])
def echo():
	ret = {'value': bot.commands(request.args.get('echoValue'))}
	return jsonify(ret)


@pbbot.route('/bot/', methods=['GET', 'POST'])
@pbbot.route('/bot/<int:page>', methods=['GET', 'POST'])
def main(page=1):
	r"""   """
	rt = 'bot.html'
	error = None
	forml = 'bot.main'
	formf = None  # form_bot()
	run = None
	ntm = namedtuple('ntm', 'rt, error, forml, formf, run, df')
<commit_msg>Change Plot Image<commit_after># import time
import os.path
from io import BytesIO
import base64
from collections import namedtuple
# import numpy as np
import pandas as pd
# import matplotlib.pyplot as plt
from flask import Blueprint, request, render_template, send_file, jsonify  # , make_response
from flask_wtf import csrf, FlaskForm as BaseForm
# from wtforms import SubmitField, StringField, BooleanField
# from wtforms.validators import DataRequired


class Bot(object):
	r""" Bot Class """

	def __init__(self):
		self.df = None

	def read(self, filename):
		if os.path.isfile('db/{}.csv'.format(filename)): # check if file exists
			try:
				self.df = pd.read_csv('db/{}.csv'.format(filename))  # read dataset file
				return self.df
			except Exception as e:
				print('Exception - read dataset:', str(e))
		return None

	def plot(self, format, col):
		r""" :type 1 = image, 2 = data"""
		if self.df is not None and col in self.df.columns:
			ploter = self.df[[col]].plot(figsize=(6, 4), fontsize=10)
			# fig, ax = plt.subplots(1)
			fig = ploter.get_figure()
			img = BytesIO()
			fig.savefig(img, format='png', dpi=100, transparent=True, edgecolor='k', bbox_inches='tight')  # facecolor='w'
			img.seek(0)
			if format == 1: return img
			if format == 2: return base64.b64encode(img.getvalue()).decode('UTF-8')
		return None

	def commands(self, line):
		# cmd = request.form['command']
		cmds = line.strip().split(' ') # .lower()
		print('cmds', cmds)

		if len(cmds) == 0:
			return None

		cmd = cmds[0].lower()
		rt = None

		try:
			if cmd == 'help':
				rt = """Available commands:<br />
				<code>load dataset_name</code> - load the dataset.<br />
				<code>ds info</code> - show the dataset information.<br />
				<code>plot column_name</code> - plot the dataset column.<br />
				<code>calc</code> - do a basic arithmetic operation.<br />
				"""

			if cmd == 'load':
				if self.read(cmds[1]) is not None:
					rt = 'Data Set (Rows, Columns): <code>' + str(self.df.shape) + '</code>'
				else:
					rt = 'Data Set doesn\'t exist.'

			if cmd == 'ds':
				if cmds[1] == 'info':
					if self.df is not None:
						rt = 'Data Set Summary:<pre><code>' + str(self.df.describe()) + '</code></pre></p>'
					else:
						rt = 'Load some dataset first: <code>load dataset_name</code>'

			if cmd == 'plot':
				data = self.plot(2, cmds[1])
				if data is not None:
					#rt = '<img src="data:image/png;base64,{}" width="533" height="355" alt="Image Placeholder">'.format(data)
					rt = '<img src="/plot/{}" width="533" height="355" alt="Image Placeholder">'.format(cmds[1])
				else:
					rt = 'Sorry, this column <code>' + cmds[1] + '</code> doesn\'t exist.'

		except Exception as e:
			print('Exception - command:', str(e))
			rt = 'Sorry, this command syntax is wrong, check: <code>help</code>'

		finally:
			pass

		if cmd == 'calc':
			rt = str(eval(' '.join(cmds[1:])))

		if rt is None:
			rt = 'Sorry, I don\'t understand what you said, type: <code>help</code>'

		rt = '<img src="/static/img/dab.png" height="25"/>' \
				 '<div class="bubble"><code>&gt; ' + line + '</code><br /><br />' + rt + '</div>'

		return rt


bot = Bot()
pbbot = Blueprint('pbbot', __name__)


@pbbot.route('/plot/<col>')
def plot(col): # http://0.0.0.0:5050/plot/Balance
	img = bot.plot(1, col)
	if img is not None:
		return send_file(img, mimetype='image/png')


@pbbot.route('/echo/', methods=['GET'])
def echo():
	ret = {'value': bot.commands(request.args.get('echoValue'))}
	return jsonify(ret)


@pbbot.route('/bot/', methods=['GET', 'POST'])
@pbbot.route('/bot/<int:page>', methods=['GET', 'POST'])
def main(page=1):
	r"""   """
	rt = 'bot.html'
	error = None
	forml = 'bot.main'
	formf = None  # form_bot()
	run = None
	ntm = namedtuple('ntm', 'rt, error, forml, formf, run, df')

{'fraction_non_alphanumeric': 0.18367619556505477, 'fraction_numerical': 0.013759016831418648, 'mean_word_length': 3.4993990384615383, 'pattern_counts': {'":': 0, '<': 80, '<?xml version=': 0, '>': 80, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 2, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '1253409', 'n_tokens_mistral': 3047, 'n_tokens_neox': 2652, 'n_words': 751}