index int64 | repo_name string | branch_name string | path string | content string | import_graph string |
|---|---|---|---|---|---|
60,717 | ahmedbendev/Reclamation-Client | refs/heads/master | /requets/migrations/0011_auto_20190423_1328.py | # Generated by Django 2.2 on 2019-04-23 11:28
import datetime
from django.db import migrations, models
from django.utils.timezone import utc
class Migration(migrations.Migration):
dependencies = [
('requets', '0010_auto_20190422_1354'),
]
operations = [
migrations.AlterField(
model_name='requet',
name='pub_date',
field=models.DateTimeField(default=datetime.datetime(2019, 4, 23, 11, 28, 22, 477130, tzinfo=utc)),
),
]
| {"/manager/views.py": ["/manager/permissions.py", "/manager/forms.py", "/requets/models.py", "/users/models.py", "/manager/serializers.py"], "/requets/admin.py": ["/requets/models.py"], "/manager/serializers.py": ["/requets/models.py"], "/users/models.py": ["/requets/models.py"], "/requets/views.py": ["/users/forms.py", "/requets/forms.py", "/requets/models.py"], "/users/admin.py": ["/users/models.py"], "/users/views.py": ["/users/models.py", "/requets/models.py", "/users/forms.py", "/manager/forms.py"], "/requets/forms.py": ["/requets/models.py"], "/users/forms.py": ["/users/models.py"], "/manager/forms.py": ["/requets/models.py", "/users/models.py"]} |
60,718 | ahmedbendev/Reclamation-Client | refs/heads/master | /users/migrations/0010_auto_20190425_1440.py | # Generated by Django 2.2 on 2019-04-25 12:40
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('users', '0009_auto_20190425_1435'),
]
operations = [
migrations.AlterField(
model_name='address',
name='logement',
field=models.IntegerField(null=True),
),
]
| {"/manager/views.py": ["/manager/permissions.py", "/manager/forms.py", "/requets/models.py", "/users/models.py", "/manager/serializers.py"], "/requets/admin.py": ["/requets/models.py"], "/manager/serializers.py": ["/requets/models.py"], "/users/models.py": ["/requets/models.py"], "/requets/views.py": ["/users/forms.py", "/requets/forms.py", "/requets/models.py"], "/users/admin.py": ["/users/models.py"], "/users/views.py": ["/users/models.py", "/requets/models.py", "/users/forms.py", "/manager/forms.py"], "/requets/forms.py": ["/requets/models.py"], "/users/forms.py": ["/users/models.py"], "/manager/forms.py": ["/requets/models.py", "/users/models.py"]} |
60,721 | EpsAvlc/SECOND_ROS | refs/heads/master | /second/data/pcd_dataset.py | import os
import pcl
import numpy as np
from pathlib import Path
import concurrent.futures as futures
import pickle
import fire
from second.data.dataset import Dataset
class PCDDataset(Dataset):
"""
This class is designed for custom data in pcd form.
"""
NumPointFeatures = 4
def __init__(self, root_path, info_path=None, class_names=None,
prep_func=None,
num_point_features=None):
self.dataset_dir = root_path
self.dataset_len = len(os.listdir(root_path))
self._prep_func=prep_func
def __getitem__(self, idx):
input_dict = self.get_sensor_data(idx)
example = self._prep_func(input_dict=input_dict)
return example
def __len__(self):
return self.dataset_len
def get_sensor_data(self, query):
assert isinstance(query, int)
res = {
"lidar": {
"type": "lidar",
"points": None,
},
}
print(query)
filename = str(self.dataset_dir) + '/' +str(query)+ ".pcd"
pc = pcl.load_XYZI(filename)
points = []
for point in pc:
points.append([point[0], point[1], point[2], point[3]])
# print(points)
res["lidar"]["points"] = np.array(points)
print(res["lidar"]["points"].shape)
return res
def get_PCD_path(idx, prefix):
return str(prefix + (str(idx) + ".pcd"))
def get_PCD_info(path,
training=True,
label_info=True,
velodyne=False,
calib=False,
image_ids=7481,
extend_matrix=True,
num_worker=8,
relative_path=True,
with_imageshape=True):
root_path = Path(path)
if not isinstance(image_ids, list):
image_ids = list(range(image_ids))
def map_func(idx):
info = {}
pc_info = {'num_features': 3}
calib_info = {}
image_info = {'image_idx': idx}
annotations = None
if velodyne:
pc_info['velodyne_path'] = get_PCD_path(
idx, path)
info["image"] = image_info
info["point_cloud"] = pc_info
return info
with futures.ThreadPoolExecutor(num_worker) as executor:
image_infos = executor.map(map_func, image_ids)
return list(image_infos)
def create_PCD_info_file(data_path, save_path=None, relative_path=True):
print("Generate info. this may take several minutes.")
if save_path is None:
save_path = Path(data_path)
else:
save_path = Path(save_path)
PCD_infos_test = get_PCD_info(
data_path,
training=False,
label_info=False,
velodyne=True,
calib=False,
image_ids=len(os.listdir(data_path)),
relative_path=relative_path)
filename = save_path / 'pcd_infos_test.pkl'
print(f"Kitti info test file is saved to {filename}")
with open(filename, 'wb') as f:
pickle.dump(PCD_infos_test, f)
if __name__ == "__main__":
# dir = "/home/cm/Projects/deep_learning_projects/dataset/second_custom"
# dataset = PCDDataset(dir)
# print(dataset.get_sensor_data(3))
fire.Fire() | {"/second_ros/pcd_inferencer.py": ["/second/data/pcd_dataset.py"]} |
60,722 | EpsAvlc/SECOND_ROS | refs/heads/master | /second_ros/pcd_inferencer.py | from pathlib import Path
from google.protobuf import text_format
import torch
import pcl
import pickle
import numpy as np
from functools import partial
from second.protos import pipeline_pb2
from second.pytorch.builder import (box_coder_builder, input_reader_builder,
lr_scheduler_builder, optimizer_builder,
second_builder)
from second.data.pcd_dataset import PCDDataset
from second.pytorch.train import build_network, example_convert_to_torch
from second.data.preprocess import prep_pointcloud
from second.utils.config_tool import get_downsample_factor
from second.builder import dbsampler_builder
class pcd_inferencer():
def __init__(self, config_path, checkpoint_path):
self.dataset = PCDDataset
self.config_path = config_path
self.checkpoint_path = checkpoint_path
self.build_network()
prep_cfg = self.config.preprocess
dataset_cfg = self.config.dataset
model_config = self.config.model.second
num_point_features = model_config.num_point_features
out_size_factor = get_downsample_factor(model_config)
assert out_size_factor > 0
cfg = self.config
db_sampler_cfg = prep_cfg.database_sampler
db_sampler = None
if len(db_sampler_cfg.sample_groups) > 0: # enable sample
db_sampler = dbsampler_builder.build(db_sampler_cfg)
grid_size = self.net.voxel_generator.grid_size
# [352, 400]
feature_map_size = grid_size[:2] // out_size_factor
feature_map_size = [*feature_map_size, 1][::-1]
print("feature_map_size", feature_map_size)
assert all([n != '' for n in self.net.target_assigner.classes]), "you must specify class_name in anchor_generators."
self.prep_func = partial(
prep_pointcloud,
root_path=dataset_cfg.kitti_root_path,
voxel_generator=self.net.voxel_generator,
target_assigner=self.net.target_assigner,
training=False,
max_voxels=prep_cfg.max_number_of_voxels,
remove_outside_points=False,
remove_unknown=prep_cfg.remove_unknown_examples,
create_targets=False,
shuffle_points=prep_cfg.shuffle_points,
gt_rotation_noise=list(prep_cfg.groundtruth_rotation_uniform_noise),
gt_loc_noise_std=list(prep_cfg.groundtruth_localization_noise_std),
global_rotation_noise=list(prep_cfg.global_rotation_uniform_noise),
global_scaling_noise=list(prep_cfg.global_scaling_uniform_noise),
global_random_rot_range=list(
prep_cfg.global_random_rotation_range_per_object),
global_translate_noise_std=list(prep_cfg.global_translate_noise_std),
db_sampler=db_sampler,
num_point_features=3,
anchor_area_threshold=prep_cfg.anchor_area_threshold,
gt_points_drop=prep_cfg.groundtruth_points_drop_percentage,
gt_drop_max_keep=prep_cfg.groundtruth_drop_max_keep_points,
remove_points_after_sample=prep_cfg.remove_points_after_sample,
remove_environment=prep_cfg.remove_environment,
use_group_id=prep_cfg.use_group_id,
out_size_factor=out_size_factor)
def build_network(self):
cfg_path = Path(self.config_path)
ckpt_path = Path(self.checkpoint_path)
if not cfg_path.exists():
print("config file not exist.")
return
if not ckpt_path.exists():
print("ckpt file not exist.")
return
pass
self.config = pipeline_pb2.TrainEvalPipelineConfig()
with open(cfg_path, "r") as f:
proto_str = f.read()
text_format.Merge(proto_str, self.config)
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
self.net = build_network(self.config.model.second).to(device).float().eval()
if not ckpt_path.is_file():
raise ValueError("checkpoint {} not exist.".format(ckpt_path))
self.net.load_state_dict(torch.load(ckpt_path))
def get_pc_data(self, pcd_path):
res = {
"lidar": {
"type": "lidar",
"points": None,
},
}
pc = pcl.load(pcd_path)
points = []
for point in pc:
points.append([point[0], point[1], point[2]])
# print(points)
res["lidar"]["points"] = np.array(points)
print(res["lidar"]["points"].shape)
return res
def infer(self, pcd_path):
pc_data = self.get_pc_data(pcd_path)
# prep_func = partial(prep_func, anchor_cache=anchor_cache)
if __name__ == "__main__":
cfg_path = "/home/cm/Projects/deep_learning_projects/second.pytorch_v1.6/second/configs/car.fhd.config"
ckpt_path = "/home/cm/Projects/deep_learning_projects/second.pytorch_v1.6/second/models/voxelnet-15475.tckpt"
infer = pcd_inferencer(cfg_path, ckpt_path)
| {"/second_ros/pcd_inferencer.py": ["/second/data/pcd_dataset.py"]} |
60,724 | 123mayur/Serverless_AWS_APIEndpoint | refs/heads/main | /EC2_Start_Stop.py | import boto3
import json
def lambda_handler_start(event, context):
inputParams = json.loads(json.dumps(event))
sevice_Id =inputParams['id']
instances = [sevice_Id]
ec2 = boto3.client('ec2')
ec2.start_instances(InstanceIds=instances)
ec2.delete_tags(Resources=instances, Tags=[{'Key':'Schedule', 'Value':'True'}])
def lambda_handler_stop(event, context):
inputParams = json.loads(json.dumps(event))
sevice_Id =inputParams['id']
instances = [sevice_Id]
ec2 = boto3.client('ec2')
ec2.stop_instances(InstanceIds=instances)
ec2.delete_tags(Resources=instances, Tags=[{'Key':'Schedule', 'Value':'True'}])
| {"/app.py": ["/schedule_lambda.py"]} |
60,725 | 123mayur/Serverless_AWS_APIEndpoint | refs/heads/main | /schedule_lambda.py | import boto3
import json
import datetime
import calendar
from croniter import croniter
import pandas as pd
db = boto3.resource('dynamodb')
table = db.Table('Myapp')
def create_schedule(event):
payload = json.loads(json.dumps(event))
table.put_item(Item=payload)
return json.dumps({"message":"your schedule is created"})
def fetch_all():
response= table.scan()['Items']
return json.dumps(response)
def get_schedule(event):
key = json.loads(json.dumps(event))
responce = table.get_item(Key=key).get('Item')
if responce:
s_date = responce['s_date']
cron = croniter(s_date)
date = cron.get_next(datetime.datetime)
dates = pd.date_range(date, periods=5, freq='D')
mylist =[]
for x in dates:
days = calendar.day_name[x.weekday()]
mylist.append(days)
return json.dumps(mylist)
else:
return json.dumps({"message":"shedule not fount"})
def update_schedule(event):
payload = json.loads(json.dumps(event))
id = payload['id']
key ={'id':id}
attribute_updates = {key: {'Value': value, 'Action': 'PUT'}
for key, value in payload}
table.update_item(Key=key, AttributeUpdates=attribute_updates)
return json.dumps({"message":"successfull"})
def delete_schedule(event):
id = json.loads(json.dumps(event))
key = id
table.delete_item(Key=key)
return json.dumps({"message":"schedule is deleted"})
| {"/app.py": ["/schedule_lambda.py"]} |
60,726 | 123mayur/Serverless_AWS_APIEndpoint | refs/heads/main | /app.py | import json
from flask import request,json
from flask_lambda import FlaskLambda
import schedule_lambda
app = FlaskLambda(__name__)
@app.route('/')
def index():
return json_response({"message":"Hello Word"})
@app.route('/myapp',methods=['GET'])
def fetch_all():
if request.method == 'GET':
data = json.loads(schedule_lambda.fetch_all())
return json_response(data)
@app.route('/myapp',methods=['POST'])
def create_schedule():
if request.method == 'POST':
payload = request.get_json()
event=schedule_lambda.create_schedule(payload)
return json_response(event)
@app.route('/myapp/<id>',methods=['DELETE'])
def removes_schedule(id):
if request.method == 'DELETE':
payload = request.get_json(id)
event = schedule_lambda.delete_schedule(payload)
return json_response(event)
@app.route('/myapp/<id>', methods=['GET'])
def fetching_schedule(id):
if request.method == 'GET':
payload = request.get_json(id)
event = schedule_lambda.get_schedule(payload)
return json_response(event)
@app.route('/myapp/<id>',methods=['PATCH'])
def update_schedule(id):
if request.method == 'PATCH':
payload = request.json(id)
items = schedule_lambda.update_schedule(payload)
return json_response(items)
def json_response(data, response_code=200):
return json.dumps(data), response_code,{'Content-Type': 'application/json'}
def api_response():
from flask import jsonify
if request.method == 'POST':
return jsonify(**request.json)
if __name__ == '__main__':
app.run(debug=True) | {"/app.py": ["/schedule_lambda.py"]} |
60,761 | FelixDikland/Suducko | refs/heads/master | /main_sudoku.py | from skimage import io, color, measure, morphology, filters
from matplotlib import pyplot as plt
from skimage.feature import local_binary_pattern
import numpy as np
import math
from datetime import datetime
startTime = datetime.now()
def preprocess(image_path):
img = io.imread(image_path)
img = color.rgb2gray(img)
img = img - img.min()
img = img/img.max()
return img
def get_thresh(image, trh):
treshed = image < trh
treshed = np.array(treshed*1)
return treshed
def edges_binar(image):
strel = morphology.disk(1)
dilate = morphology.dilation(image, strel)
edges = dilate-image
return edges
def find_mid(image):
y = [sum(row)*idx for idx, row in enumerate(image)]
transposed = image.transpose()
x = [sum(row)*idx for idx, row in enumerate(transposed)]
total = sum(sum(image))
return sum(x)//total, sum(y)//total, [sum(row) for idx, row in enumerate(transposed)], [sum(row) for idx, row in enumerate(image)]
def check_orientation(image):
y = np.array([sum(row) for row in image if sum(row) > 0])
transposed = image.transpose()
x = np.array([sum(row) for row in transposed if sum(row) > 0])
x = np.convolve(x, np.ones(10)/10, mode = 'valid')
y = np.convolve(y, np.ones(10)/10, mode = 'valid')
y = y - y.min()
y = y / y.max()
x = x - x.min()
x = x / x.max()
std = np.std(x) + np.std(y)
if std <= 0.5:
return 1
else:
return 0
def find_edges(mid_x, mid_y, x, y, thresh):
min_x_upp = min(x[mid_x:])
x_upp = [value-min_x_upp for value in x[mid_x:]]
for idx, value in enumerate(x_upp):
if value < thresh:
x_edge_upp = idx+mid_x
break
min_x_low = min(x[mid_x::-1])
x_low = [value - min_x_low for value in x[mid_x::-1]]
for idx, value in enumerate(x_low):
if value < thresh:
x_edge_low = mid_x-idx
break
min_y_upp = min(y[mid_y:])
y_upp = [value-min_y_upp for value in y[mid_y:]]
for idx, value in enumerate(y_upp):
if value < thresh:
y_edge_upp = idx+mid_y
break
min_y_low = min(y[mid_y::-1])
y_low = [value - min_y_low for value in y[mid_y::-1]]
for idx, value in enumerate(y_low):
if value < thresh:
y_edge_low = mid_y-idx
break
return [x_edge_upp, x_edge_low], [y_edge_upp, y_edge_low]
def find_left_right(label_list):
for idx, value in enumerate(label_list):
if value > 0:
left = idx
break
for idx, value in enumerate(label_list[::-1]):
if value > 0:
right = idx
break
return len(label_list)-left-right
def crop_to_edge(image, x_edge, y_edge, mid_x, mid_y):
image = image[y_edge[1]: y_edge[0],x_edge[1]:x_edge[0]]
orientation = check_orientation(image)
labels = morphology.label(image, connectivity=2)
spread = []
for label in set(labels.flat):
if label != 0:
labels_sort = labels == label
y_labels_sort = sum(labels_sort)
transposed = labels_sort.transpose()
x_labels_sort = sum(transposed)
spread.append(find_left_right(y_labels_sort) * find_left_right(x_labels_sort))
# assert( labels.max() != 0 )
# image = labels == np.argmax(np.bincount(labels.flat)[1:])+1
image = labels == np.argmax(spread)+1
x = sum(image)
transposed = image.transpose()
y = sum(transposed)
x = [value*idx for idx, value in enumerate(x)]
y = [value*idx for idx, value in enumerate(y)]
mid_x = sum(x)/len(x)
mid_y = sum(y)/len(y)
return image, mid_x - x_edge[1], mid_y - y_edge[1], orientation
def get_x_y_pairs(image):
_, colomns = np.shape(image)
flat = image.flatten()
x_y_pair = [[idx%colomns, idx//colomns] for idx, value in enumerate(flat) if value == 1]
return x_y_pair
def get_euclidean_distances(x_y_pairs, mid_x, mid_y):
distances = [ math.sqrt((value[0] - mid_x)**2 + (value[1] - mid_y)**2) for value in x_y_pairs]
return distances
def get_corners_tilted(x_y_pairs, distances, mid_x, mid_y, x_offset, y_offset):
dist_upp = 20
dist_low = 20
dist_left = 20
dist_right = 20
for coord, dist in zip(x_y_pairs, distances):
x = coord[0] - mid_x
y = coord[1] - mid_y
if x < y:
if (x < -1*y) and (dist > dist_left):
corn_left = coord
dist_left = dist
elif (x > -1*y) and (dist > dist_upp):
corn_upp = coord
dist_upp = dist
elif x > y:
if (x > -1*y) and (dist > dist_right):
corn_right = coord
dist_right = dist
if (x < -1*y) and (dist > dist_low):
corn_low = coord
dist_low = dist
corners = [corn_left, corn_low, corn_right, corn_upp]
corners = [[corn[0]+x_offset, corn[1]+y_offset] for corn in corners]
return corners
def get_corners_straight(x_y_pairs, distances, mid_x, mid_y, x_offset, y_offset):
dist_upp = 20
dist_low = 20
dist_left = 20
dist_right = 20
for coord, dist in zip(x_y_pairs, distances):
x = coord[0] - mid_x
y = coord[1] - mid_y
if x < 0:
if (y < 0) and (dist > dist_left):
corn_left = coord
dist_left = dist
elif (y > 0) and (dist > dist_upp):
corn_upp = coord
dist_upp = dist
elif x > 0:
if (y > 0) and (dist > dist_right):
corn_right = coord
dist_right = dist
if (y < 0) and (dist > dist_low):
corn_low = coord
dist_low = dist
corners = [corn_left, corn_low, corn_right, corn_upp]
corners = [[corn[0]+x_offset, corn[1]+y_offset] for corn in corners]
return corners
def find_rc_b(point1, point2, grid_size):
diff_x = point1[0] - point2[0]
diff_y = point1[1] - point2[1]
rc = diff_y/diff_x
b = point1[1] - (point1[0] * rc)
return rc, b
def interpolate(image, point):
lower_left = [ value // 1 for value in point]
offsets = [value % 1 for value in point]
cell = [[1,1], [1,0], [0,1], [0,0]]
total_value = 0
height, width = np.shape(image)
if (point[0]+1 >= height) or (point[1]+1 >= width):
total_value = 0
else:
for corner in cell:
weight = 1
for offset, value in zip(offsets, corner):
if value == 1:
weight *= offset
else:
weight *= 1 - offset
total_value += image[int(lower_left[0]+corner[0]),int(lower_left[1]+corner[1])]*weight
return total_value
def get_sample_points(vanishing_point, point1, point2, grid_size):
rc, b = find_rc_b(point1, point2, grid_size)
distances = get_euclidean_distances([point1, point2], vanishing_point[0], vanishing_point[1])
if vanishing_point[0] > point1[0]:
step_factor = np.linspace(max(distances)/(min(distances)), 1, grid_size)
step_size = abs(point1[0]-point2[0])/(grid_size)
x_start = min([point1[0],point2[0]])
x = [x_start+idx*factor*step_size for idx, factor in enumerate(step_factor)]
sample_points = [[rc*value + b, value] for value in x]
else:
step_factor = np.linspace(min(distances)/(max(distances)), 1, grid_size)
step_size = abs(point1[0]-point2[0])/(grid_size)
x_start = min([point1[0],point2[0]])
x = [x_start+idx*factor*step_size for idx, factor in enumerate(step_factor)]
sample_points = [[rc*value + b, value] for value in x]
return sample_points
def get_sample_points_row(vanishing_point, point1, point2, grid_size):
rc, b = find_rc_b(point1, point2, grid_size)
distances = get_euclidean_distances([point1, point2], vanishing_point[0], vanishing_point[1])
if vanishing_point[0] > point1[0]:
step_factor = np.linspace(max(distances)/(min(distances)), 1, grid_size)
step_size = abs(point1[0]-point2[0])/(grid_size)
x_start = min([point1[0],point2[0]])
x = [x_start+idx*factor*step_size for idx, factor in enumerate(step_factor)]
sample_points = [[ value, rc*value + b] for value in x]
else:
step_factor = np.linspace(min(distances)/(max(distances)), 1, grid_size)
step_size = abs(point1[0]-point2[0])/(grid_size)
x_start = min([point1[0],point2[0]])
x = [x_start+idx*factor*step_size for idx, factor in enumerate(step_factor)]
sample_points = [[ value, rc*value + b] for value in x]
return sample_points
def get_vanishing_point(edge1, edge2, grid_size):
rc_left, b_left = find_rc_b(edge1[0], edge1[1], grid_size)
rc_right, b_right = find_rc_b(edge2[0], edge2[1], grid_size)
x_intersect = (b_right-b_left)/(rc_left-rc_right)
y_intersect = x_intersect*rc_left+b_left
return [x_intersect, y_intersect]
def translate_crop(corners, image, grid_size, flip):
cropped_img = np.zeros((grid_size, grid_size))
vanishing_point_row = get_vanishing_point([corners[1], corners[0]], [corners[2], corners[3]], grid_size)
left_points = get_sample_points(vanishing_point_row, corners[1], corners[0], grid_size)
right_points = get_sample_points(vanishing_point_row, corners[2], corners[3], grid_size)
vanishing_point_col = get_vanishing_point([corners[2], corners[1]], [corners[3], corners[0]], grid_size)
if flip == 0:
for idx, point in enumerate(zip(left_points, right_points)):
sample_points = get_sample_points_row(vanishing_point_col, point[0], point[1], grid_size)
row = [interpolate(image, sample) for sample in sample_points]
cropped_img[grid_size - idx -1, :] = row
else:
for idx, point in enumerate(zip(left_points, right_points)):
sample_points = get_sample_points_row(vanishing_point_col, point[0], point[1], grid_size)
row = [interpolate(image, sample) for sample in sample_points]
cropped_img[idx] = row
return cropped_img
def test(path, stage):
plt.figure()
image = preprocess(path)
rows, cols = image.shape
if rows > cols:
image = np.transpose(image)
flip = 1
else:
flip = 0
if stage > 0:
dark = get_thresh(image, 0.6)
plt.subplot(2,2,1)
plt.imshow(dark, cmap = 'gray')
if stage > 1:
edges = edges_binar(dark)
plt.subplot(2,2,2)
plt.imshow(edges, cmap = 'gray')
if stage > 2:
mid_x, mid_y, x, y = find_mid(edges)
x_edge, y_edge = find_edges(mid_x, mid_y, x, y,2)
edges, mid_x_new, mid_y_new, orientation = crop_to_edge(edges, x_edge, y_edge, mid_x, mid_y)
x_y_pairs = get_x_y_pairs(edges)
distances = get_euclidean_distances(x_y_pairs, mid_x_new, mid_y_new)
plt.subplot(2,2,3)
plt.imshow(edges, cmap = 'gray')
print(f'the orientation is {orientation}')
if stage > 3:
if orientation == 1:
corners = get_corners_straight(x_y_pairs, distances, mid_x_new, mid_y_new, x_edge[1], y_edge[1])
else:
corners = get_corners_tilted(x_y_pairs, distances, mid_x_new, mid_y_new, x_edge[1], y_edge[1])
cropped_img = translate_crop(corners, image, 250, flip)
plt.subplot(2,2,4)
plt.imshow(cropped_img, cmap = 'gray')
print(datetime.now() - startTime)
plt.show()
def main(plot, image_paths):
if plot == 'yes':
plt.figure(1)
for idx, path in enumerate(image_paths):
image = preprocess(path)
rows, cols = image.shape
if rows > cols:
image = np.transpose(image)
flip = 1
else:
flip = 0
dark = get_thresh(image, 0.6)
edges = edges_binar(dark)
mid_x, mid_y, x, y = find_mid(edges)
x_edge, y_edge = find_edges(mid_x, mid_y, x, y,2)
edges, mid_x_new, mid_y_new, orientation = crop_to_edge(edges, x_edge, y_edge, mid_x, mid_y)
x_y_pairs = get_x_y_pairs(edges)
distances = get_euclidean_distances(x_y_pairs, mid_x_new, mid_y_new)
if orientation == 1:
corners = get_corners_straight(x_y_pairs, distances, mid_x_new, mid_y_new, x_edge[1], y_edge[1])
else:
corners = get_corners_tilted(x_y_pairs, distances, mid_x_new, mid_y_new, x_edge[1], y_edge[1])
cropped_img = translate_crop(corners, image, 250, flip)
print(datetime.now() - startTime)
if plot == 'yes':
plt.subplot(2, 4, idx+5)
plt.imshow(cropped_img, cmap = 'gray')
plt.subplot(2,4,idx+1)
plt.imshow(image, cmap = 'gray')
plt.show()
#image_paths = ['sudoku_straight.jpeg','sudoku_diag.jpeg', 'sudoku_diag_tilted.jpeg', 'sudoku_straight_tilted.jpeg']
#main('yes', image_paths)
| {"/flup.py": ["/main_sudoku.py"]} |
60,762 | FelixDikland/Suducko | refs/heads/master | /flup.py | import main_sudoku as sud
image_paths = ['sudoku_straight.jpeg','sudoku_diag.jpeg', 'sudoku_diag_tilted.jpeg', 'sudoku_straight_tilted.jpeg']
path = 'test.jpeg'
#sud.test('test.jpeg', 4)
sud.main('yes', image_paths)
| {"/flup.py": ["/main_sudoku.py"]} |
60,763 | jahanxb/hello_world | refs/heads/master | /hello_world_api/hello_api/__init__.py | # -*-coding:utf-8-*-
from flask import Blueprint
hello_app = Blueprint('hello_app', __name__)
from hello_world_api.hello_api import views
| {"/hello_world_api/__init__.py": ["/hello_world_api/hello_api/__init__.py", "/conf/configs.py"], "/hello_world_api/hello_api/views.py": ["/hello_world_api/hello_api/__init__.py"]} |
60,764 | jahanxb/hello_world | refs/heads/master | /hello_world_api/__init__.py | # -*-coding:utf-8-*-
import os
from flask import Flask
from hello_world_api.hello_api import hello_app
from conf.configs import Config as config,config_dict
def create_app():
app = Flask(__name__)
app.config.from_object(config_dict[configName])
return app
configName = os.environ.get('CONFIGNAME') or 'default'
app = create_app()
# register apps
app.register_blueprint(hello_app, url_prefix='/api')
@app.route('/', methods=['GET'])
def index():
return 'Welcome to Local Time Code service! redirect to http://0.0.0.0:8000/api/localtime for localtime API json'
| {"/hello_world_api/__init__.py": ["/hello_world_api/hello_api/__init__.py", "/conf/configs.py"], "/hello_world_api/hello_api/views.py": ["/hello_world_api/hello_api/__init__.py"]} |
60,765 | jahanxb/hello_world | refs/heads/master | /hello_world_api/hello_api/views.py | from datetime import datetime
from hello_world_api.hello_api import hello_app
import json
@hello_app.route('/localtime', methods=['GET'])
def response_manager():
from datetime import datetime, timezone
utc_dt = datetime.now(timezone.utc)
print("Local time {}".format(utc_dt.astimezone().isoformat()))
res_ = dict(date_time=str(utc_dt))
return json.dumps(res_)
| {"/hello_world_api/__init__.py": ["/hello_world_api/hello_api/__init__.py", "/conf/configs.py"], "/hello_world_api/hello_api/views.py": ["/hello_world_api/hello_api/__init__.py"]} |
60,766 | jahanxb/hello_world | refs/heads/master | /conf/configs.py | # -*-coding:utf-8-*-
class Config:
pass
class ProductionConfig(Config):
DEBUG = False
class DevelopmentConfig(Config):
DEBUG = True
config_dict = {
'development': DevelopmentConfig,
'production': ProductionConfig,
'default': DevelopmentConfig
}
| {"/hello_world_api/__init__.py": ["/hello_world_api/hello_api/__init__.py", "/conf/configs.py"], "/hello_world_api/hello_api/views.py": ["/hello_world_api/hello_api/__init__.py"]} |
60,767 | Jaima-Jarnaz/Django-website-2-SKETCH- | refs/heads/master | /drawings/admin.py | from django.contrib import admin
from .models import Sketch,Samima,Tonima,Mithila,Isrita,Bintu,Puspo
# Register your models here.
admin.site.register(Sketch)
admin.site.register(Samima)
admin.site.register(Tonima)
admin.site.register(Mithila)
admin.site.register(Isrita)
admin.site.register(Bintu)
admin.site.register(Puspo)
| {"/drawings/admin.py": ["/drawings/models.py"], "/drawings/views.py": ["/drawings/models.py"]} |
60,768 | Jaima-Jarnaz/Django-website-2-SKETCH- | refs/heads/master | /drawings/models.py | from django.db import models
# Create your models here.
class Sketch(models.Model):
img=models.ImageField(upload_to='pics')
class Samima(models.Model):
img=models.ImageField(upload_to='picsofsamima')
class Tonima(models.Model):
img=models.ImageField(upload_to='picsoftonima')
class Mithila(models.Model):
img=models.ImageField(upload_to='picsofmithila')
class Isrita(models.Model):
img=models.ImageField(upload_to='picsofisrita')
class Bintu(models.Model):
img=models.ImageField(upload_to='picsofbintu')
class Puspo(models.Model):
img=models.ImageField(upload_to='picsofpuspo')
| {"/drawings/admin.py": ["/drawings/models.py"], "/drawings/views.py": ["/drawings/models.py"]} |
60,769 | Jaima-Jarnaz/Django-website-2-SKETCH- | refs/heads/master | /accounts/models.py | from django.db import models
#class User(models.Model):
#pic=models.ImageField(upload_to="profiles") | {"/drawings/admin.py": ["/drawings/models.py"], "/drawings/views.py": ["/drawings/models.py"]} |
60,770 | Jaima-Jarnaz/Django-website-2-SKETCH- | refs/heads/master | /accounts/urls.py | from django.urls import path
from django.conf import settings
from django.conf.urls.static import static
from . import views
urlpatterns=[
path("register",views.register,name='register'),
path("login",views.login,name='login'),
path("user",views.user,name='user'),
#path('upload',views.upload_image,name='upload_image'),
] | {"/drawings/admin.py": ["/drawings/models.py"], "/drawings/views.py": ["/drawings/models.py"]} |
60,771 | Jaima-Jarnaz/Django-website-2-SKETCH- | refs/heads/master | /accounts/views.py | from django.shortcuts import render,redirect
from django.contrib import messages
from django.contrib.auth.models import User,auth
# Create your views here.
def login(request):
if request.method=='POST':
username=request.POST['username']
password=request.POST['password']
user=auth.authenticate(username=username,password=password)
if user is not None:
auth.login(request,user)
return redirect('user')
else:
messages.info(request,'Invalid Credentials')
return redirect('login')
else:
return render(request,"login.html")
def register(request):
if request.method=='POST':
firstname=request.POST['firstname']
lastname=request.POST['lastname']
username=request.POST['username']
email=request.POST['email']
password1=request.POST['pass1']
password2=request.POST['pass2']
if password1==password2:
if User.objects.filter(username=username).exists():
messages.info(request,"username taken")
return redirect('register')
elif User.objects.filter(email=email).exists():
messages.info(request,"can't use")
return redirect('register')
else:
user=User.objects.create_user(first_name=firstname,last_name=lastname,username=username,email=email,password=password1)
user.save()
else:
messages.info(request,"pass not matching")
return redirect('register')
return redirect('login')
else:
return render(request,"register.html")
def user(request):
return render(request,'user.html')
'''def user(request):
from .models import User
users=User()
users=User.objects.all()
p=users[len(users)-1].pic
return render(request,'user.html',{'users':users})
def upload_image(request):
from .models import User
p=request.FILES['image']
user=User(pic=p)
user.save()
print("uploaded")
return render(request,'user.html')''' | {"/drawings/admin.py": ["/drawings/models.py"], "/drawings/views.py": ["/drawings/models.py"]} |
60,772 | Jaima-Jarnaz/Django-website-2-SKETCH- | refs/heads/master | /drawings/migrations/0004_bintu_isrita_mithila_puspo_tonima.py | # Generated by Django 3.0.5 on 2020-07-10 17:19
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('drawings', '0003_auto_20200710_2207'),
]
operations = [
migrations.CreateModel(
name='Bintu',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('img', models.ImageField(upload_to='picsofbintu')),
],
),
migrations.CreateModel(
name='Isrita',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('img', models.ImageField(upload_to='picsofisrita')),
],
),
migrations.CreateModel(
name='Mithila',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('img', models.ImageField(upload_to='picsofmithila')),
],
),
migrations.CreateModel(
name='Puspo',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('img', models.ImageField(upload_to='picsofpuspo')),
],
),
migrations.CreateModel(
name='Tonima',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('img', models.ImageField(upload_to='picsoftonima')),
],
),
]
| {"/drawings/admin.py": ["/drawings/models.py"], "/drawings/views.py": ["/drawings/models.py"]} |
60,773 | Jaima-Jarnaz/Django-website-2-SKETCH- | refs/heads/master | /drawings/views.py | from django.shortcuts import render
from .models import Sketch,Samima,Mithila,Isrita,Bintu,Puspo,Tonima
#,Tonima,Mithila,Isrita,Bintu,Puspo
def home(request):
s=Sketch.objects.all()
return render(request,"home.html",{'s':s})
# Create your views here.
def samima(request):
s=Samima.objects.all()
return render(request,"artist.html",{'s':s})
def tonima(request):
s=Tonima.objects.all()
return render(request,"artist.html",{'s':s})
def mithila(request):
s=Mithila.objects.all()
return render(request,"artist.html",{'s':s})
def isrita(request):
s=Isrita.objects.all()
return render(request,"artist.html",{'s':s})
def bintu(request):
s=Bintu.objects.all()
return render(request,"artist.html",{'s':s})
def puspo(request):
s=Puspo.objects.all()
return render(request,"artist.html",{'s':s}) | {"/drawings/admin.py": ["/drawings/models.py"], "/drawings/views.py": ["/drawings/models.py"]} |
60,774 | Jaima-Jarnaz/Django-website-2-SKETCH- | refs/heads/master | /drawings/apps.py | from django.apps import AppConfig
class DrawingsConfig(AppConfig):
name = 'drawings'
| {"/drawings/admin.py": ["/drawings/models.py"], "/drawings/views.py": ["/drawings/models.py"]} |
60,775 | Jaima-Jarnaz/Django-website-2-SKETCH- | refs/heads/master | /accounts/migrations/0004_delete_user.py | # Generated by Django 3.0.5 on 2020-07-10 15:52
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('accounts', '0003_user'),
]
operations = [
migrations.DeleteModel(
name='User',
),
]
| {"/drawings/admin.py": ["/drawings/models.py"], "/drawings/views.py": ["/drawings/models.py"]} |
60,776 | Jaima-Jarnaz/Django-website-2-SKETCH- | refs/heads/master | /drawings/urls.py | from django.urls import path
from .import views
urlpatterns=[
path('',views.home,name='home'),
path('samima',views.samima,name='samima'),
path('tonima',views.tonima,name='tonima'),
path('mithila',views.mithila,name='mithila'),
path('isrita',views.isrita,name='isrita'),
path('bintu',views.bintu,name='bintu'),
path('puspo',views.puspo,name='puspo'),
] | {"/drawings/admin.py": ["/drawings/models.py"], "/drawings/views.py": ["/drawings/models.py"]} |
60,782 | muberrabulbul/fakedatabase | refs/heads/master | /fakedata.py | import os
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'config.settings')
import django
django.setup()
from faker import Faker
from fakedatabase.models import Person
fake = Faker()
def database(N=1000):
for _ in range(N):
name=fake.first_name()
surname=fake.last_name()
job=fake.job()
# print(job)
address=fake.address()
email=fake.ascii_safe_email()
description=fake.paragraph()
person = Person.objects.get_or_create(name=name, surname=surname, job=job, address=address, email=email, description=description)
# save.person()
#return person
if __name__ == '__main__':
database(1000)
#deneme
# fake = Faker()
# for _ in range(10):
# print(fake.name()) | {"/fakedata.py": ["/fakedatabase/models.py"], "/fakedatabase/views.py": ["/fakedatabase/models.py"]} |
60,783 | muberrabulbul/fakedatabase | refs/heads/master | /fakedatabase/apps.py | from django.apps import AppConfig
class FakedatabaseConfig(AppConfig):
name = 'fakedatabase'
| {"/fakedata.py": ["/fakedatabase/models.py"], "/fakedatabase/views.py": ["/fakedatabase/models.py"]} |
60,784 | muberrabulbul/fakedatabase | refs/heads/master | /fakedatabase/migrations/0002_auto_20200901_0612.py | # Generated by Django 3.1 on 2020-09-01 06:12
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('fakedatabase', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='person',
name='job',
field=models.TextField(),
),
migrations.AlterField(
model_name='person',
name='name',
field=models.TextField(),
),
migrations.AlterField(
model_name='person',
name='surname',
field=models.TextField(),
),
]
| {"/fakedata.py": ["/fakedatabase/models.py"], "/fakedatabase/views.py": ["/fakedatabase/models.py"]} |
60,785 | muberrabulbul/fakedatabase | refs/heads/master | /fakedatabase/models.py |
from django.db import models
class Person(models.Model):
name = models.TextField()
surname = models.TextField()
job = models.TextField()
address = models.TextField()
email = models.EmailField()
description = models.TextField()
def __str__(self):
return self.name
| {"/fakedata.py": ["/fakedatabase/models.py"], "/fakedatabase/views.py": ["/fakedatabase/models.py"]} |
60,786 | muberrabulbul/fakedatabase | refs/heads/master | /fakedatabase/views.py | from django.utils import timezone
from django.views.generic.list import ListView
from .models import Person
from django.core.paginator import Paginator
from django.shortcuts import render
from django.http import HttpResponseRedirect
from django.contrib import messages
from django.db.models import Q
class PersonListView(ListView):
model = Person
paginate_by = 100
template_name = 'person_list.html'
queryset = Person.objects.all()
search_param = None
row_total = paginate_by
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['now'] = timezone.now()
context['search'] = self.search_param
return context
def get_queryset(self, *args, **kwargs):
queryset = super(PersonListView, self).get_queryset(*args, **kwargs)
search_query = self.request.GET.get('search')
if search_query:
self.search_param = search_query
queryset = queryset.filter(
Q(name__icontains=search_query)|
Q(surname__icontains=search_query)|
Q(job__icontains=search_query)|
Q(address__icontains=search_query)|
Q(email__icontains=search_query)|
Q(description__icontains=search_query)
).distinct()
return queryset
# def get_queryset(self):
# qs = super().get_queryset()
# return qs.filter(name__iexact=self.kwargs['name'])
# def search(request):
# if request.method == 'POST':
# srch = request.POST.get("title")
# if srch:
# match = Person.objects.filter(Q(name__contains=srch) |
# Q(surname__contains=srch) |
# Q(job__contains=srch) |
# Q(address__contains=srch) |
# Q(email__contains=srch) |
# Q(description__contains=srch))
# if match:
# return render(request,"search.html",{"sr":match})
# else:
# messages.error(request, 'arama sonucu bulunamadi')
# else:
# return HttpResponseRedirect('/search/')
# return render(request,"search.html") | {"/fakedata.py": ["/fakedatabase/models.py"], "/fakedatabase/views.py": ["/fakedatabase/models.py"]} |
60,787 | muberrabulbul/fakedatabase | refs/heads/master | /fakedatabase/api/serializers.py | from django.urls import path, include
from django.contrib.auth.models import Person
from rest_framework import routers, serializers, viewsets
class UserSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Person
fields = ['name', 'surname', 'job', 'address', 'email', 'address' ] | {"/fakedata.py": ["/fakedatabase/models.py"], "/fakedatabase/views.py": ["/fakedatabase/models.py"]} |
60,788 | rlcjj/OAServer | refs/heads/master | /OAServer/db_manage.py | __author__ = 'Justin'
import json
def to_json(objs):
jsObjs = []
for temp in objs:
dict = {}
dict.update(temp.__dict__)
jsObjs.append(dict)
return jsObjs
| {"/OAServer/views.py": ["/OAServer/models.py", "/OAServer/db_manage.py"]} |
60,789 | rlcjj/OAServer | refs/heads/master | /server.py | import Pyro.core
from PyQt4.QtCore import QCoreApplication
import sys, threading
from demoEngine import MainEngine
from eventEngine import EventEngine
def qtLoop():
daemon.requestLoop()
app = QCoreApplication(sys.argv)
me = MainEngine()
daemon=Pyro.core.Daemon(host='localhost',port=9000)
Pyro.core.initServer()
proxyOfMainEn = Pyro.core.ObjBase()
proxyOfMainEn.delegateTo(me)
proxyOfEventEn = Pyro.core.ObjBase()
proxyOfEventEn.delegateTo(me.ee)
daemon.connect(proxyOfMainEn, 'mainEn')
daemon.connect(proxyOfEventEn, 'eventEn')
t1 = threading.Thread(target=qtLoop, name='loop')
t1.start()
app.exec_()
| {"/OAServer/views.py": ["/OAServer/models.py", "/OAServer/db_manage.py"]} |
60,790 | rlcjj/OAServer | refs/heads/master | /OAServer/models.py | __author__ = 'Justin'
from django.db import models
class TestModel(models.Model):
name = models.CharField(max_length=5)
def __unicode__(self):
return self.name | {"/OAServer/views.py": ["/OAServer/models.py", "/OAServer/db_manage.py"]} |
60,791 | rlcjj/OAServer | refs/heads/master | /OAServer/views.py | __author__ = 'Justin'
from django.http import HttpResponse
from OAServer.models import TestModel
from OAServer.db_manage import to_json
import json
#haha
def post_only(func):
""" Ensures a method is post only """
def wrapped_f(request):
if request.method != "POST":
response = HttpResponse(json.dumps(
{"error": "this method only accepts posts!"}))
response.status_code = 500
return response
return func(request)
return wrapped_f
# Create your views here.
# @post_only
def test_view(request):
posts = TestModel.objects.all()
return HttpResponse(to_json(posts))
| {"/OAServer/views.py": ["/OAServer/models.py", "/OAServer/db_manage.py"]} |
60,804 | JohnSchlerf/CenterOut | refs/heads/master | /devices/UseMouse.py | # Mouse module for Cursor class.
# Uses pygame.
# Could be re-implemented for other hardware.
import pygame
class MotionHardware:
def __init__(self, homeX, homeY):
# Since this is just a mouse, this is trivial. Other hardware
# may need hardware initialization code here (query serial
# port, etc.)
self.homeX = homeX
self.homeY = homeY
self.currentX = homeX
self.currentY = homeY
def Update(self):
# Since this is just a mouse, update it with the change since
# the last update. Doing it this way is important, because I
# expect that the actual mouse cursor will not be visible in
# most use-cases:
[dX,dY] = pygame.mouse.get_rel()
# In a perfect world, I would make sure that currentX and
# currentY were always in mm. But I'm ignoring that since
# we're using a mouse.
self.currentX += dX
self.currentY += dY
def getRelX(self):
# return distance along X to home position
return self.currentX - self.homeX
def getRelY(self):
# return distance along Y to home position
return self.currentY - self.homeY
def setHome(self,newHomeX,newHomeY):
# adjust "hardware center"
self.homeX = newHomeX
self.homeY = newHomeY
def reHome(self):
# adjust "hardware center" to current
self.homeX = self.currentX
self.homeY = self.currentY
# Return the home position for bookkeeping
return [self.homeX, self.homeY]
| {"/devices/Cursor.py": ["/devices/UseMouse.py"], "/Adaptation_Experiment.py": ["/devices/Clock.py", "/devices/Cursor.py", "/devices/Monitor.py", "/dialog.py"]} |
60,805 | JohnSchlerf/CenterOut | refs/heads/master | /devices/Monitor.py | import pygame
from pygame.locals import *
# I'm defining this to handle basic pygame initialization stuff and deal
# with the screen object in an easy-to-use way. Does a lot of the standard
# things that I need for experiments; somewhat limited in terms of more
# advanced graphics.
def loadImage(filename, colorkey=(0,0,0)):
"""Load an image by filename."""
if filename:
image = pygame.image.load(filename)
image = image.convert()
if colorkey:
image.set_colorkey(colorkey)
return image
class Monitor:
def __init__(self, width=1024, height=768, fullscreen=False,
grabValue=1, textSize=40):
pygame.init()
pygame.font.init()
pygame.mouse.set_visible(0)
pygame.event.set_grab(grabValue)
self.horizSize = width
self.vertSize = height
if fullscreen:
self.myScreen = pygame.display.set_mode((width, height),FULLSCREEN)
else:
self.myScreen = pygame.display.set_mode((width, height))
self.font = pygame.font.Font(None, textSize)
# Using these speeds things up enormously
self.rectlist = []
self.blankrectlist = []
# This slightly speeds up drawText
self.textDict = {}
# Defaults (allows for back-projection, mirrors, rotation...)
self.horizFlipped = False
self.vertFlipped = False
def blank(self,color=(0,0,0)):
self.myScreen.fill(color)
pygame.display.flip()
def flipHorizontal(self):
self.horizFlipped = not(self.horizFlipped)
def flipVertical(self):
self.vertFlipped = not(self.vertFlipped)
def update(self):
pygame.display.update(self.blankrectlist)
pygame.display.update(self.rectlist)
self.blankrectlist = self.rectlist
self.rectlist = []
def drawObject(self,imageObject,position):
# draw an object centered on a position
# handle screen flipping
if self.horizFlipped:
position = [self.horizSize-position[0],position[1]]
if self.vertFlipped:
position = [position[0],self.vertSize-position[1]]
# Get around deprecation warnings:
position = [int(round(position[0])),int(round(position[1]))]
width,height = imageObject.get_size()
posAdj = [round(position[0]+width/2),round(position[1]+height/2)]
self.rectlist.append(self.myScreen.blit(pygame.transform.flip(imageObject,self.horizFlipped,self.vertFlipped),posAdj))
def blankRects(self,color=(0,0,0)):
for rect in self.blankrectlist:
self.myScreen.fill(color,rect)
def drawFix(self,color,position,radius,width=2):
# draws a circle with a cross in the center
self.drawCircle(color,position,radius,width)
self.drawLine(color,[position[0]-radius,position[1]],
[position[0]+radius,position[1]],width)
self.drawLine(color,[position[0],position[1]-radius],
[position[0],position[1]+radius],width)
def drawCircle(self,color,position,radius,width=0):
# draw a circle. Filled by default; set width nonzero to leave empty
# handle screen flipping
if self.horizFlipped:
position = [self.horizSize-position[0],position[1]]
if self.vertFlipped:
position = [position[0],self.vertSize-position[1]]
# Get around deprecation warnings:
position = [int(round(position[0])),int(round(position[1]))]
radius = int(round(radius))
width = int(round(width))
self.rectlist.append(pygame.draw.circle(self.myScreen,color,\
position,radius,width))
def drawLine(self,color,start_pos,end_pos,width=1):
# draw a line.
# handle screen flipping
if self.horizFlipped:
start_pos = [self.horizSize-start_pos[0],start_pos[1]]
end_pos = [self.horizSize-end_pos[0],end_pos[1]]
if self.vertFlipped:
start_pos = [start_pos[0],self.vertSize-start_pos[1]]
end_pos = [end_pos[0],self.vertSize-end_pos[1]]
# Get around deprecation warnings:
start_pos = [int(round(start_pos[0])),int(round(start_pos[1]))]
end_pos = [int(round(end_pos[0])),int(round(end_pos[1]))]
self.rectlist.append(pygame.draw.line(self.myScreen,color,\
start_pos,end_pos,width))
def drawText(self,color,pos,text,defaultVertIsFlipped = True):
"""Draw (blit) text on the screen (self.screen). If cache is True, the
text bitmap will be stored into textDict for reuse.
"""
if not text in self.textDict:
self.textDict[text] = self.font.render(text, 1, color)
width,height = self.textDict[text].get_size()
# handle screen flipping
if self.horizFlipped:
pos = [self.horizSize-pos[0],pos[1]]
if self.vertFlipped:
pos = [pos[0],self.vertSize-pos[1]]
pos = [int(round(pos[0]))-width/2,int(round(pos[1]))-height/2]
self.rectlist.append(self.myScreen.blit(pygame.transform.flip(self.textDict[text],
self.horizFlipped,
self.vertFlipped),
pos))
def close(self):
# Cleanup
pygame.display.quit()
| {"/devices/Cursor.py": ["/devices/UseMouse.py"], "/Adaptation_Experiment.py": ["/devices/Clock.py", "/devices/Cursor.py", "/devices/Monitor.py", "/dialog.py"]} |
60,806 | JohnSchlerf/CenterOut | refs/heads/master | /devices/old__init__.py | # This lets me import code in the "devices" directory using
# the syntax: "from devices import <X>"
try: from Clock import *
except (ImportError):
print("Clock.py is broken or missing.")
try: from Monitor import *
except (ImportError):
print("Monitor.py is broken or missing.")
try: from Cursor import *
except (ImportError):
print("Cursor.py is broken or missing.")
| {"/devices/Cursor.py": ["/devices/UseMouse.py"], "/Adaptation_Experiment.py": ["/devices/Clock.py", "/devices/Cursor.py", "/devices/Monitor.py", "/dialog.py"]} |
60,807 | JohnSchlerf/CenterOut | refs/heads/master | /devices/Cursor.py | import math
# Import the appropriate "MotionHardware" class
from .UseMouse import MotionHardware
# Could be expanded for additional plugins.
class Cursor:
"""
2D Cursor class.
"""
# Handle some simple world-to-graphics values. These can be perturbed to
# require adaptation (learning).
CurrentRotation = 0
CurrentRotationRad = 0
HorizontalMapping = 1
VerticalMapping = 1
def __init__(self,CenterPos=(1024/2,768/2),HomePos=None):
# Create the cursor, start everything at the middle value.
self.CenterX = CenterPos[0]
self.CenterY = CenterPos[1]
# Using a mouse (which can be picked up and moved), this is
# redundant. Using something with a one-to-one mapping
# between physical position and reported position (IE,
# motion capture device, tablets), this is important as it
# specifies the "hardware" location of the center.
if not (HomePos):
self.homeX = CenterPos[0]
self.homeY = CenterPos[1]
else:
self.homeX = HomePos[0]
self.homeY = HomePos[1]
self.CurrentX = self.CenterX
self.CurrentY = self.CenterY
self.DisplayX = self.CenterX
self.DisplayY = self.CenterY
# Initialize motion hardware (mouse, motion tracker, etc)
self.hardware = MotionHardware(self.homeX,self.homeY)
def invertY(self):
# Allows y-axis to be inverted (up moves down):
self.VerticalMapping *= -1
def invertX(self):
# Allows x-axis to be inverted (left moves right):
self.HorizontalMapping *= -1
def setGain(newXgain,newYgain=None):
# Allows for cursor gain manipulations and affords calibration
# from mm to pixels on certain displays.
# default is isotropic:
if not(newYgain): newYgain = newXgain
# Preserve flipping for convenience
self.HorizontalMapping = math.copysign(newXgain, self.HorizontalMapping)
self.VerticalMapping = math.copysign(newYgain, self.VerticalMapping)
def update(self):
# Hardware update
self.hardware.Update()
# In a perfect world, this would be the horizontal and vertical
# distance in mm from home:
self.CurrentX = self.hardware.getRelX()
self.CurrentY = self.hardware.getRelY()
# Compute where the visual cursor should be:
dX_Vis = self.CurrentX*self.HorizontalMapping
dY_Vis = self.CurrentY*self.VerticalMapping
# Implement rotation:
self.DisplayX = int(round(self.CenterX + \
dX_Vis*math.cos(self.CurrentRotationRad) - \
dY_Vis*math.sin(self.CurrentRotationRad)))
self.DisplayY = int(round(self.CenterY + \
dX_Vis*math.sin(self.CurrentRotationRad) + \
dY_Vis*math.cos(self.CurrentRotationRad)))
# Distance is very handy in these experiments, so compute it:
self.VisualDisplacement = math.sqrt(dX_Vis**2 + dY_Vis**2)
def setRotationDeg(self,newRotation):
# set the cursor rotation in degrees
self.CurrentRotation = newRotation
self.CurrentRotationRad = newRotation * math.pi / 180
def setRotationRad(self,newRotationRad):
# set the cursor rotation in radians
self.CurrentRotationRad = newRotationRad
self.CurrentRotation = newRotationRad * 180 / math.pi
def setRotation(self,newRotation):
# legacy behavior; assume degrees
self.setRotationDeg(newRotation)
def setCenter(self,newCenterX,newCenterY=None):
# change the position of the graphical center
if len(newCenterX) == 2:
newCenterY = newCenterX[1]
newCenterX = newCenterX[0]
self.CenterX = newCenterX
self.CenterY = newCenterY
def setHome(self,newHomeX,newHomeY=None):
# change the position of the hardware center
if len(newHomeX) == 2:
newHomeY = newHomeX[1]
newHomeX = newHomeX[0]
self.homeX = newHomeX
self.homeY = newHomeY
self.hardware.setHome(self.homeX,self.homeY)
def reCenter(self):
# recenter the cursor on the current location
self.DisplayX = self.CenterX
self.DisplayY = self.CenterY
# Use current hardware position as home:
[self.homeX, self.homeY] = self.hardware.reHome()
def getHomePosition(self):
return (self.homeX,self.homeY)
| {"/devices/Cursor.py": ["/devices/UseMouse.py"], "/Adaptation_Experiment.py": ["/devices/Clock.py", "/devices/Cursor.py", "/devices/Monitor.py", "/dialog.py"]} |
60,808 | JohnSchlerf/CenterOut | refs/heads/master | /devices/Clock.py | import os
# Use the most accurate clock.
# Tested on Windows XP and Linux.
if os.name == 'nt':
from time import clock as CurrentTime
import time
ADJUST_FOR_EPOCH = time.time()
else:
from time import time as CurrentTime
ADJUST_FOR_EPOCH = 0
class Clock:
"""Class for timers
In general, calls to the built-in time class can stop the iteration
of your program and slow things down. Maintaining multiple timers is
something that you often want, so this simplifies that while minimizing
calls to the built-in time functions.
Original inspiration for this concept came from Joern Diedrichsen.
"""
def __init__(self, num_timers=10):
"""Initialize a set of synchronized timers, all set at 0
Parameters
----------
num_timers : int (optional)
The number of timers to maintain. Default is 10.
"""
self.timers = []
for _ in range(num_timers):
self.timers.append(0.0)
self.resetAll()
def __getitem__(self, which_timer):
"""Return the value of the appropriate timer
Note that Python counts from 0.
Example:
--------
>>> myTimers = Clock(10)
>>> print(myTimers[0], myTimers[1], myTimers[2])
0.0, 0.0, 0.0
"""
return self.timers[which_timer]
def __setitem__(self, which_timer, value):
"""Allows stopwatches to be set directly for convenience
Example:
--------
>>> myTimers = Clock(10)
>>> myTimers[0] = 0.0
>>> myTimers[1] = 1.0
>>> myTimers[2] = 2.0
>>> print(myTimers[0], myTimers[1], myTimers[2])
0.0, 1.0, 2.0
"""
self.timers[which_timer] = value
def update(self):
"""Updates all timers with a single call to time
Example:
--------
>>> myTimers = Clock(10)
>>> orig_0 = myTimers[0]
>>> orig_1 = myTimers[1]
>>> myTimers.update()
>>> print((myTimers[0] - orig_0) == (myTimers[1] - orig_1))
True
>>> myTimers.update()
>>> print((myTimers[0] - orig_0) == (myTimers[1] - orig_1))
True
>>> myTimers[1] = 0.0
>>> myTimers.update()
>>> print((myTimers[0] - orig_0) == (myTimers[1] - orig_1))
False
"""
# First make a call to time and compute the update (dt):
self.dt = CurrentTime() + ADJUST_FOR_EPOCH - self.lastTime
# Now update the last time to keep the next dt accurate:
self.lastTime += self.dt
# Finally, update all the timers we're keeping track of:
for i in range(len(self.timers)):
self.timers[i] += self.dt
def reset(self, which_timer):
# Reset individual stopwatches
self.timers[which_timer] = 0.0
def resetAll(self):
# Reset all stopwatches and the master clock.
self.initialTime = CurrentTime()+ADJUST_FOR_EPOCH
self.lastTime = self.initialTime
self.dt = 0
for i in range(len(self.timers)):
self.timers[i] = 0.0
| {"/devices/Cursor.py": ["/devices/UseMouse.py"], "/Adaptation_Experiment.py": ["/devices/Clock.py", "/devices/Cursor.py", "/devices/Monitor.py", "/dialog.py"]} |
60,809 | JohnSchlerf/CenterOut | refs/heads/master | /dialog.py | from tkinter import Tk
from tkinter.simpledialog import askstring
from tkinter.filedialog import askopenfilenames
import os
def get_name(prompt="Name of Volunteer", default_value="Volunteer"):
"""Prompt for a subject's name using a dialog
Parameters
----------
prompt : string, optional
Text above the text entry cell. IF not supplied, defaults to a
generic "Name of Volunteer"
default_value : string, optional
The default value to put into the dialog. If not supplied, the
default is "Volunteer"
Returns
-------
subject_name : string
Returns the value entered in the dialog
"""
top = Tk()
top.update()
subject_name = askstring(
'', prompt, parent=top, initialvalue=default_value
)
top.destroy()
return subject_name
def get_target_files(directory="target_files"):
"""Quick prompt to load target files
It's possible to select multiple, but the list will be sorted by the
alphabetical order of filenames.
Parameters
----------
directory : string, optional
A directory to look in for target files. The default is "target_files"
Returns
-------
target_list : list(string)
Returns a list of every file that was selected, in order.
"""
top = Tk()
top.update()
# Path management
orig_dir = os.path.abspath(os.curdir)
os.chdir(directory)
file_names = askopenfilenames(parent=top)
top.destroy()
os.chdir(orig_dir)
return file_names
if __name__=="__main__":
print(name_dialog())
| {"/devices/Cursor.py": ["/devices/UseMouse.py"], "/Adaptation_Experiment.py": ["/devices/Clock.py", "/devices/Cursor.py", "/devices/Monitor.py", "/dialog.py"]} |
60,810 | JohnSchlerf/CenterOut | refs/heads/master | /Adaptation_Experiment.py | # This implements a simple center-out reaching experiment.
# My code:
from devices.Clock import Clock
from devices.Cursor import Cursor
from devices.Monitor import Monitor
from dialog import get_name, get_target_files
# Pygame:
import pygame
from pygame.locals import *
# These packages are fairly standard:
import os
import sys
import math
import random
import copy
import pandas as pd
#States:
STARTING = 0
WAITING = 1
WAIT_FOR_RT = 3
MOVING_EARLY = 4
MOVING_MIDPOINT = 5
MOVING = 10
FEEDBACK = 20
FINISHED = 99
# Figure out what subject name to use for data saving:
try:
participant_name = sys.argv[1]
except IndexError:
default = 'Volunteer'
participant_name = get_name('Participant name (for data saving):', default)
def distance(tuple1,tuple2):
# computes vector length from 2D tuple1 to tuple2
return math.sqrt((tuple1[0]-tuple2[0])**2 +
(tuple1[1]-tuple2[1])**2)
def angle(tuple1,tuple2):
# computes vecot angle from 2D tuple1 to tuple2
return math.atan2((tuple1[1]-tuple2[1]),
(tuple1[0]-tuple2[0])) * 180 / math.pi
class Adaptation_Experiment:
# target parameters:
numTargets = 12
targetDistance = 200 # pixels
targetRadius = 10 # pixels
targetColor = (128,128,0) # yellow
holdTime = 0.2 # time in seconds before target appears
# screen parameters
width = 1024
height = 768
fullscreen = True
# file locations
dataDir = "Data"
# onscreen cursor (a circle)
cursorColor = (128,128,128) # ie, white
cursorRad = 5 # radius in pixels
# starting location
fixRad = 15 # pixels
fixWidth = 2 # pixels
# feedback
feedbackColor = (255,0,0) #red
feedbackTime = 1 # seconds
sampleRate = 100 # in Hz
graphicsRate = 120 # in Hz; this is an "upper limit" across a trial
# I'm going to store data into a Python dictionary to make this code
# readable. The keys in Python dictionaries are not sorted in any
# particular order. Since I'd like control over how values show up in
# the datafile, I need to enforce the order with a list:
datFileKeyOrder = [
'blockNumber',
'trialNumber',
'startTime',
'rotation',
'cursorVisible',
'earlyAngle',
'midpointAngle',
'reactionTime',
'movementTime',
'targetX',
'targetY',
'targetAngle',
'targetDistance',
'startX',
'startY',
'earlyX',
'earlyY',
'earlyAngle',
'midpointX',
'midpointY',
'midpointAngle',
'finalX',
'finalY',
'finalAngle',
'feedbackX',
'feedbackY',
'feedbackAngle',
]
# Anything that is added outside this list will be appended at the end
# using whatever order Python chooses.
# initial control flags:
quitBlock = False
quitExperiment = False
blockRunning = False
def __init__(self, subname):
# Figure out the blocks to run:
self.block_list = get_target_files()
# Initialize data dictionary:
self.defaultTrialDict = {}
for key in self.datFileKeyOrder:
self.defaultTrialDict[key] = -1
self.screen = Monitor(self.width,self.height,self.fullscreen)
self.centerX = self.width/2
self.centerY = self.height/2
self.cursor = Cursor((self.centerX,self.centerY))
self.timer = Clock(5)
self.subName = subname
self.curBlock = 0
# graphics flags:
self.cursorOn = False
self.cueOn = False
self.targetOn = False
self.fixOn = False
self.feedbackOn = False
def update(self):
# check the clock and cursor:
self.timer.update()
self.cursor.update()
# check keyboard events for quit signal:
for event in pygame.event.get():
if event.type == KEYDOWN:
if event.key == K_ESCAPE:
self.quitBlock = True
elif event.key == K_END:
self.quitExperiment = True
def pol2rect(self, r, theta_deg):
"""Convert from polar to rectangular coordinates
Assumes the origin of the polar axis should be at centerX,
centerY in Cartesian space.
Parameters
----------
r : float
The radius, in pixels, from the center of the screen
theta_deg : float
The angle, in degrees, from horizontal
Returns
-------
(x, y) : float
Returns cartesian coordinates in screen space, where a
radius of 0 is always at the center of the screen
"""
x = self.centerX + r * math.cos(theta_deg * math.pi / 180.0)
y = self.centerY + r * math.sin(theta_deg * math.pi / 180.0)
return (x, y)
def rect2pol(self, x, y):
"""Convert from rectangular coordinates to polar
Parameters
----------
(x, y) : numeric
Cartesian coordinates, relative to the center of the screen.
Returns
r : float
The radius, in pixels, from the center of the screen
theta_deg : float
The angle, in degrees, from horizontal
"""
r = (x**2 + y**2)**0.5
theta_deg = math.atan2(y, x) * 180.0 / math.pi
return (r, theta_deg)
def drawGraphics(self):
"""Routine to update graphics
"""
self.screen.blankRects()
# draw the "fixation" spot in the center:
if self.fixOn:
current_dist = distance(
(self.cursor.DisplayX, self.cursor.DisplayY),
(self.centerX, self.centerY)
)
if current_dist < self.fixRad and not(self.targetOn):
fixColor = (0,0,255)
else:
fixColor = (255,255,0)
self.screen.drawFix(
fixColor,
(self.centerX, self.centerY),
self.fixRad,
self.fixWidth
)
# The cursor can be invisible
if self.cursorOn:
self.screen.drawCircle(
self.cursorColor,
(self.cursor.DisplayX, self.cursor.DisplayY),
self.cursorRad,
0
)
# Sometimes I'll write some text near the center:
if self.cueOn:
self.screen.drawText(
self.textColor,
(self.centerX, self.centerY + 50),
self.cueText
)
# target
if self.targetOn:
self.screen.drawCircle(
self.targetColor,
(
self.thisTrial['targetX'] + self.thisTrial['startX'],
self.thisTrial['targetY'] + self.thisTrial['startY']
),
self.targetRadius,
0
)
# feedback of final position
if (self.feedbackOn):
self.screen.drawCircle(
self.feedbackColor,
(
self.thisTrial['feedbackX'] + self.thisTrial['startX'],
self.thisTrial['feedbackY'] + self.thisTrial['startY']
),
self.cursorRad,
0
)
self.screen.update()
def writeAna(self,dataDict):
# write the trial-by-trial summary datafile:
datFileName = os.path.join(self.dataDir,self.subName+'.ana')
if not(os.path.exists(datFileName)):
datFileObj = open(datFileName,'w')
# Write a header first
# First thing, write all the data that I've coded above:
keyList = list(dataDict.keys())
for key in self.datFileKeyOrder:
if key in keyList:
datFileObj.write(str(key)+'\t')
keyList.remove(key)
# Now write any data that I haven't explicitly ordered:
for key in keyList:
datFileObj.write(str(key)+'\t')
# Write a newline:
datFileObj.write('\n')
else:
datFileObj = open(datFileName,'a')
# Now save the data, stepping through explicitly ordered keys first:
for key in self.datFileKeyOrder:
if key in dataDict.keys():
datFileObj.write(str(dataDict[key])+'\t')
del dataDict[key]
# Now write any data that I haven't explicitly ordered:
for key in dataDict.keys():
datFileObj.write(str(dataDict[key])+'\t')
# write a newline and close the file
datFileObj.write('\n')
datFileObj.close()
def writeTrajectory(self,dataList,header = 'Trial:\n'):
# Writes one trial at a time; trials could be rather long
dataFile = open(
os.path.join(
self.dataDir,
self.subName + '_' + str(self.curBlock).zfill(2) + '.mvt'
),
'a'
)
if not('\n' in header):
header = header + '\n'
dataFile.write(header)
for datum in dataList:
try:
for column in datum:
dataFile.write(str(column) + '\t')
except:
dataFile.write(str(datum))
dataFile.write('\n')
dataFile.write('\n')
dataFile.close()
def randomTarget(self, target_distance = None):
if not(target_distance):
# This allows for some flexibility later;
# not really necessary right now, though
target_distance = self.targetDistance
# Pick the target at random, and set all necessary positions:
self.thisTrial['targetAngle'] = \
random.choice(range(self.numTargets)) * (360.0/self.numTargets)
self.thisTrial['targetDistance'] = target_distance
(self.thisTrial['targetX'], self.thisTrial['targetY']) = \
self.pol2rect(
self.thisTrial['targetDistance'],
self.thisTrial['targetAngle']
)
def runTrial(self, trial_number, trial_data):
"""Run a single trial
Parameters
----------
trial_number : int
The trial number. More for bookkeeping than anything else.
trial_data : dict
A dictionary of parameters for this trial. Parameters supported:
rotation - numeric (optional)
A rotation perturbation to apply to the cursor. If not supplied, we'll use 0.
target_angle - numeric (optional)
The angle of the target, in degrees. Has precedence over supplying X/Y coordinates.
target_distance - numeric (optional)
The distance of the target, in pixels. If not supplied, defaults to the set distance.
target_x, target_y - numeric (optional)
The x- and y-coordinates of the target. Ignored if target_angle is set.
NOTE: If no target information is supplied, a target will be selected at random.
Returns
-------
ana_dict : dict
A dictionary summary of the events in the trial.
trajectory : list
A list of values that make up the full trajectory. Each row is a single sample.
"""
# Coded as a functional example of a "slicing" movement
self.thisTrial = copy.deepcopy(self.defaultTrialDict)
if 'rotation' in trial_data:
self.thisTrial['rotation'] = trial_data['rotation']
else:
self.thisTrial['rotation'] = 0
# count from 1 to make data more human-readable
self.thisTrial['trialNumber'] = trial_number + 1
self.thisTrial['blockNumber'] = self.curBlock
self.thisTrial['startTime'] = self.timer[0]
# May want to remove this later if trials are to be scripted:
#self.randomTarget()
if 'target_angle' in trial_data:
self.thisTrial['targetAngle'] = trial_data['target_angle']
if 'target_distance' in trial_data:
self.thisTrial['targetDistance'] = trial_data['target_distance']
else:
self.thisTrial['targetDistance'] = self.targetDistance
self.thisTrial['targetX'], self.thisTrial['targetY'] = \
self.pol2rect(
self.thisTrial['targetDistance'],
self.thisTrial['targetAngle']
)
elif 'target_x' in trial_data:
self.thisTrial['targetX'] = trial_data['target_x']
self.thisTrial['targetY'] = trial_data['target_y']
self.thisTrial['targetAngle'], self.thisTrial['targetDistance'] = \
self.rect2pol(
self.thisTrial['targetX'], self.thisTrial['targetY']
)
else:
# If no target is defined, then pick one at random:
self.randomTarget()
trialOver = False
traj = []
state = STARTING
# Initialize graphics flags:
self.cursorOn = True
self.fixOn = True
self.targetOn = False
self.feedbackOn = False
self.cueOn = False
self.cursor.setRotation(self.thisTrial['rotation'])
self.timer.reset(1)
while not(trialOver) \
and not(self.quitBlock) \
and not(self.quitExperiment):
self.update()
# Save data at a fixed rate (keeps datafile sane)
if self.timer[4] >= 1.0/self.sampleRate:
traj.append([self.timer[1], state,
self.cursor.CurrentX, self.cursor.CurrentY,
self.cursor.DisplayX, self.cursor.DisplayY])
# Rather than resetting timer 4, I want to allow jitter:
self.timer[4] = self.timer[4] - 1.0/self.sampleRate
# Update graphics at a fixed rate (avoids overhead)
if self.timer[3] >= 1.0/self.graphicsRate:
self.drawGraphics()
# Rather than resetting timer 3, I want to allow jitter:
self.timer[3] = self.timer[3] - 1.0/self.graphicsRate
################################################################
# Trial state machine:
if state == STARTING:
# wait for the cursor to be in the fixation spot:
if self.cursor.VisualDisplacement < self.fixRad:
self.timer.reset(2)
state = WAITING
elif state == WAITING:
# wait an appropriate amount of time in the fixation spot
if self.timer[2] >= self.holdTime:
self.timer.reset(2)
self.targetOn = True
state = WAIT_FOR_RT
elif state == WAIT_FOR_RT:
# wait for subject to start moving
if self.cursor.VisualDisplacement < self.fixRad:
self.thisTrial['reactionTime'] = self.timer[2]
self.timer.reset(2)
state = MOVING_EARLY
elif state == MOVING_EARLY:
# wait for the cursor to cross 1/4 of target distance,
# save position
if self.cursor.VisualDisplacement >= self.targetDistance / 4.0:
self.thisTrial['earlyTime'] = self.timer[2]
self.thisTrial['earlyX'] = self.cursor.CurrentX
self.thisTrial['earlyY'] = self.cursor.CurrentY
self.thisTrial['earlyAngle'] = \
math.atan2(self.cursor.CurrentY, self.cursor.CurrentX)
state = MOVING_MIDPOINT
elif state == MOVING_MIDPOINT:
# wait for the cursor to cross 1/2 of target distance,
# save position
if self.cursor.VisualDisplacement >= self.targetDistance / 2.0:
self.thisTrial['midpointTime'] = self.timer[2]
self.thisTrial['midpointX'] = self.cursor.CurrentX
self.thisTrial['midpointY'] = self.cursor.CurrentY
self.thisTrial['midpointAngle'] = \
math.atan2(self.cursor.CurrentY, self.cursor.CurrentX)
state = MOVING
elif state == MOVING:
# wait for the cursor to cross target distance, save position
if self.cursor.VisualDisplacement >= self.targetDistance:
self.thisTrial['movementTime'] = self.timer[2]
self.thisTrial['finalX'] = self.cursor.CurrentX
self.thisTrial['finalY'] = self.cursor.CurrentY
self.thisTrial['finalAngle'] = \
math.atan2(self.cursor.CurrentY, self.cursor.CurrentX)
self.thisTrial['feedbackX'] = self.cursor.DisplayX
self.thisTrial['feedbackY'] = self.cursor.DisplayY
state = FEEDBACK
self.timer.reset(2)
self.feedbackOn = True
elif state == FEEDBACK:
if self.timer[2] >= self.feedbackTime:
state = FINISHED
trialOver = True
return [self.thisTrial, traj]
def runBlock(self, target_file):
"""Run a block
Parameters
----------
target_file : string
The path to a target file. This is expected to be a comma separated file with one line for each trial.
When all trials have been run, the block will be considered done.
"""
try:
all_trials = pd.read_csv(target_file)
except:
# Something seems to have gone wrong with the target file. COULD run a demo block if you like.
print("Something is wrong with the input target file...")
# Uncomment this next line to run a demo block:
#self.runBlockDemo()
return
for trial_number in range(all_trials.shape[0]):
[ana_data, trajectory_data] = self.runTrial(
trial_number, dict(all_trials.iloc[trial_number, :])
)
# Write out data after every trial to avoid losing data.
self.writeAna(ana_data)
self.writeTrajectory(trajectory_data, 'Trial %i:' % (trial_number))
if self.quitExperiment or self.quitBlock:
break
self.screen.blank()
def runBlockDemo(self, num_trials=24):
# Old version; just runs 24-trial blocks, with random +/- 45 degree rotation each time.
if self.curBlock%2==0:
if random.random() > 0.5: rotation = 45
else: rotation = -45
else:
rotation = 0
for trial_number in range(num_trials):
[trial_data, traj] = self.runTrial(trial_number, {'rotation':rotation})
# write the trajectory information after every trial to
# keep memory cost low
self.writeAna(trial_data)
self.writeTrajectory(traj, 'Trial ' + str(trial_number) + ':')
if self.quitExperiment or self.quitBlock:
break
self.screen.blank()
def run(self):
# Run the selected blocks. Allow an abort if the END button is pressed:
while not(self.quitExperiment):
self.screen.drawText(
(255, 255, 255),
(self.centerX, self.centerY - 50),
'Welcome, ' + self.subName
)
self.screen.drawText(
(255, 255, 255),
(self.centerX, self.centerY),
'Press <SPACE> to begin, <END> or <ESC> to quit'
)
self.screen.drawText(
(255, 255, 255),
(self.centerX, self.centerY + 50),
'You have run ' + str(self.curBlock) + ' blocks.'
)
self.screen.update()
for event in pygame.event.get():
if event.type == KEYDOWN:
if event.key == K_ESCAPE:
self.quitExperiment = True
elif event.key == K_END:
self.quitExperiment = True
elif event.key == K_SPACE:
target_file = self.block_list[self.curBlock]
self.curBlock += 1
self.runBlock(target_file)
if self.curBlock >= len(self.block_list):
self.screen.drawText(
(255, 255, 255),
(self.centerX, self.centerY - 50),
"Thank you, " + self.subName + "!"
)
self.screen.drawText(
(255, 255, 255),
(self.centerX, self.centerY),
"You are now done."
)
self.screen.update()
# The above "thank you" message will disappear quickly unless you introduce a pause:
self.timer.reset(1)
while self.timer[1] < 1:
self.timer.update()
self.quitExperiment = True
self.screen.close()
if __name__ == "__main__":
Adaptation_Experiment(participant_name).run()
| {"/devices/Cursor.py": ["/devices/UseMouse.py"], "/Adaptation_Experiment.py": ["/devices/Clock.py", "/devices/Cursor.py", "/devices/Monitor.py", "/dialog.py"]} |
60,822 | puzzleindex/SS_Panel_TrimePay_Bot | refs/heads/master | /main.py | # -*- coding: UTF-8 -*-
import config
import trimepay
import sql
import re
import qrcode
import PIL
import os
import time
import telebot
from telebot import types
bot = telebot.TeleBot(config.TOKEN)
@bot.message_handler(commands=['start'])
def start(message):
bot.send_message(message.chat.id,'使用本机器人需先绑定\n在网站-菜单-资料编辑页面找到二维码发送给 @%s\n绑定后发送关键字(支付宝充值或微信充值)+金额,按照提示充值即可\n例如发送支付宝充值10'%config.bindBot)
@bot.message_handler(func=lambda message:True)
def code(message):
if message.chat.type == 'private':
if message.text.startswith('支付宝充值'):
price = message.text[5:].strip()
try:
price = float(price)
except:
bot.send_message(message.chat.id,'非法金额')
return
if isinstance(price, float) == True and price > 0:
tgid = str(message.chat.id)
totalFee = int(float(price) * 100)
payType = 'ALIPAY_WAP'
data = trimepay.params(tgid,totalFee,payType)
if data is False:
bot.send_message(message.chat.id,'您的网站账户没有绑定tg账户,无法充值')
else:
data['sign'] = trimepay.sign(data)
result = trimepay.alipay_post(data)
#print()
markup = types.InlineKeyboardMarkup()
alipay_btn = types.InlineKeyboardButton('点击充值', url=result['data'])
markup.add(alipay_btn)
bot.send_message(message.chat.id,'支付宝充值%.2f元'%price,reply_markup=markup)
else:
bot.send_message(message.chat.id,'非法金额')
elif message.text.startswith('微信充值'):
price = message.text[5:].strip()
try:
price = float(price)
except:
bot.send_message(message.chat.id,'非法金额')
return
if isinstance(price, float) == True and price > 0:
tgid = str(message.chat.id)
totalFee = int(float(price) * 100)
payType = 'WEPAY_QR'
data = trimepay.params(tgid,totalFee,payType)
if data is False:
bot.send_message(message.chat.id,'您的网站账户没有绑定tg账户,无法充值')
else:
data['sign'] = trimepay.sign(data)
result = trimepay.wechat_post(data)
status = trimepay.getQrcode(result)
if status is True:
qr = open('qr.png', 'rb')
bot.send_message(message.chat.id,'微信充值%.2f元'%price)
bot.send_photo(message.chat.id,qr)
qr.close()
if os.path.exists('qr.png'):
os.remove('qr.png')
else:
print('qrcode删除失败')
else:
print('qrcode生成失败')
else:
bot.send_message(message.chat.id,'非法金额')
elif message.text == '查询余额':
money = sql.getMoney(message.chat.id)
bot.send_message(message.chat.id,'账户余额为%s'%money)
elif message.text == '套餐列表':
msg = ''
goods = sql.getGoods()
for good in goods:
msg = msg + 'id:' + str(good[0]) + '\t名称:' + good[1] + '\t价格:' + str(good[2]) + '\n'
bot.send_message(message.chat.id,msg)
elif message.text.startswith('购买套餐'):
t = int(time.time())
shopid = str(message.text[4:7].strip())
credit = 1.0
coupon = ''
try:
coupon = message.text.split()[1]
data = sql.getCoupon(coupon)
credit = 1 - float(data[5])/100
if t > int(data[3]):
bot.send_message(message.chat.id,'优惠码已过期')
return
except Exception:
pass
goods = sql.getGoods()
shopids = {}
details = {}
for good in goods:
shopids[str(good[0])] = str(good[2])
for good in goods:
details[str(good[0])] = str(good[3])
if shopid not in shopids.keys():
bot.send_message(message.chat.id,'非法shopid')
else:
price = float(shopids[shopid])
totalPrice = round(credit * price,2)
money = float(sql.getMoney(message.chat.id))
if totalPrice <= money:
status_1 = sql.Bought(sql.getUidByTgid(str(message.chat.id)),shopid,str(t),coupon,totalPrice)
status_2 = sql.UpdateUser(sql.getUidByTgid(str(message.chat.id)),totalPrice,str(t),details[shopid])
if status_1 and status_2 is True:
bot.send_message(message.chat.id,'购买成功,当前余额为%s'%sql.getMoney(message.chat.id))
else:
bot.send_message(message.chat.id,'余额不足请充值')
while True:
try:
bot.polling(none_stop=True)
except Exception:
time.sleep(10)
| {"/main.py": ["/config.py", "/trimepay.py", "/sql.py"], "/trimepay.py": ["/config.py", "/sql.py"], "/sql.py": ["/config.py"]} |
60,823 | puzzleindex/SS_Panel_TrimePay_Bot | refs/heads/master | /trimepay.py | # -*- coding: UTF-8 -*-
import config
import sql
import hashlib
import urllib
import json
import base64
import uuid
import qrcode
import PIL
import requests
def params(tgid,totalFee,payType):
#准备签名
merchantTradeNo = ''.join(str(uuid.uuid1()).split('-'))[:8].upper()
#创建paylist
uid = sql.getUidByTgid(tgid)
if uid is False:
return False
status = sql.newPaylist(uid,str(float(totalFee)/100),merchantTradeNo)
if status == True:
appId = config.trimepay_appid
notifyUrl = config.baseUrl + '/payment/notify'
returnUrl = config.baseUrl + '/user/payment/return'
data = {}
data['appId'] = appId
data['payType'] = payType
data['merchantTradeNo'] = merchantTradeNo
data['totalFee'] = str(totalFee)
data['notifyUrl'] = notifyUrl
data['returnUrl'] = returnUrl
return data
#签名
def sign(data):
arrangeData = {}
for key in sorted(data):
arrangeData[key] = data[key]
data = urllib.parse.urlencode(arrangeData)
sign = hashlib.md5((hashlib.md5(data.encode()).hexdigest() + config.trimepay_secret).encode()).hexdigest()
return sign
#支付宝post
def alipay_post(data,type='pay'):
if type == 'pay':
gatewayUri = config.gatewayUri + 'pay/go'
else:
gatewayUri = config.gatewayUri + 'refund/go'
r = requests.post(url=gatewayUri,data=data)
return r.json()
#微信post
def wechat_post(data):
result = {}
result['code'] = 0
result['data'] = 'http://cashier.hlxpay.com/#/wepay/jsapi?payData=' + str(base64.b64encode(bytes(json.dumps(data), encoding="utf8")), encoding='utf8')
result['pid'] = data['merchantTradeNo']
return result
#获取微信二维码
def getQrcode(result):
qr = qrcode.QRCode(
version=1,
error_correction=qrcode.constants.ERROR_CORRECT_L,
box_size=10,
border=4,
)
qr.add_data(result['data'])
qr.make()
img = qr.make_image()
img.save('qr.png')
return True
| {"/main.py": ["/config.py", "/trimepay.py", "/sql.py"], "/trimepay.py": ["/config.py", "/sql.py"], "/sql.py": ["/config.py"]} |
60,824 | puzzleindex/SS_Panel_TrimePay_Bot | refs/heads/master | /config.py | # -*- coding: UTF-8 -*-
TOKEN = '' #申请的充值 bot 的 Token
#魔改数据库信息
db_host = ''
db_database = ''
db_username = ''
db_password = ''
baseUrl = '' #SSPanel的config的baseUrl
bindBot = '' #SSPanel绑定的签到查询bot的username
#Trimepay
trimepay_appid = ''
trimepay_secret = ''
#此行勿动
gatewayUri = 'https://api.Trimepay.com/gateway/'
| {"/main.py": ["/config.py", "/trimepay.py", "/sql.py"], "/trimepay.py": ["/config.py", "/sql.py"], "/sql.py": ["/config.py"]} |
60,825 | puzzleindex/SS_Panel_TrimePay_Bot | refs/heads/master | /sql.py | # -*- coding: UTF-8 -*-
import config
import pymysql
import time
#数据库链接信息
def getConnect():
db = pymysql.connect(config.db_host,config.db_username,config.db_password,config.db_database)
return db
#通过tg id 获取user id
def getUidByTgid(tgid):
db = getConnect()
cursor = db.cursor()
sql = 'SELECT id FROM user WHERE telegram_id = ' + tgid
try:
cursor.execute(sql)
data = str(cursor.fetchone()[0])
except:
data = False
print('获取uid失败')
finally:
db.close()
return data
#创建paylist
def newPaylist(userid,total,tradeno):
status = False
db = getConnect()
cursor = db.cursor()
sql = "INSERT INTO `paylist` (`id`, `userid`, `total`, `status`, `tradeno`, `datetime`, `type`, `url`) VALUES (NULL, '%s', '%s', '0', '%s', '0', '0', NULL)"%(userid,total,tradeno)
try:
cursor.execute(sql)
db.commit()
status = True
except:
print('创建paylist失败')
finally:
db.close()
return status
#查询余额
def getMoney(tgid):
db = getConnect()
cursor = db.cursor()
sql = 'SELECT money FROM user WHERE telegram_id = ' + str(tgid)
try:
cursor.execute(sql)
data = str(cursor.fetchone()[0])
except:
data = False
print('查询余额失败')
finally:
db.close()
return data
#获取套餐列表
def getGoods():
db = getConnect()
cursor = db.cursor()
sql = 'SELECT * FROM shop WHERE status = 1'
try:
cursor.execute(sql)
data = cursor.fetchall()
except:
data = False
print('查询套餐列表失败')
finally:
db.close()
return data
#获取coupon
def getCoupon(coupon):
db = getConnect()
cursor = db.cursor()
sql = 'SELECT * FROM coupon WHERE code = ' + coupon
try:
cursor.execute(sql)
data = cursor.fetchone()
except:
data = False
print('获取coupon失败')
finally:
db.close()
return data
#创建Bought记录
def Bought(userid,shopid,t,coupon,price):
status = False
db = getConnect()
cursor = db.cursor()
sql = "INSERT INTO `bought` (`id`, `userid`, `shopid`, `datetime`, `renew`, `coupon`, `price`) VALUES (NULL, '%s', '%s', '%s', '0', '%s', %s)"%(userid,shopid,t,coupon,price)
try:
cursor.execute(sql)
db.commit()
status = True
except:
print('创建bought失败')
finally:
db.close()
return status
#购买套餐修改user表
def UpdateUser(userid,price,t,details):
status = False
db = getConnect()
cursor = db.cursor()
details = eval(details)
transfer_enable = int(details['bandwidth']) * 1024 * 1024 * 1024
node_connector = int(details['connector'])
_class = int(details['class'])
class_expire = int(t) + int(details['class_expire']) * 86400
class_expire = time.localtime(class_expire)
class_expire = time.strftime("%Y-%m-%d %H:%M:%S",class_expire)
if 'expire' in details.keys():
expire = int(t) + int(details['expire']) * 86400
expire = time.localtime(expire)
expire = time.strftime("%Y-%m-%d %H:%M:%S",expire)
sql = "UPDATE `user` SET `u` = 0, `d` = 0, `transfer_enable` = %d, `money` = `money` - %f, `node_connector` = %d, `last_day_t` = 0, `class` = %d, `class_expire` = str_to_date(\'%s\','%%Y-%%m-%%d %%H:%%i:%%s'), `expire_in` = str_to_date(\'%s\','%%Y-%%m-%%d %%H:%%i:%%s') WHERE id = %s"%(transfer_enable,price,node_connector,_class,class_expire,expire,userid)
else:
sql = "UPDATE `user` SET `u` = 0, `d` = 0, `transfer_enable` = %d, `money` = `money` - %f, `node_connector` = %d, `last_day_t` = 0, `class` = %d, `class_expire` = str_to_date(\'%s\','%%Y-%%m-%%d %%H:%%i:%%s') WHERE id = %s"%(transfer_enable,price,node_connector,_class,class_expire,userid)
try:
cursor.execute(sql)
db.commit()
status = True
except:
print('更新user失败')
finally:
db.close()
return status
| {"/main.py": ["/config.py", "/trimepay.py", "/sql.py"], "/trimepay.py": ["/config.py", "/sql.py"], "/sql.py": ["/config.py"]} |
60,826 | 2021-Sillicon-Valley-Internship-TeamG/poc_beta | refs/heads/master | /app/models.py | from app import db
class img_upload(db.Model):
__tablename__ = 'imgdir_table'
img_type = db.Column(db.String())
imgdir = db.Column(db.Text,primary_key=True)
def __init__(self, img_type, imgdir):
self.img_type = img_type
self.imgdir = imgdir
# def __repr__(self):
# return '<id {}>'.format(self.name)
# def serialize(self):
# return {
# 'img_type': self.img_type,
# 'imgdir': self.imgdir,
# } | {"/app/models.py": ["/app/__init__.py"], "/app/dbcon.py": ["/app/__init__.py"]} |
60,827 | 2021-Sillicon-Valley-Internship-TeamG/poc_beta | refs/heads/master | /app/__init__.py | # Controller file : call & render html, data process
import os
from flask import Flask, render_template, request
from werkzeug.utils import secure_filename
from app.main import test_kakao
from flask_cors import CORS
import configparser
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
config = configparser.ConfigParser()
config.read('config.ini')
app = Flask(__name__)
db = SQLAlchemy(app)
migrate = Migrate(app, db)
app.config['SQLALCHEMY_DATABASE_URI'] = config['DEFAULT']['SQLALCHEMY_DATABASE_URI']
# 추가하지 않을 시 FSADeprecationWarning 주의가 떠서 추가해 줌
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
CORS(app)
from app import dbcon
@app.route('/detect', methods=['POST'])
def detect():
print("hihi")
if request.form['image_type'] == "0":
img_url = request.form['image_url']
detect_result = test_kakao.detect_adult(img_url, 0)
dbcon.add('img_url',img_url)
return {"result" : detect_result}
elif request.form['image_type'] == "1" :
input_img = request.files['file']
input_img_filename = secure_filename(input_img.filename)
print(input_img)
input_img.save(os.path.join('./data/', input_img_filename))
detect_result = kakao_api.detect_adult('./data/'+input_img_filename, 1)
dbcon.add('img_file','./data/'+img_filename)
return {'result' : detect_result}
| {"/app/models.py": ["/app/__init__.py"], "/app/dbcon.py": ["/app/__init__.py"]} |
60,828 | 2021-Sillicon-Valley-Internship-TeamG/poc_beta | refs/heads/master | /app/dbcon.py | from app import db
from . import models
def add(img_type,imgdir):
img = models.img_upload(img_type,imgdir)
db.session.add(img)
db.session.commit()
def read():
return db.session.query(models.img_upload.imgdir).all()
def count():
return db.session.query(models.img_upload).count() | {"/app/models.py": ["/app/__init__.py"], "/app/dbcon.py": ["/app/__init__.py"]} |
60,830 | no-i-in-team/twitoff23 | refs/heads/main | /twitoff/models.py | """SQLAlchemy Database"""
from flask_sqlalchemy import SQLAlchemy
from flask_login import UserMixin
DB = SQLAlchemy()
# User Table using sqlalchemy syntax
class User(DB.Model):
"""Twitter users that correspond to tweets"""
id = DB.Column(DB.BigInteger, primary_key=True)
name = DB.Column(DB.String, nullable=False)
full_name = DB.Column(DB.String, nullable=False)
newest_tweet_id = DB.Column(DB.BigInteger)
def __repr__(self):
return "<User: '{}'>".format(self.name)
# Tweet Table
class Tweet(DB.Model):
"""Twitter tweets that correspond to users"""
id = DB.Column(DB.BigInteger, primary_key=True)
text = DB.Column(DB.Unicode(300))
vect = DB.Column(DB.PickleType, nullable=False)
user_id = DB.Column(DB.BigInteger, DB.ForeignKey("user.id"), nullable=False)
user = DB.relationship("User", backref=DB.backref("tweets", lazy=True))
def __repr__(self):
return "<Tweet: '{}'>".format(self.text)
# Login Credentials
class Credential(UserMixin, DB.Model):
userid = DB.Column(DB.Integer, primary_key=True) #sqlite_autoincrement=True?
username = DB.Column(DB.String(50), unique=True)
password = DB.Column(DB.String(50))
email = DB.Column(DB.String, unique=True)
def __repr__(self):
return "<Credentials: '{}'>".format(self.username) | {"/twitoff/main.py": ["/twitoff/models.py", "/twitoff/predict.py"], "/twitoff/predict.py": ["/twitoff/models.py"]} |
60,831 | no-i-in-team/twitoff23 | refs/heads/main | /twitoff/main.py | """Main main/routing file for Twitoff"""
from os import getenv
from flask import Flask, render_template, request, Blueprint
from flask_login import LoginManager, login_required, current_user
from .models import DB, User
from .twitter import aou_user, uall_users
from .predict import predict_user
main = Blueprint('main', __name__)
@main.route("/")
@login_required
def root():
return render_template("base.html", title= "Home",
cred= current_user.name, users=User.query.all())
@main.route("/compare", methods=["POST"])
def compare():
user0, user1 = sorted([request.values["user0"],
request.values["user1"]])
if user0 == user1:
message = "Cannot compare a user to itself!"
else:
prediction = predict_user(
user0, user1, request.values["tweet_text"])
message = "'{}' is more likely a tweet by @{} than @{}".format(
request.values["tweet_text"], user1 if prediction else user0, user0 if prediction else user1)
return render_template("prediction.html", title="Prediction", message=message)
@main.route("/user/", methods = ["POST"])
@main.route("/user/<name>", methods = ["GET"])
def user(name=None, message=""):
name = name or request.values["user_name"]
try:
if request.method == "POST":
aou_user(name)
message = "User {} successfully added!".format(name)
tweets = User.query.filter(User.name == name).one().tweets
except Exception as e:
message = "Error adding '{}': {}".format(name, e)
tweets = []
return render_template("user.html",
user=User.query.filter(User.name == name).one(),
tweets=tweets,
message=message)
@main.route("/update")
def update():
"""Update users"""
uall_users()
return render_template("base.html", title="Users Updated!", users=User.query.all())
@main.route("/reset")
def reset():
"""Reset database"""
DB.drop_all()
DB.create_all()
return render_template("base.html", title="RESET",
users=User.query.all())
| {"/twitoff/main.py": ["/twitoff/models.py", "/twitoff/predict.py"], "/twitoff/predict.py": ["/twitoff/models.py"]} |
60,832 | no-i-in-team/twitoff23 | refs/heads/main | /twitoff/predict.py | """Predicts who is more likely to say a hypothetical tweet"""
import numpy as np
from sklearn.linear_model import LogisticRegression
from .models import User
from .twitter import vectorize_tweet
def predict_user(user0_name, user1_name, hypothetical_tweet):
"""Determines which user is most lilely the tweet's author"""
# Array of vectors
user0 = User.query.filter(User.name == user0_name).one()
user1 = User.query.filter(User.name == user1_name).one()
user0_vectors = np.array([tweet.vect for tweet in user0.tweets])
user1_vectors = np.array([tweet.vect for tweet in user1.tweets])
vectors = np.vstack([user0_vectors, user1_vectors])
# Labels
labels = np.concatenate(
[np.zeros(len(user0.tweets)), np.ones(len(user1.tweets))])
model = LogisticRegression().fit(vectors, labels)
hv_tweet = vectorize_tweet(hypothetical_tweet).reshape(1, -1)
return model.predict(hv_tweet)
| {"/twitoff/main.py": ["/twitoff/models.py", "/twitoff/predict.py"], "/twitoff/predict.py": ["/twitoff/models.py"]} |
60,861 | gogbajbobo/3d-fourier | refs/heads/master | /generator.py | """
Generate porous pictures
Code taken from PoreSpy with adding param k to blobs() function to make orthogonal anisotropy
"""
import scipy as sp
from scipy import ndimage as spim
from scipy import special
import numpy as np
import skimage as skim
import skimage.filters as filters
import matplotlib.pyplot as plt
import time
from datetime import timedelta
import cv2
def time_measurement(func):
def wrapper(*args, **kwargs):
start_time = time.perf_counter()
result = func(*args, **kwargs)
finish_time = time.perf_counter()
elapsed_time = finish_time - start_time
print(f'{ func.__name__ }() elapsed time: { timedelta(seconds=elapsed_time) }')
return result
return wrapper
@time_measurement
def norm_to_uniform(im, scale=None):
if scale is None:
scale = [im.min(), im.max()]
im = (im - sp.mean(im)) / sp.std(im)
im = 1 / 2 * special.erfc(-im / sp.sqrt(2))
im = (im - im.min()) / (im.max() - im.min())
im = im * (scale[1] - scale[0]) + scale[0]
return im
def blobs(shape, k, porosity: float = 0.5, blobiness: int = 1, show_figs: bool = False):
blobiness = sp.array(blobiness)
shape = sp.array(shape)
if sp.size(shape) == 1:
shape = sp.full((3, ), int(shape))
sigma = sp.mean(shape)/(40*blobiness)
sigma = sp.array(k) * sigma
im = sp.random.random(shape)
im = spim.gaussian_filter(im, sigma=sigma)
im = norm_to_uniform(im, scale=[0, 1])
im_test, _ = image_histogram_equalization(im)
im_test -= np.min(im_test)
im_test *= 1.0 / np.max(im_test)
im_test_opencv = opencv_histogram_equalization(im)
im_test_opencv -= np.min(im_test_opencv)
im_test_opencv = im_test_opencv / np.max(im_test_opencv)
im_test_clahe = opencv_clahe_hist_equal(im)
im_test_clahe -= np.min(im_test_clahe)
im_test_clahe = im_test_clahe / np.max(im_test_clahe)
if porosity:
im = im < porosity
im_test = im_test < porosity
im_test_opencv = im_test_opencv < porosity
im_test_clahe = im_test_clahe < porosity
print(np.sum(im)/im.ravel().shape[0])
print(np.sum(im_test)/im_test.ravel().shape[0])
print(np.sum(im_test_opencv) / im_test_opencv.ravel().shape[0])
print(np.sum(im_test_clahe) / im_test_clahe.ravel().shape[0])
if show_figs:
show_image_and_histogram(im, 'Porespy norm2uniform')
show_image_and_histogram(im_test, 'numpy hist eq')
show_image_and_histogram(im_test_opencv, 'opencv hist eq')
show_image_and_histogram(im_test_clahe, 'opencv clahe hist eq')
if show_figs:
plt.show()
return im
def show_image_and_histogram(im, title=None):
im2show = im[0, :, :] if np.size(im.shape) == 3 else im
plt.figure()
plt.imshow(im2show, cmap='gray')
if title:
plt.title(title)
# g_im = np.ravel(im)
# plt.figure()
# plt.hist(g_im, 255, [0, 1], density=True)
# if title:
# plt.title(title)
@time_measurement
def image_histogram_equalization(image, number_bins=256):
# from http://www.janeriksolem.net/2009/06/histogram-equalization-with-python-and.html
# get image histogram
image_histogram, bins = np.histogram(image.flatten(), number_bins, density=True)
cdf = image_histogram.cumsum() # cumulative distribution function
cdf = 255 * cdf / cdf[-1] # normalize
# use linear interpolation of cdf to find new pixel values
image_equalized = np.interp(image.flatten(), bins[:-1], cdf)
return image_equalized.reshape(image.shape), cdf
@time_measurement
def opencv_histogram_equalization(im):
_im = np.copy(im)
dim = np.size(_im.shape)
if dim == 2:
img = np.uint8(cv2.normalize(_im, None, 0, 255, cv2.NORM_MINMAX))
return cv2.equalizeHist(img)
elif dim == 3:
for i in range(_im.shape[0]):
im_slice = _im[i, :, :]
im_slice = np.uint8(cv2.normalize(im_slice, None, 0, 255, cv2.NORM_MINMAX))
im_slice = cv2.equalizeHist(im_slice)
_im[i, :, :] = im_slice
return _im
else:
raise ValueError('image dimension error')
@time_measurement
def opencv_clahe_hist_equal(im):
_im = np.copy(im)
dim = np.size(_im.shape)
clahe = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8, 8))
if dim == 2:
img = np.uint8(cv2.normalize(_im, None, 0, 255, cv2.NORM_MINMAX))
return clahe.apply(img)
elif dim == 3:
for i in range(_im.shape[0]):
im_slice = _im[i, :, :]
im_slice = np.uint8(cv2.normalize(im_slice, None, 0, 255, cv2.NORM_MINMAX))
im_slice = clahe.apply(im_slice)
_im[i, :, :] = im_slice
return _im
else:
raise ValueError('image dimension error')
def add_noise_to_image(im, high_value=1, low_value=0):
"""
Naive addition of noise to image
"""
im = im.astype(np.float)
im[im > 0] = high_value
im[im == 0] = low_value
im = skim.util.random_noise(im, mode='poisson')
return filters.gaussian(im, sigma=1)
if __name__ == '__main__':
pass
| {"/gen_hist_3d.py": ["/generator.py"], "/gen_test.py": ["/generator.py"], "/gen_fft.py": ["/generator.py"]} |
60,862 | gogbajbobo/3d-fourier | refs/heads/master | /gen_hist_3d.py | """
Generate 3D porous picture and calc gray values histogram
"""
import matplotlib.pyplot as plt
import numpy as np
import generator
im_size = 200
im_shape = np.ones(3, dtype=int) * im_size
shape_ranges = tuple(int(i * im_size) for i in (0.0125, 0.025, 0.05, 0.1, 0.25, 0.5, 1))
nrows = 3
ncols = 7
figsize = (28, 9)
fig, axes = plt.subplots(nrows=nrows, ncols=ncols, figsize=figsize)
plt.tight_layout()
im = generator.blobs(im_shape, k=[1, 1, 1], blobiness=1)
for i, r in enumerate(shape_ranges):
# show generated images
center = im_size // 2
start = center - r//2
finish = center + r // 2
axes[0, i].imshow(im[start:finish, start:finish, center], cmap='gray')
im = generator.add_noise_to_image(im, high_value=0.7, low_value=0.3)
for i, r in enumerate(shape_ranges):
# show generated images with noise
center = im_size // 2
start = center - r//2
finish = center + r // 2
axes[1, i].imshow(im[start:finish, start:finish, center], cmap='gray')
for i, r in enumerate(shape_ranges):
# show images gray values histogram
center = im_size // 2
start = center - r//2
finish = center + r // 2
g_im = im[start:finish, start:finish, start:finish]
g_im = np.ravel(g_im)
axes[2, i].hist(g_im, 255, [0, 1], density=True)
plt.show()
| {"/gen_hist_3d.py": ["/generator.py"], "/gen_test.py": ["/generator.py"], "/gen_fft.py": ["/generator.py"]} |
60,863 | gogbajbobo/3d-fourier | refs/heads/master | /gen_test.py | """
Generate 2D porous picture and calc gray values histogram
"""
import matplotlib.pyplot as plt
import numpy as np
import generator
dim = 3
im_size = 400
im_shape = np.ones(dim, dtype=int) * im_size
k = np.ones(dim)
image = generator.blobs(im_shape, k=k, show_figs=True)
# plt.figure()
# plt.imshow(image, cmap='gray')
# for i, r in enumerate(shape_ranges):
# # show images gray values histogram
# center = im_size // 2
# start = center - r//2
# finish = center + r // 2
# g_im = im[start:finish, start:finish]
# g_im = np.ravel(g_im)
# axes[2, i].hist(g_im, 255, [0, 1], density=True)
# plt.show()
| {"/gen_hist_3d.py": ["/generator.py"], "/gen_test.py": ["/generator.py"], "/gen_fft.py": ["/generator.py"]} |
60,864 | gogbajbobo/3d-fourier | refs/heads/master | /gen_fft.py | """
Generate 2D porous picture and fft it's internal parts
"""
import matplotlib.pyplot as plt
import numpy as np
import generator
im_size = 1000
im_shape = np.ones(2, dtype=int) * im_size
shape_ranges = tuple(int(i * im_size) for i in (0.0125, 0.025, 0.05, 0.1, 0.25, 0.5, 1))
nrows = 4
ncols = 7
figsize = (28, 12)
fig, axes = plt.subplots(nrows=nrows, ncols=ncols, figsize=figsize)
plt.tight_layout()
im = generator.blobs(im_shape, k=[1, 0.25])
for i, r in enumerate(shape_ranges):
# show generated images
center = im_size // 2
start = center - r//2
finish = center + r // 2
axes[0, i].imshow(im[start:finish, start:finish], cmap='gray')
im = generator.add_noise_to_image(im, high_value=0.7, low_value=0.3)
for i, r in enumerate(shape_ranges):
# show generated images with noise
center = im_size // 2
start = center - r//2
finish = center + r // 2
axes[1, i].imshow(im[start:finish, start:finish], cmap='gray')
for i, r in enumerate(shape_ranges):
# show fft amplitudes
center = im_size // 2
start = center - r//2
finish = center + r // 2
f_im = np.fft.fft2(im[start:finish, start:finish])
f_im_abs = np.fft.fftshift(np.log(1 + np.abs(f_im)))
# if r > 100:
# center = r // 2
# f_im_abs = f_im_abs[center-50:center+50, center-50:center+50]
axes[2, i].imshow(f_im_abs)
axes[3, i].plot(f_im_abs[(finish - start) // 2, :])
# for i, r in enumerate(shape_ranges):
# # show fft phase
# center = im_size // 2
# start = center - r//2
# finish = center + r // 2
# f_im = np.fft.fft2(im[start:finish, start:finish])
# f_im_angle = np.fft.fftshift(np.angle(f_im))
# # if r > 100:
# # center = r // 2
# # f_im_angle = f_im_angle[center-50:center+50, center-50:center+50]
# axes[3, i].imshow(f_im_angle)
plt.show()
| {"/gen_hist_3d.py": ["/generator.py"], "/gen_test.py": ["/generator.py"], "/gen_fft.py": ["/generator.py"]} |
60,865 | gogbajbobo/3d-fourier | refs/heads/master | /gen_mem_profile.py | from typing import List
import scipy as sp
import scipy.ndimage as spim
from scipy import special
import matplotlib.pyplot as plt
from memory_profiler import profile
import sys
@profile
def blobs(
shape: List[int],
porosity: float = 0.5,
blobiness: int = 1,
show_images: bool = False,
random_seed: int = None
):
blobiness = sp.array(blobiness)
shape = sp.array(shape)
if sp.size(shape) == 1:
shape = sp.full((3, ), int(shape))
sigma = sp.mean(shape) / (40 * blobiness)
sp.random.seed(random_seed)
im = sp.random.random(shape).astype(sp.float32)
im = spim.gaussian_filter(im, sigma=sigma)
show_image(im, show_images=show_images)
im = norm_to_uniform(im, scale=[0, 1])
show_image(im, show_images=show_images)
if porosity:
im = im < porosity
show_image(im, show_images=show_images)
return im
@profile
def norm_to_uniform(im, scale=None):
if scale is None:
scale = [im.min(), im.max()]
im = (im - sp.mean(im)) / sp.std(im)
im = 1 / 2 * special.erfc(-im / sp.sqrt(2))
im = (im - im.min()) / (im.max() - im.min())
im = im * (scale[1] - scale[0]) + scale[0]
return im
def show_image(im, show_images=False):
if not show_images:
return
plt.figure()
plt.imshow(im, cmap='gray')
@profile
def main():
size = 200
dimensions = 3
show_images = False
blobs(
shape=sp.ones(dimensions, dtype=int) * size,
blobiness=1,
show_images=show_images,
random_seed=1
)
if show_images:
plt.show()
if __name__ == '__main__':
main()
| {"/gen_hist_3d.py": ["/generator.py"], "/gen_test.py": ["/generator.py"], "/gen_fft.py": ["/generator.py"]} |
60,866 | gogbajbobo/3d-fourier | refs/heads/master | /main2d.py | import porespy as ps
import matplotlib.pyplot as plt
import skimage as skim
import skimage.filters as filters
im = ps.generators.blobs([100, 100])
plt.figure()
plt.imshow(im)
im1 = skim.util.random_noise(im, var=0.125)
im1 = filters.gaussian(im1)
plt.figure()
plt.imshow(im1)
plt.figure()
plt.hist(im1, 100, facecolor='blue', alpha=0.5)
plt.show()
| {"/gen_hist_3d.py": ["/generator.py"], "/gen_test.py": ["/generator.py"], "/gen_fft.py": ["/generator.py"]} |
60,867 | gogbajbobo/3d-fourier | refs/heads/master | /main.py | import numpy as np
import matplotlib.pyplot as plt
def plot_some(a):
b = np.fft.fft(a)
plt.figure(figsize=(14, 3))
plt.subplot(121)
plt.plot(a)
plt.subplot(122)
_b = np.fft.fftshift(np.log(1 + np.abs(b)))
center = _b.shape[0]//2
_b = _b[center-50:center+50]
plt.plot(_b)
# plt.subplot(133)
# __b = np.fft.fftshift(np.angle(b))
# plt.plot(__b)
return _b
a = np.random.rand(100)
aa = np.tile(a, 10)
plot_some(aa)
plot_some(aa[0:666])
plot_some(aa[0:333])
plot_some(aa[0:100])
# amp = np.empty((3, 100))
#
# for i in range(0,3):
#
# amp[i:] = plot_some(np.roll(a, 33 * i))
# # plot_some(np.flip(a))
#
# print(np.sum(amp[0]-amp[1]))
# print(np.sum(amp[0]-amp[2]))
plt.show()
| {"/gen_hist_3d.py": ["/generator.py"], "/gen_test.py": ["/generator.py"], "/gen_fft.py": ["/generator.py"]} |
60,868 | DnWTechnology/Cubic-Spline-Interpolation | refs/heads/master | /cubicsplinedollitle.py | '''Author - MD ELIOUS ALI MONDAL
Created - 28/5/2017'''
#approximation via cubic splines
from sined import xi
from sined import yi
ai = yi[:]
x = float(input('Enter the value of x : '))
j = 0
for i in range(len(xi)):
if x > xi[i]:
if x < xi[i+1]:
j = i
else:
continue
def h(i):
'''
takes integer i and returns the width of the interval (x(i+1),x(i))
'''
if i < len(xi)-1:
return xi[i+1]-xi[i]
def a(i):
'''
takes in integer i and returns the ith entry in the x matrix of equation
Ax = b
'''
if i == 0 or i == len(xi)-1:
return 0
else:
return ((3*(ai[i+1]-ai[i])) / h(i)) - ((3*(ai[i]-ai[i-1])) / h(i-1))
def l(i):
if i == 0 or i == len(xi)-1:
return 1
def mu(i):
if i == 0 :
return 1
elif i == len(xi)-1:
return 0
else:
return ai[i]-((h(i-1)**2)/mu(i-1))
def z(i):
if i == 0 or i == len(xi)-1:
return 0
else:
return a(i)- ((h(i-1)*z(i-1)) / mu(i-1))
def c(j):
'''
takes in the value of j and returns c(jth) constant
'''
if j == 0 or j == len(xi)-1:
return 0
else:
return z(j) - mu(j)*c(j+1)
def b(j):
'''
takes in the value of j and returns b(jth) constant
'''
return (ai[j+1] - ai[j])/h(j) - h(j)*(c(j+1)+2*c(j))/3
def d(j):
'''
takes in the value of j and returns d(jth) constant
'''
return (c(j+1)-c(j))/(3*h(j))
def S(x):
'''
takes the value of x znd returns the value of spline at tht point
'''
return ai[j] + b(j)*(x-xi[j]) + c(j)*((x-xi[j])**2) + d(j)*((x-xi[j])**3)
print('The value of y on the cubic spline formed by given data points is ',S(x))
| {"/cubicsplinedollitle.py": ["/sined.py"]} |
60,869 | DnWTechnology/Cubic-Spline-Interpolation | refs/heads/master | /sined.py | '''Author - MD ELIOUS ALI MONDAL
Created - 28/5/2017'''
import math
xi = []
i = 0
while i <= math.pi/2:
xi.append(i)
i += 0.1
yi = [math.sin(i) for i in xi]
| {"/cubicsplinedollitle.py": ["/sined.py"]} |
60,877 | Krash13/vk_bot | refs/heads/master | /pars.py | from selenium import webdriver
from bs4 import BeautifulSoup
def print_score(url):
driver = webdriver.PhantomJS()
driver.get(url)
main_page = driver.page_source
soup = BeautifulSoup(main_page, 'lxml')
scoreA = soup.find("div", { "class" : "ig__stat-scoreA" }).text
scoreB = soup.find("div", {"class": "ig__stat-scoreB"}).text
names = soup.findAll("div", { "class" : "ig__stat-team-name" })
nameA=names[0].text
nameB = names[1].text
return " {} {}:{} {}".format(nameA,scoreA,scoreB,nameB)
| {"/main.py": ["/pars.py"]} |
60,878 | Krash13/vk_bot | refs/heads/master | /main.py | import vk_api
from vk_api.bot_longpoll import VkBotLongPoll, VkBotEventType
from vk_api.utils import get_random_id
from pars import print_score
def vkbot():
vk_session=vk_api.VkApi(token='fcb715bac83de58c82745490f78b4bc7264bf23035dbff8d35c1531193f8acc43113122ad9866cb78e6a6') #Сообщество https://vk.com/club192951175
longpoll=VkBotLongPoll(vk_session,'192951175')
vk = vk_session.get_api()
for event in longpoll.listen():
if event.type == VkBotEventType.MESSAGE_NEW:
print('Новое сообщение:')
print('Для меня от: ', end='')
print(event.obj.message["peer_id"])
print('Текст:', event.obj.message["text"])
print()
if event.obj.message["text"]=="!счёт" or event.obj.message["text"]=="!счет":
text=print_score("http://ig.pro100basket.ru/game/?id=80466&tab=0&compId=42127®ion=40120&db=asb")
vk.messages.send(
user_id=event.obj.message["peer_id"],
random_id=get_random_id(),
message=text
)
vkbot()
| {"/main.py": ["/pars.py"]} |
60,879 | reparadocs/asgard | refs/heads/master | /polls/urls.py | from django.urls import path
from . import views
urlpatterns = [
path('vote', views.SubmitVote.as_view(), name='vote'),
path('status', views.GetStatus.as_view(), name='status'),
path('question', views.SubmitQuestion.as_view(), name='question'),
path('comment', views.CommentView.as_view(), name='comment'),
] | {"/polls/views.py": ["/polls/models.py", "/polls/serializers.py"], "/polls/serializers.py": ["/polls/models.py"]} |
60,880 | reparadocs/asgard | refs/heads/master | /polls/views.py | from django.shortcuts import render
from .models import *
from .serializers import *
from rest_framework.views import APIView
from rest_framework import status
from rest_framework.response import Response
from django.utils import timezone
from datetime import timedelta
class SubmitVote(APIView):
def post(self, request, format=None):
serializer = VoteSerializer(data=request.data)
if serializer.is_valid():
if Vote.objects.filter(user_id=serializer.validated_data['user_id'], chosen__question=serializer.validated_data['chosen'].question).count() > 0:
return Response("Duplicate vote", status=status.HTTP_400_BAD_REQUEST)
else:
serializer.save()
return Response(serializer.data)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
class GetStatus(APIView):
def get(self, request, format=None):
now = timezone.now()
delta = timedelta(seconds=30)
question = Question.objects.order_by('-time').first()
if question:
status_info = {'status': 'results'}
if (question.time + delta) > now:
status_info = {'status': 'question'}
serializer = QuestionSerializer(question)
status_info.update(serializer.data)
return Response(status_info)
else:
return Response({'status': 'null'})
class SubmitQuestion(APIView):
def post(self, request, format=None):
serializer = SubmitQuestionSerializer(data=request.data)
if serializer.is_valid():
q = Question(text=serializer.validated_data['question'])
q.save()
for option in serializer.validated_data['options']:
o = Option(text=option, question=q)
o.save()
return Response(serializer.data)
else:
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
class CommentView(APIView):
def get(self, request, format=None):
comments = Comment.objects.order_by('-id')[:20]
serializer = CommentSerializer(comments, many=True)
return Response(serializer.data)
def post(self, request, format=None):
serializer = CommentSerializer(data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
| {"/polls/views.py": ["/polls/models.py", "/polls/serializers.py"], "/polls/serializers.py": ["/polls/models.py"]} |
60,881 | reparadocs/asgard | refs/heads/master | /polls/migrations/0001_initial.py | # Generated by Django 2.2.6 on 2019-10-31 01:25
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Option',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('text', models.CharField(max_length=100)),
],
),
migrations.CreateModel(
name='Question',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('text', models.CharField(max_length=500)),
('time', models.DateTimeField(auto_now_add=True)),
],
),
migrations.CreateModel(
name='Vote',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('user_id', models.CharField(max_length=100)),
('chosen', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='polls.Option')),
],
),
migrations.AddField(
model_name='option',
name='question',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='polls.Question'),
),
]
| {"/polls/views.py": ["/polls/models.py", "/polls/serializers.py"], "/polls/serializers.py": ["/polls/models.py"]} |
60,882 | reparadocs/asgard | refs/heads/master | /polls/serializers.py | from rest_framework import serializers
from .models import *
from django.core.exceptions import ObjectDoesNotExist
class VoteSerializer(serializers.ModelSerializer):
class Meta:
model = Vote
exclude = ('id',)
class OptionSerializer(serializers.ModelSerializer):
votes = serializers.IntegerField()
class Meta:
model = Option
exclude = ()
class CommentSerializer(serializers.ModelSerializer):
class Meta:
model = Comment
exclude = ('id',)
class QuestionSerializer(serializers.ModelSerializer):
option_set = OptionSerializer(many=True)
class Meta:
model = Question
exclude = ('id',)
class SubmitQuestionSerializer(serializers.Serializer):
question = serializers.CharField(max_length=500)
options = serializers.ListField(child=serializers.CharField(max_length=100)) | {"/polls/views.py": ["/polls/models.py", "/polls/serializers.py"], "/polls/serializers.py": ["/polls/models.py"]} |
60,883 | reparadocs/asgard | refs/heads/master | /polls/models.py | from django.db import models
class Question(models.Model):
text = models.CharField(max_length=500)
time = models.DateTimeField(auto_now_add=True)
class Option(models.Model):
text = models.CharField(max_length=100)
question = models.ForeignKey(Question, on_delete=models.CASCADE)
@property
def votes(self):
return self.vote_set.count()
class Vote(models.Model):
chosen = models.ForeignKey(Option, on_delete=models.CASCADE)
user_id = models.CharField(max_length=100)
class Comment(models.Model):
text = models.CharField(max_length=500) | {"/polls/views.py": ["/polls/models.py", "/polls/serializers.py"], "/polls/serializers.py": ["/polls/models.py"]} |
60,884 | kswapd/crypto-trading-bot | refs/heads/master | /fetch_huobi.py | #! /usr/bin/python
#-*-coding:utf-8-*-
import urllib.request
import json
import sys, time
import curses
import hmac,hashlib,base64
import conf
import console_view as cv
import logging
import requests
import datetime
import collections
class fetch_huobi(cv.console_view):
def __init__(self, x = 0, y = 16, width = 80, height = 15, is_view = True):
#cv.console_view.__init__(self, x, y, width, height, is_view)
self.is_stop = False
self.num = 50
self.pos_y = 2
self.target_symbol = ['ltcusdt']
#self.coin_url = "https://api.coinmarketcap.com/v1/ticker/?limit=%d"%self.num
self.base_url_inner = 'https://api.huobipro.com'
self.base_url_outer = 'https://api.huobi.pro'
#self.base_url = self.base_url_inner
self.base_url = self.base_url_outer
self.trade_base_url ='https://poloniex.com/tradingApi'
self.order_book_url = 'https://poloniex.com/public?command=returnOrderBook&¤cyPair=all&depth=1'
self.send_headers = {
'Content-Type':'application/x-www-form-urlencoded',
'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.71 Safari/537.36',
'Cookie':'__cfduid=d92eb21c1dd0e150a8e730ef1e8780fd61516264900; cf_clearance=e61fba35a2c2bdc9cd35af99cb5ca9112244f353-1516613184-1800'
}
keys_conf = conf.TradeKeys()
self.cur_balances = {}
self.apikey = keys_conf.keys_info['huobi']['public']
self.secret = keys_conf.keys_info['huobi']['secret']
##self.apikey = 'aaa'
#self.secret = 'bbb'
#self.display_pos = {'x':0, 'y':16, 'width':80, 'height':15}
#print(self.secret)
#print(self.apikey)
self.monitor_info = {
'time':time.time(),
'BTC':{'last':{'price':-1, 'num':-1}, 'bid':{'price':-1, 'num':-1}, 'ask':{'price':-1, 'num':-1}, 'change':-1, 'isFrozen':-1},
'LTC':{'last':{'price':-1, 'num':-1}, 'bid':{'price':-1, 'num':-1}, 'ask':{'price':-1, 'num':-1}, 'change':-1, 'isFrozen':-1},
'ETH':{'last':{'price':-1, 'num':-1}, 'bid':{'price':-1, 'num':-1}, 'ask':{'price':-1, 'num':-1}, 'change':-1, 'isFrozen':-1},
'XRP':{'last':{'price':-1, 'num':-1}, 'bid':{'price':-1, 'num':-1}, 'ask':{'price':-1, 'num':-1}, 'change':-1, 'isFrozen':-1},
'DASH':{'last':{'price':-1, 'num':-1}, 'bid':{'price':-1, 'num':-1}, 'ask':{'price':-1, 'num':-1}, 'change':-1,'isFrozen':-1},
'DOGE':{'last':{'price':-1, 'num':-1}, 'bid':{'price':-1, 'num':-1}, 'ask':{'price':-1, 'num':-1}, 'change':-1,'isFrozen':-1}
}
self.symbol_info_pair = {'btcusdt':'BTC','ltcusdt':'LTC','USDT_ETH':'ETH','USDT_XRP':'XRP', 'BTC_DOGE':'DOGE', 'USDT_DASH':'DASH'}
self.trade_info_pair = {'btcusdt':'btc','ltcusdt':'ltc','xrpusdt':'xrp'}
self.trade_info_pair_inv = {}
for key,val in self.trade_info_pair.items():
self.trade_info_pair_inv[val] = key
def stop(self):
self.is_stop = True
print('stopped')
def sell(self, symbol, price, num):
logging.info('start sell:%s,%.2f,%.5f'%(symbol, price, num))
self.get_balance()
self.base_url = self.base_url_inner
sub_path = '/v1/order/orders/place'
self.send_headers = {
'Accept': 'application/json',
'Content-Type':'application/json',
'User-Agent':'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:53.0) Gecko/20100101 Firefox/53.0'
}
msg = collections.OrderedDict()
msg['AccessKeyId'] = self.apikey
msg['SignatureMethod'] = 'HmacSHA256'
msg['SignatureVersion'] = '2'
msg['Timestamp'] = datetime.datetime.utcnow().strftime("%Y-%m-%dT%H:%M:%S")
msg_Method = 'POST\n'
msg_Url = self.base_url[8:]+'\n'
msg_Path = sub_path + '\n'
message_head = msg_Method+msg_Url+msg_Path
message_param = urllib.urlencode(msg)
message_all = message_head + message_param
#print(message_all)
self.sell_url = self.base_url + sub_path
signature = base64.b64encode(hmac.new(self.secret, message_all, digestmod=hashlib.sha256).digest())
#signature = signature.decode()
msg['Signature'] = signature.decode()
#req_url = self.sell_url + '?' + 'AccessKeyId='+msg['AccessKeyId']+'&SignatureMethod='+msg['SignatureMethod']+'&SignatureVersion='+ \
#msg['SignatureVersion']+'&Timestamp='+urllib.quote(msg['Timestamp'])+'&Signature='+urllib.quote(signature)
req_url = self.sell_url + '?' + urllib.urlencode(msg)
logging.info(req_url)
if(not self.cur_balances.has_key(symbol)):
logging.info('not get this symbol:%s, return'%symbol)
return
to_sell_num = num
if self.cur_balances[symbol] < to_sell_num:
to_sell_num = self.cur_balances[symbol]
#if to_sell_num*price < 1:
# logging.info('total must > 1, drop this order')
# return
logging.info('selling num:%.5f'%to_sell_num)
#post_data = {}
post_data = collections.OrderedDict()
post_data['account-id'] = '991115'
post_data['amount'] = '%.2f'%to_sell_num
post_data['price'] = '%.2f'%price
post_data['source'] = 'api'
post_data['symbol'] = self.trade_info_pair_inv[symbol] #ltcusdt
post_data['type'] = 'sell-limit'
post_data_enc = urllib.urlencode(post_data)
#req = urllib.request.Request(req_url, post_data_enc)
post_data_dump = json.dumps(post_data)
logging.info(post_data_dump)
try:
ret = requests.post(req_url, data=post_data_dump, headers=self.send_headers)
json_obj = json.loads(ret.text)
#res = urllib.request.urlopen(req, timeout=5)
#page = res.read()
#json_obj = json.loads(page)
logging.info('sell success'+'{:}'.format(json_obj))
except e:
err = 'sell at huobi error'
logging.info(err)
logging.info(e)
time.sleep(1)
def buy(self, symbol, price, num):
logging.info('start buy:%s,%.2f,%.5f'%(symbol, price, num))
self.get_balance()
self.base_url = self.base_url_inner
sub_path = '/v1/order/orders/place'
self.send_headers = {
'Accept': 'application/json',
'Content-Type':'application/json',
'User-Agent':'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:53.0) Gecko/20100101 Firefox/53.0'
}
msg = collections.OrderedDict()
msg['AccessKeyId'] = self.apikey
msg['SignatureMethod'] = 'HmacSHA256'
msg['SignatureVersion'] = '2'
msg['Timestamp'] = datetime.datetime.utcnow().strftime("%Y-%m-%dT%H:%M:%S")
msg_Method = 'POST\n'
msg_Url = self.base_url[8:]+'\n'
msg_Path = sub_path + '\n'
message_head = msg_Method+msg_Url+msg_Path
message_param = urllib.urlencode(msg)
message_all = message_head + message_param
#print(message_all)
self.sell_url = self.base_url + sub_path
signature = base64.b64encode(hmac.new(self.secret, message_all, digestmod=hashlib.sha256).digest())
#signature = signature.decode()
msg['Signature'] = signature.decode()
#req_url = self.sell_url + '?' + 'AccessKeyId='+msg['AccessKeyId']+'&SignatureMethod='+msg['SignatureMethod']+'&SignatureVersion='+ \
#msg['SignatureVersion']+'&Timestamp='+urllib.quote(msg['Timestamp'])+'&Signature='+urllib.quote(signature)
req_url = self.sell_url + '?' + urllib.urlencode(msg)
logging.info(req_url)
if(not self.cur_balances.has_key('usdt')):
logging.info('not have enough money return')
return
to_buy_num = num
if self.cur_balances['usdt'] < to_buy_num*price:
to_buy_num = self.cur_balances['usdt']/(price)
logging.info('not have enough money:%.2f,change buy amount %.2f-->%.2f', self.cur_balances['usdt'], num, to_buy_num)
if to_buy_num*price < 1:
logging.info('total must > 1, drop this order')
return
logging.info('buy amount:%.5f'%to_buy_num)
#post_data = {}
post_data = collections.OrderedDict()
post_data['account-id'] = '991115'
post_data['amount'] = '%.2f'%to_buy_num
post_data['price'] = '%.2f'%price
post_data['source'] = 'api'
post_data['symbol'] = self.trade_info_pair_inv[symbol] #ltcusdt
post_data['type'] = 'buy-limit'
post_data_enc = urllib.urlencode(post_data)
#req = urllib.request.Request(req_url, post_data_enc)
post_data_dump = json.dumps(post_data)
logging.info(post_data_dump)
try:
ret = requests.post(req_url, data=post_data_dump, headers=self.send_headers)
json_obj = json.loads(ret.text)
#res = urllib.request.urlopen(req, timeout=5)
#page = res.read()
#json_obj = json.loads(page)
logging.info('buy success'+'{:}'.format(json_obj))
except e:
err = 'buy at huobi error'
logging.info(err)
logging.info(e)
time.sleep(1)
def get_balance(self):
self.base_url = self.base_url_inner
sub_path = '/v1/account/accounts/991115/balance'
msg = collections.OrderedDict()
msg['AccessKeyId'] = self.apikey
msg['SignatureMethod'] = 'HmacSHA256'
msg['SignatureVersion'] = '2'
utc_datetime = datetime.datetime.utcnow()
utcmsg = utc_datetime.strftime("%Y-%m-%dT%H:%M:%S")
msg['Timestamp'] = utcmsg#time.strftime("%Y-%m-%dT%H:%M:%S", time.localtime())
#msg['Timestamp'] = msg['Timestamp'][0:-2]+'13'
#print(msg['Timestamp'])
msg_Method = 'GET\n'
msg_Url = self.base_url[8:]+'\n'
msg_Path = sub_path + '\n'
message_head = msg_Method+msg_Url+msg_Path
message_param = urllib.urlencode(msg)
#print(message_param)
message_all = message_head + message_param
self.balance_url = self.base_url + sub_path
self.cur_balances = {}
self.send_headers = {}
signature = base64.b64encode(hmac.new(self.secret, message_all, digestmod=hashlib.sha256).digest())
req_url = self.balance_url + '?' + 'AccessKeyId='+msg['AccessKeyId']+'&SignatureMethod='+msg['SignatureMethod']+'&SignatureVersion='+ \
msg['SignatureVersion']+'&Timestamp='+urllib.quote(msg['Timestamp'])+'&Signature='+urllib.quote(signature)
logging.info(req_url)
#print('{:}'.format(self.send_headers))
req = urllib.request.Request(req_url, headers=self.send_headers)
#ret = urllib.request.urlopen(urllib.request.Request('https://poloniex.com/tradingApi', post_data, headers))
#elf.send_headers['Key'] = self.apikey
# 'Sign': mysign,
# 'Key': self.apikey
#}
try:
res = urllib.request.urlopen(req,timeout=5)
page = res.read()
json_obj = json.loads(page)
#print('{:}'.format(json_obj))
if json_obj['data'] is not None:
for item in json_obj['data']['list']:
if float(item['balance'])>0.000001 and item['type'] != 'frozen':
self.cur_balances[item['currency']] = float(item['balance'])
logging.info('{:}'.format(self.cur_balances))
else:
logging.info(json_obj)
except e:
err = 'Get huobi balance error'
print(err)
print(e)
logging.info(err)
logging.info(e)
time.sleep(1)
logging.info('get balances:'+'{:}'.format(self.cur_balances))
def get_accounts(self):
msg = collections.OrderedDict()
msg['AccessKeyId'] = self.apikey
msg['SignatureMethod'] = 'HmacSHA256'
msg['SignatureVersion'] = '2'
utc_datetime = datetime.datetime.utcnow()
utcmsg = utc_datetime.strftime("%Y-%m-%dT%H:%M:%S")
msg['Timestamp'] = utcmsg#time.strftime("%Y-%m-%dT%H:%M:%S", time.localtime())
print(msg['Timestamp'])
msg_Method = 'GET\n'
msg_Url = self.base_url[8:-1]+'\n'
msg_Path = '/v1/account/accounts\n'
message_head = msg_Method+msg_Url+msg_Path
message_param = urllib.urlencode(msg)
#print(message_param)
message_all = message_head + message_param
#print(message_all)
self.balance_url = self.base_url + 'v1/account/accounts'
self.cur_balances = {}
self.send_headers = {}
signature = base64.b64encode(hmac.new(self.secret, message_all, digestmod=hashlib.sha256).digest())
req_url = self.balance_url + '?' + 'AccessKeyId='+msg['AccessKeyId']+'&SignatureMethod='+msg['SignatureMethod']+'&SignatureVersion='+ \
msg['SignatureVersion']+'&Timestamp='+urllib.quote(msg['Timestamp'])+'&Signature='+signature
print(req_url)
#print('{:}'.format(self.send_headers))
req = urllib.request.Request(req_url, headers=self.send_headers)
#ret = urllib.request.urlopen(urllib.request.Request('https://poloniex.com/tradingApi', post_data, headers))
#elf.send_headers['Key'] = self.apikey
# 'Sign': mysign,
# 'Key': self.apikey
#}
try:
res = urllib.request.urlopen(req,timeout=5)
page = res.read()
json_obj = json.loads(page)
#print(json_obj)
print('{:}'.format(json_obj))
except e:
err = 'Get huobi balance error'
print(e)
logging.info(err)
time.sleep(1)
def get_ticker(self):
ticker_url = self.base_url_inner +'/market/detail/merged?symbol=ltcusdt'
#myreq = {}
#myreq['command'] = 'returnTicker'
#myreq['nonce'] = int(time.time()*1000)
#post_data = urllib.urlencode(myreq)
#mysign = hmac.new(self.secret, post_data, hashlib.sha512).hexdigest()
#self.send_headers['Sign'] = mysign
#elf.send_headers['Key'] = self.apikey
# 'Sign': mysign,
# 'Key': self.apikey
#}
req = urllib.request.Request(ticker_url, headers=self.send_headers)
try:
res = urllib.request.urlopen(req,timeout=5)
page = res.read()
json_obj = json.loads(page)
self.monitor_info['time'] = time.time()
for pair in self.target_symbol:
if self.symbol_info_pair.has_key(pair):
#self.monitor_info[self.symbol_info_pair[pair]]['last']['price'] = float(json_obj[pair]['last'])
self.monitor_info[self.symbol_info_pair[pair]]['bid']['price'] = float(json_obj['tick']['bid'][0])
self.monitor_info[self.symbol_info_pair[pair]]['bid']['num'] = float(json_obj['tick']['bid'][1])
self.monitor_info[self.symbol_info_pair[pair]]['ask']['price'] = float(json_obj['tick']['ask'][0])
self.monitor_info[self.symbol_info_pair[pair]]['ask']['num'] = float(json_obj['tick']['ask'][1])
#self.monitor_info[self.symbol_info_pair[pair]]['change'] = float(json_obj[pair]['percentChange'])
except e:
err = 'Get huobi ticker error'
logging.info(err)
logging.info(e)
logging.info(ticker_url)
time.sleep(1)
def get_open_info(self):
while not self.is_stop:
self.get_ticker()
#self.get_order_book()
time.sleep(2)
if __name__ == "__main__":
logging.basicConfig(level=logging.DEBUG,
format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',
#datefmt='%a, %d %b %Y %H:%M:%S',
filename='test.log',
filemode='w')
console = logging.StreamHandler()
console.setLevel(logging.INFO)
formatter = logging.Formatter('%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s')
console.setFormatter(formatter)
logging.getLogger('').addHandler(console)
info = fetch_huobi()
try:
#info.get_open_info()
#info.get_accounts()
info.get_balance()
#info.buy('xrp', 0.8, 5)
#info.buy('ltc', 150.8, 5)
except KeyboardInterrupt as e:
info.stop()
| {"/fetch_huobi.py": ["/conf.py", "/console_view.py"], "/fetch_kraken.py": ["/console_view.py", "/conf.py"], "/fetch_poloniex.py": ["/conf.py", "/console_view.py"], "/console_view.py": ["/conf.py"], "/trade.py": ["/conf.py"], "/fetch_coinmarket.py": ["/console_view.py"], "/poloniex_bot.py": ["/conf.py", "/console_view.py"], "/monitor.py": ["/fetch_web.py", "/fetch_coinmarket.py", "/fetch_poloniex.py", "/fetch_kraken.py"], "/main.py": ["/fetch_web.py", "/fetch_coinmarket.py", "/fetch_poloniex.py", "/fetch_kraken.py", "/auto_monitor.py"]} |
60,885 | kswapd/crypto-trading-bot | refs/heads/master | /fetch_kraken.py | #! /usr/bin/python
#-*-coding:utf-8-*-
import urllib.request
import json
import sys, time
import curses
import logging
import console_view as cv
import conf,hmac,hashlib,base64
import requests
class fetch_kraken(cv.console_view):
def __init__(self, x = 80, y = 16, width = 80, height = 15, is_view = True):
#cv.console_view.__init__(self, x, y, width, height, is_view)
self.is_stop = False
self.num = 50
self.pos_y = 2
self.target_symbol = ('BTC','ETH','XRP', 'BCH', 'LTC', 'DASH', 'USDT', 'DOGE')
self.method = ('depth','ticker','trades', 'info')
self.trade_list = ('XXBTZUSD', 'XLTCZUSD', 'BCHUSD', 'XETHZUSD', 'XXRPZUSD','DASHUSD')
#self.coin_url = "https://api.coinmarketcap.com/v1/ticker/?limit=%d"%self.num
self.base_url = 'https://api.kraken.com/0/public/Ticker?pair='
self.order_book_url = 'https://api.kraken.com/0/public/Depth?count=1&pair='
self.api_url = 'https://api.kraken.com'
self.api_version = '0'
self.send_headers = {
'Accept':'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',
'User-Agent':'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36',
'Connection':'keep-alive'
}
self.monitor_info = {
'time':time.time(),
'BTC':{'last':{'price':-1, 'num':-1}, 'bid':{'price':-1, 'num':-1}, 'ask':{'price':-1, 'num':-1}},
'LTC':{'last':{'price':-1, 'num':-1}, 'bid':{'price':-1, 'num':-1}, 'ask':{'price':-1, 'num':-1}},
'ETH':{'last':{'price':-1, 'num':-1}, 'bid':{'price':-1, 'num':-1}, 'ask':{'price':-1, 'num':-1}},
'XRP':{'last':{'price':-1, 'num':-1}, 'bid':{'price':-1, 'num':-1}, 'ask':{'price':-1, 'num':-1}},
'DASH':{'last':{'price':-1, 'num':-1}, 'bid':{'price':-1, 'num':-1}, 'ask':{'price':-1, 'num':-1}},
'DOGE':{'last':{'price':-1, 'num':-1}, 'bid':{'price':-1, 'num':-1}, 'ask':{'price':-1, 'num':-1}}
}
self.symbol_info_pair = {'XXBTZUSD':'BTC','XLTCZUSD':'LTC','XETHZUSD':'ETH','XXRPZUSD':'XRP', 'DASHUSD':'DASH'}
self.symbol_info_pair_inv = {}
for key,val in self.symbol_info_pair.items():
self.symbol_info_pair_inv[val] = key
keys_conf = conf.TradeKeys()
self.cur_balances = {}
self.apikey = keys_conf.keys_info['kraken']['public']
self.secret = keys_conf.keys_info['kraken']['secret']
def stop(self):
self.is_stop = True
print('stopped')
def get_balance(self):
self.cur_balances = {}
self.send_headers = {}
url_path = '/' + self.api_version + '/private/'+'Balance'
req_url = self.api_url + url_path
myreq = {}
myreq['nonce'] = int(time.time()*1000)
post_data = urllib.urlencode(myreq)
message = url_path + hashlib.sha256(str(myreq['nonce']) +
post_data).digest()
signature = hmac.new(base64.b64decode(self.secret),
message, hashlib.sha512)
self.send_headers['API-Key'] = self.apikey
self.send_headers['API-Sign'] = base64.b64encode(signature.digest())
#print('{:}'.format(self.send_headers))
req = urllib.request.Request(req_url,post_data, headers=self.send_headers)
#ret = urllib.request.urlopen(urllib.request.Request('https://poloniex.com/tradingApi', post_data, headers))
#elf.send_headers['Key'] = self.apikey
# 'Sign': mysign,
# 'Key': self.apikey
#}
try:
res = urllib.request.urlopen(req,timeout=5)
page = res.read()
json_obj = json.loads(page)
#print(json_obj['SDC'])
print('{:}'.format(json_obj))
for (k,v) in json_obj['result'].items():
if float(v)>0.000001:
print (k,v)
self.cur_balances[k] = float(v)
except e:
err = 'Get kraken balance error'
print(e)
logging.info(err)
time.sleep(1)
logging.info('get balances:'+'{:}'.format(self.cur_balances))
def buy(self, symbol, price, num):
law_coin = {'USDT':'ZUSD'}
url_path = '/' + self.api_version + '/private/'+'AddOrder'
req_url = self.api_url + url_path
logging.info('start buy:%s,%.2f,%.5f'%(symbol, price, num))
self.get_balance()
if(not self.cur_balances.has_key(law_coin['USDT'])):
logging.info('not have money usdt, return')
return
to_buy_num = num
if self.cur_balances[law_coin['USDT']] < to_buy_num*price:
to_buy_num = self.cur_balances[law_coin['USDT']]/(price)
logging.info('not have enough money:%.2f,change buy amount %.2f-->%.2f', self.cur_balances[law_coin['USDT']], num, to_buy_num)
if to_buy_num*price < 1:
logging.info('total must > 1, drop this order')
return
logging.info('buy amount:%.5f'%to_buy_num)
self.send_headers = {}
myreq = {}
myreq['pair'] = self.symbol_info_pair_inv[symbol]
myreq['type'] = 'buy'
myreq['ordertype'] = 'limit'
myreq['price'] = price
myreq['volume'] = to_buy_num
myreq['nonce'] = int(time.time()*1000)
post_data = urllib.urlencode(myreq)
message = url_path + hashlib.sha256(str(myreq['nonce']) +
post_data).digest()
signature = hmac.new(base64.b64decode(self.secret),
message, hashlib.sha512)
self.send_headers['API-Key'] = self.apikey
self.send_headers['API-Sign'] = base64.b64encode(signature.digest())
#req = urllib.request.Request(self.trade_base_url,post_data, headers=self.send_headers)
try:
#res = urllib.request.urlopen(req,timeout=5)
#page = res.read()
#json_obj = json.loads(page)
ret = requests.post(req_url, data=myreq, headers=self.send_headers)
json_obj = json.loads(ret.text)
logging.info('buy success'+'{:}'.format(json_obj))
except e:
err = 'buy at kraken error'
logging.info(err)
logging.info(e)
time.sleep(1)
def sell(self, symbol, price, num):
logging.info('start sell:%s,%.2f,%.5f'%(symbol, price, num))
url_path = '/' + self.api_version + '/private/'+'AddOrder'
req_url = self.api_url + url_path
self.get_balance()
to_sell_num = num
if(not self.cur_balances.has_key(symbol)):
logging.info('not get this symbol:%s, return'%symbol)
return
if self.cur_balances[symbol] < to_sell_num:
to_sell_num = self.cur_balances[symbol]
if to_sell_num*price < 1:
logging.info('total must > 1, drop this order')
return
logging.info('selling num:%.5f'%to_sell_num)
self.send_headers = {}
myreq = {}
myreq['pair'] = self.symbol_info_pair_inv[symbol]
myreq['type'] = 'sell'
myreq['ordertype'] = 'limit'
myreq['price'] = price
myreq['volume'] = to_sell_num
myreq['nonce'] = int(time.time()*1000)
post_data = urllib.urlencode(myreq)
message = url_path + hashlib.sha256(str(myreq['nonce']) +
post_data).digest()
signature = hmac.new(base64.b64decode(self.secret),
message, hashlib.sha512)
self.send_headers['API-Key'] = self.apikey
self.send_headers['API-Sign'] = base64.b64encode(signature.digest())
#req = urllib.request.Request(self.trade_base_url,post_data, headers=self.send_headers)
try:
#res = urllib.request.urlopen(req,timeout=5)
#page = res.read()
#json_obj = json.loads(page)
ret = requests.post(req_url, data=myreq, headers=self.send_headers)
json_obj = json.loads(ret.text)
logging.info('buy success'+'{:}'.format(json_obj))
except e:
err = 'buy at kraken error'
logging.info(err)
logging.info(e)
time.sleep(1)
def get_open_info(self):
while not self.is_stop:
#self.get_ticker()
self.get_order_book()
time.sleep(2)
def get_ticker(self):
ticker_url = self.base_url+','.join(self.trade_list)
req = urllib.request.Request(ticker_url, headers=self.send_headers)
try:
res = urllib.request.urlopen(req,timeout=5)
page = res.read()
json_obj_all = json.loads(page)
json_obj = json_obj_all['result']
self.monitor_info['time'] = time.time()
for pair in self.trade_list:
if self.symbol_info_pair.has_key(pair):
self.monitor_info[self.symbol_info_pair[pair]]['last']['price'] = float(json_obj[pair]['c'][0])
self.monitor_info[self.symbol_info_pair[pair]]['bid']['price'] = float(json_obj[pair]['b'][0])
self.monitor_info[self.symbol_info_pair[pair]]['ask']['price'] = float(json_obj[pair]['a'][0])
except e:
err = 'Get kraken ticker error.'
logging.info(err)
time.sleep(1)
def get_order_book(self):
for stock in self.trade_list:
ticker_url = self.order_book_url+stock
req = urllib.request.Request(ticker_url, headers=self.send_headers)
try:
res = urllib.request.urlopen(req,timeout=5)
page = res.read()
json_obj_all = json.loads(page)
json_obj = json_obj_all['result']
self.monitor_info['time'] = time.time()
pair = stock
if self.symbol_info_pair.has_key(pair):
self.monitor_info[self.symbol_info_pair[pair]]['bid']['price'] = float(json_obj[pair]['bids'][0][0])
self.monitor_info[self.symbol_info_pair[pair]]['ask']['price'] = float(json_obj[pair]['asks'][0][0])
self.monitor_info[self.symbol_info_pair[pair]]['bid']['num'] = float(json_obj[pair]['bids'][0][1])
self.monitor_info[self.symbol_info_pair[pair]]['ask']['num'] = float(json_obj[pair]['asks'][0][1])
except e:
err = 'Get kraken order book error.'
logging.info(err)
time.sleep(1)
if __name__ == "__main__":
logging.basicConfig(level=logging.DEBUG,
format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',
datefmt='%a, %d %b %Y %H:%M:%S',
filename='test.log',
filemode='w')
info = fetch_kraken()
try:
#info.get_open_info()
#info.get_balance()
info.sell('LTC', 530.0, 0.1)
#info.buy('XRP', 0.75, 1.5)
except KeyboardInterrupt as e:
info.stop()
| {"/fetch_huobi.py": ["/conf.py", "/console_view.py"], "/fetch_kraken.py": ["/console_view.py", "/conf.py"], "/fetch_poloniex.py": ["/conf.py", "/console_view.py"], "/console_view.py": ["/conf.py"], "/trade.py": ["/conf.py"], "/fetch_coinmarket.py": ["/console_view.py"], "/poloniex_bot.py": ["/conf.py", "/console_view.py"], "/monitor.py": ["/fetch_web.py", "/fetch_coinmarket.py", "/fetch_poloniex.py", "/fetch_kraken.py"], "/main.py": ["/fetch_web.py", "/fetch_coinmarket.py", "/fetch_poloniex.py", "/fetch_kraken.py", "/auto_monitor.py"]} |
60,886 | kswapd/crypto-trading-bot | refs/heads/master | /fetch_poloniex.py | #! /usr/bin/python
#-*-coding:utf-8-*-
import urllib.request
import json
import sys, time
import curses
import hmac,hashlib
import conf
import console_view as cv
import logging
import requests
class fetch_poloniex(cv.console_view):
def __init__(self, x = 0, y = 16, width = 80, height = 15, is_view = True):
#cv.console_view.__init__(self, x, y, width, height, is_view)
self.is_stop = False
self.num = 50
self.pos_y = 2
self.fee_rate = 0.0025
self.target_symbol = ('USDT_BTC','USDT_LTC','USDT_BCH','USDT_ETH','USDT_XRP', 'USDT_DASH', 'BTC_DOGE')
self.method = ('depth','ticker','trades', 'info')
self.trade_list = ('ltc_usd', 'btc_usd', 'eth_usd', 'bcc_usd', 'dash_usd', 'doge_usd')
#self.coin_url = "https://api.coinmarketcap.com/v1/ticker/?limit=%d"%self.num
self.base_url = 'https://poloniex.com/public?command=returnTicker'
self.trade_base_url ='https://poloniex.com/tradingApi'
self.order_book_url = 'https://poloniex.com/public?command=returnOrderBook&¤cyPair=all&depth=1'
self.send_headers = {
'Accept':'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
'User-Agent':'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:55.0) Gecko/20100101 Firefox/55.0',
'Cookie':'__cfduid=d92eb21c1dd0e150a8e730ef1e8780fd61516264900; cf_clearance=e61fba35a2c2bdc9cd35af99cb5ca9112244f353-1516613184-1800'
}
keys_conf = conf.TradeKeys()
self.cur_balances = {}
self.apikey = keys_conf.keys_info['poloniex']['public']
self.secret = keys_conf.keys_info['poloniex']['secret']
##self.apikey = 'aaa'
#self.secret = 'bbb'
#self.display_pos = {'x':0, 'y':16, 'width':80, 'height':15}
#print(self.secret)
#print(self.apikey)
self.monitor_info = {
'time':time.time(),
'BTC':{'last':{'price':-1, 'num':-1}, 'bid':{'price':-1, 'num':-1}, 'ask':{'price':-1, 'num':-1}, 'change':-1, 'isFrozen':-1},
'LTC':{'last':{'price':-1, 'num':-1}, 'bid':{'price':-1, 'num':-1}, 'ask':{'price':-1, 'num':-1}, 'change':-1, 'isFrozen':-1},
'ETH':{'last':{'price':-1, 'num':-1}, 'bid':{'price':-1, 'num':-1}, 'ask':{'price':-1, 'num':-1}, 'change':-1, 'isFrozen':-1},
'XRP':{'last':{'price':-1, 'num':-1}, 'bid':{'price':-1, 'num':-1}, 'ask':{'price':-1, 'num':-1}, 'change':-1, 'isFrozen':-1},
'DASH':{'last':{'price':-1, 'num':-1}, 'bid':{'price':-1, 'num':-1}, 'ask':{'price':-1, 'num':-1}, 'change':-1,'isFrozen':-1},
'DOGE':{'last':{'price':-1, 'num':-1}, 'bid':{'price':-1, 'num':-1}, 'ask':{'price':-1, 'num':-1}, 'change':-1,'isFrozen':-1}
}
self.symbol_info_pair = {'USDT_BTC':'BTC','USDT_LTC':'LTC','USDT_ETH':'ETH','USDT_XRP':'XRP', 'BTC_DOGE':'DOGE', 'USDT_DASH':'DASH'}
self.symbol_info_pair_inv = {}
for key,val in self.symbol_info_pair.items():
self.symbol_info_pair_inv[val] = key
def stop(self):
self.is_stop = True
print('stopped')
def sell(self, symbol, price, num):
logging.info('start sell:%s,%.2f,%.5f'%(symbol, price, num))
self.get_balance()
if(not self.cur_balances.has_key(symbol)):
logging.info('not get this symbol:%s, return'%symbol)
return
to_sell_num = num
if self.cur_balances[symbol] < to_sell_num:
to_sell_num = self.cur_balances[symbol]
if to_sell_num*price < 1:
logging.info('total must > 1, drop this order')
return
logging.info('selling num:%.5f'%to_sell_num)
self.send_headers = {}
myreq = {}
myreq['currencyPair'] = self.symbol_info_pair_inv[symbol]
myreq['rate'] = price
myreq['amount'] = to_sell_num
myreq['command'] = 'sell'
myreq['nonce'] = int(time.time()*1000)
post_data = urllib.urlencode(myreq)
mysign = hmac.new(self.secret, post_data, hashlib.sha512).hexdigest()
self.send_headers['Sign'] = mysign
self.send_headers['Key'] = self.apikey
req = urllib.request.Request(self.trade_base_url,post_data, headers=self.send_headers)
try:
#res = urllib.request.urlopen(req,timeout=5)
#page = res.read()
#json_obj = json.loads(page)
ret = requests.post(self.trade_base_url, data=myreq, headers=self.send_headers)
json_obj = json.loads(ret.text)
logging.info('sell success'+'{:}'.format(json_obj))
except e:
err = 'sell at poloniex error'
logging.info(err)
logging.info(e)
time.sleep(1)
def buy(self, symbol, price, num):
logging.info('start buy:%s,%.2f,%.5f'%(symbol, price, num))
self.get_balance()
if(not self.cur_balances.has_key('USDT')):
logging.info('not have money usdt, return')
return
to_buy_num = num
if self.cur_balances['USDT'] < to_buy_num*price:
to_buy_num = self.cur_balances['USDT']/(price)
logging.info('not have enough money:%.2f,change buy amount %.2f-->%.2f', self.cur_balances['USDT'], num, to_buy_num)
if to_buy_num*price < 1:
logging.info('total must > 1, drop this order')
return
logging.info('buy amount:%.5f'%to_buy_num)
self.send_headers = {}
myreq = {}
myreq['currencyPair'] = self.symbol_info_pair_inv[symbol]
myreq['rate'] = price
myreq['amount'] = to_buy_num
myreq['command'] = 'buy'
myreq['nonce'] = int(time.time()*1000)
post_data = urllib.urlencode(myreq)
mysign = hmac.new(self.secret, post_data, hashlib.sha512).hexdigest()
self.send_headers['Sign'] = mysign
self.send_headers['Key'] = self.apikey
req = urllib.request.Request(self.trade_base_url,post_data, headers=self.send_headers)
try:
#res = urllib.request.urlopen(req,timeout=5)
#page = res.read()
#json_obj = json.loads(page)
ret = requests.post(self.trade_base_url, data=myreq, headers=self.send_headers)
json_obj = json.loads(ret.text)
logging.info('buy success'+'{:}'.format(json_obj))
except e:
err = 'buy at poloniex error'
logging.info(err)
logging.info(e)
time.sleep(1)
def get_balance(self):
self.cur_balances = {}
self.send_headers = {}
myreq = {}
myreq['command'] = 'returnBalances'
myreq['nonce'] = int(time.time()*1000)
post_data = urllib.urlencode(myreq)
mysign = hmac.new(self.secret, post_data, hashlib.sha512).hexdigest()
self.send_headers['Sign'] = mysign
self.send_headers['Key'] = self.apikey
#print('{:}'.format(self.send_headers))
req = urllib.request.Request(self.trade_base_url,post_data, headers=self.send_headers)
#ret = urllib.request.urlopen(urllib.request.Request('https://poloniex.com/tradingApi', post_data, headers))
#elf.send_headers['Key'] = self.apikey
# 'Sign': mysign,
# 'Key': self.apikey
#}
try:
res = urllib.request.urlopen(req,timeout=5)
page = res.read()
json_obj = json.loads(page)
#print(json_obj['SDC'])
#print('{:}'.format(json_obj))
for (k,v) in json_obj.items():
if float(v)>0.000001:
self.cur_balances[k] = float(v)
except e:
err = 'Get poloniex balance error'
print(e)
logging.info(err)
time.sleep(1)
logging.info('get balances:'+'{:}'.format(self.cur_balances))
def get_ticker(self):
ticker_url = self.base_url
#myreq = {}
#myreq['command'] = 'returnTicker'
#myreq['nonce'] = int(time.time()*1000)
#post_data = urllib.urlencode(myreq)
#mysign = hmac.new(self.secret, post_data, hashlib.sha512).hexdigest()
#self.send_headers['Sign'] = mysign
#elf.send_headers['Key'] = self.apikey
# 'Sign': mysign,
# 'Key': self.apikey
#}
req = urllib.request.Request(ticker_url, headers=self.send_headers)
try:
res = urllib.request.urlopen(req,timeout=5)
page = res.read()
json_obj = json.loads(page)
self.monitor_info['time'] = time.time()
for pair in self.target_symbol:
if self.symbol_info_pair.has_key(pair):
self.monitor_info[self.symbol_info_pair[pair]]['last']['price'] = float(json_obj[pair]['last'])
self.monitor_info[self.symbol_info_pair[pair]]['bid']['price'] = float(json_obj[pair]['highestBid'])
self.monitor_info[self.symbol_info_pair[pair]]['ask']['price'] = float(json_obj[pair]['lowestAsk'])
self.monitor_info[self.symbol_info_pair[pair]]['change'] = float(json_obj[pair]['percentChange'])
except e:
err = 'Get poloniex ticker error'
logging.info(err)
time.sleep(1)
def get_order_book(self):
ticker_url = self.order_book_url
req = urllib.request.Request(ticker_url, headers=self.send_headers)
try:
res = urllib.request.urlopen(req,timeout=5)
page = res.read()
json_obj = json.loads(page)
self.monitor_info['time'] = time.time()
for pair in self.target_symbol:
if self.symbol_info_pair.has_key(pair):
self.monitor_info[self.symbol_info_pair[pair]]['bid']['price'] = float(json_obj[pair]['bids'][0][0])
self.monitor_info[self.symbol_info_pair[pair]]['ask']['price'] = float(json_obj[pair]['asks'][0][0])
self.monitor_info[self.symbol_info_pair[pair]]['bid']['num'] = float(json_obj[pair]['bids'][0][1])
self.monitor_info[self.symbol_info_pair[pair]]['ask']['num'] = float(json_obj[pair]['asks'][0][1])
self.monitor_info[self.symbol_info_pair[pair]]['isFrozen'] = int(json_obj[pair]['isFrozen'])
except e:
err = 'Get poloniex order book error'
logging.info(err)
time.sleep(1)
def get_open_info(self):
while not self.is_stop:
self.get_ticker()
self.get_order_book()
time.sleep(2)
if __name__ == "__main__":
logging.basicConfig(level=logging.DEBUG,
format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',
datefmt='%a, %d %b %Y %H:%M:%S',
filename='test.log',
filemode='w')
console = logging.StreamHandler()
console.setLevel(logging.INFO)
formatter = logging.Formatter('%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s')
console.setFormatter(formatter)
logging.getLogger('').addHandler(console)
info = fetch_poloniex()
try:
#info.get_open_info()
info.get_balance()
#info.sell('LTC', 130.0, 0.01)
#info.buy('XRP', 0.75, 1.5)
except KeyboardInterrupt as e:
info.stop()
| {"/fetch_huobi.py": ["/conf.py", "/console_view.py"], "/fetch_kraken.py": ["/console_view.py", "/conf.py"], "/fetch_poloniex.py": ["/conf.py", "/console_view.py"], "/console_view.py": ["/conf.py"], "/trade.py": ["/conf.py"], "/fetch_coinmarket.py": ["/console_view.py"], "/poloniex_bot.py": ["/conf.py", "/console_view.py"], "/monitor.py": ["/fetch_web.py", "/fetch_coinmarket.py", "/fetch_poloniex.py", "/fetch_kraken.py"], "/main.py": ["/fetch_web.py", "/fetch_coinmarket.py", "/fetch_poloniex.py", "/fetch_kraken.py", "/auto_monitor.py"]} |
60,887 | kswapd/crypto-trading-bot | refs/heads/master | /console_view.py | #! /usr/bin/python
#-*-coding:utf-8-*-
import urllib.request
import json
import sys, time
import curses
import hmac,hashlib
import conf
class console_view:
def __init__(self, x = 0, y = 0, width = 80, height = 15, is_view = True):
self.display_pos = {'x':x, 'y':y, 'width':width, 'height':height}
self.is_view = is_view
self.view_mode = 'simp'
| {"/fetch_huobi.py": ["/conf.py", "/console_view.py"], "/fetch_kraken.py": ["/console_view.py", "/conf.py"], "/fetch_poloniex.py": ["/conf.py", "/console_view.py"], "/console_view.py": ["/conf.py"], "/trade.py": ["/conf.py"], "/fetch_coinmarket.py": ["/console_view.py"], "/poloniex_bot.py": ["/conf.py", "/console_view.py"], "/monitor.py": ["/fetch_web.py", "/fetch_coinmarket.py", "/fetch_poloniex.py", "/fetch_kraken.py"], "/main.py": ["/fetch_web.py", "/fetch_coinmarket.py", "/fetch_poloniex.py", "/fetch_kraken.py", "/auto_monitor.py"]} |
60,888 | kswapd/crypto-trading-bot | refs/heads/master | /trade.py | #! /usr/bin/python
import ccxt as ct
import pprint
import trade
import time
import conf
class auto_trade:
def prt(self,info):
pprint.pprint(info)
def __init__(self):
self.k = ct.kraken()
self.y = ct.yobit()
self.p = ct.poloniex()
self.coinmarket = ct.coinmarketcap()
self.liqui = ct.bitfinex()
print(ct.exchanges)
print(self.k.hasFetchOHLCV, self.k.rateLimit)
print(self.y.hasFetchOHLCV, self.y.rateLimit)
print(self.p.hasFetchOHLCV, self.p.rateLimit)
# print(self.coinmarket.hasFetchOHLCV, self.coinmarket.rateLimit)
keys_conf = conf.TradeKeys()
#print(keys_conf.keys_info)
self.k.apiKey = keys_conf.keys_info['kraken']['public']
self.k.secret = keys_conf.keys_info['kraken']['secret']
#self.k.load_markets()
print(self.k.symbols)
#self.k.create_market_buy_order ('BTC/USD', 0.1)
#print(self.k.fetch_ohlcv('LTC/USD', '1d'))
def start(self):
symbol = 'BTC/USD'
all_info = {'k':{}, 'y':{}, 'liqui':{}}
for i in range(0,10):
r = self.liqui
start = time.time()
ticker = r.fetch_ticker(symbol)
#print(i, "open:%s, bid:%s, ask:%s,cost:%s"%(ticker['open'],ticker['bid'],ticker['ask'], time.time()-start))
all_info['k']['bid'] = ticker['bid']
r = self.y
start = time.time()
ticker = r.fetch_ticker(symbol)
#print(i, "open:%s, bid:%s, ask:%s,cost:%s"%(ticker['open'],ticker['bid'],ticker['ask'], time.time()-start))
all_info['y']['bid'] = ticker['bid']
r = self.liqui
start = time.time()
ticker = r.fetch_ticker(symbol)
#print(i, "open:%s, bid:%s, ask:%s,cost:%s"%(ticker['open'],ticker['bid'],ticker['ask'], time.time()-start))
all_info['liqui']['bid'] = ticker['bid']
print(i, "bid k:%s, y:%s, liqui:%s"%(all_info['k']['bid'],all_info['y']['bid'],all_info['liqui']['bid']))
time.sleep(0.5)
"""
for i in range(1,10):
r = self.k
start = time.time()
orderbook = r.fetch_order_book('BTC/USD', {
'depth': 5,
})
bid = orderbook['bids'][0][0] if len (orderbook['bids']) > 0 else None
ask = orderbook['asks'][0][0] if len (orderbook['asks']) > 0 else None
spread = (ask - bid) if (bid and ask) else None
print(i, r.id, 'market price', { 'bid': bid, 'ask': ask, 'spread': spread }, "cost: %s sec"%(time.time()-start))
r = self.y
start = time.time()
orderbook = r.fetch_order_book('BTC/USD', {
'depth': 5,
})
bid = orderbook['bids'][0][0] if len (orderbook['bids']) > 0 else None
ask = orderbook['asks'][0][0] if len (orderbook['asks']) > 0 else None
spread = (ask - bid) if (bid and ask) else None
print(i, r.id, 'market price', { 'bid': bid, 'ask': ask, 'spread': spread }, "cost: %s sec"%(time.time()-start))
"""
| {"/fetch_huobi.py": ["/conf.py", "/console_view.py"], "/fetch_kraken.py": ["/console_view.py", "/conf.py"], "/fetch_poloniex.py": ["/conf.py", "/console_view.py"], "/console_view.py": ["/conf.py"], "/trade.py": ["/conf.py"], "/fetch_coinmarket.py": ["/console_view.py"], "/poloniex_bot.py": ["/conf.py", "/console_view.py"], "/monitor.py": ["/fetch_web.py", "/fetch_coinmarket.py", "/fetch_poloniex.py", "/fetch_kraken.py"], "/main.py": ["/fetch_web.py", "/fetch_coinmarket.py", "/fetch_poloniex.py", "/fetch_kraken.py", "/auto_monitor.py"]} |
60,889 | kswapd/crypto-trading-bot | refs/heads/master | /conf.py | #! /usr/bin/python
import configparser
import string, os, sys
class TradeKeys:
def __init__(self):
cf = configparser.ConfigParser()
cf.read("keys.ini")
kraken_public = cf.get("kraken", "public")
kraken_secret = cf.get("kraken", "secret")
poloniex_public = cf.get("poloniex", "public")
poloniex_secret = cf.get("poloniex", "secret")
huobi_public = cf.get("huobi", "public")
huobi_secret = cf.get("huobi", "secret")
self.keys_info = {
'kraken':{'public':kraken_public,
'secret':kraken_secret
},
'poloniex':{'public':poloniex_public,
'secret':poloniex_secret
},
'huobi':{
'public':huobi_public,
'secret':huobi_secret
},
'binance':{
'public':cf.get("binance", "public"),
'secret':cf.get("binance", "secret")
}
};
| {"/fetch_huobi.py": ["/conf.py", "/console_view.py"], "/fetch_kraken.py": ["/console_view.py", "/conf.py"], "/fetch_poloniex.py": ["/conf.py", "/console_view.py"], "/console_view.py": ["/conf.py"], "/trade.py": ["/conf.py"], "/fetch_coinmarket.py": ["/console_view.py"], "/poloniex_bot.py": ["/conf.py", "/console_view.py"], "/monitor.py": ["/fetch_web.py", "/fetch_coinmarket.py", "/fetch_poloniex.py", "/fetch_kraken.py"], "/main.py": ["/fetch_web.py", "/fetch_coinmarket.py", "/fetch_poloniex.py", "/fetch_kraken.py", "/auto_monitor.py"]} |
60,890 | kswapd/crypto-trading-bot | refs/heads/master | /fetch_web.py | import urllib.request
class fetch_url:
def __init__(self):
print('init')
def start(self):
req = urllib.request.Request('http://www.baidu.com')
res = urllib.request.urlopen(req)
page = res.read()
print(page)
| {"/fetch_huobi.py": ["/conf.py", "/console_view.py"], "/fetch_kraken.py": ["/console_view.py", "/conf.py"], "/fetch_poloniex.py": ["/conf.py", "/console_view.py"], "/console_view.py": ["/conf.py"], "/trade.py": ["/conf.py"], "/fetch_coinmarket.py": ["/console_view.py"], "/poloniex_bot.py": ["/conf.py", "/console_view.py"], "/monitor.py": ["/fetch_web.py", "/fetch_coinmarket.py", "/fetch_poloniex.py", "/fetch_kraken.py"], "/main.py": ["/fetch_web.py", "/fetch_coinmarket.py", "/fetch_poloniex.py", "/fetch_kraken.py", "/auto_monitor.py"]} |
60,891 | kswapd/crypto-trading-bot | refs/heads/master | /fetch_coinmarket.py | #! /usr/bin/python
#-*-coding:utf-8-*-
import urllib.request
import json
import sys, time
import curses
import console_view as cv
class fetch_coinmarket(cv.console_view):
def __init__(self, x = 0, y = 0, width = 80, height = 15, is_view = True):
cv.console_view.__init__(self, x, y, width, height, is_view)
self.is_stop = False
self.num = 50
self.pos_y = 2
self.targetSymbol = ('BTC','ETH','XRP', 'BCH', 'LTC', 'DASH', 'USDT', 'DOGE')
#self.coin_url = "https://pro-api.coinmarketcap.com/v1/ticker/?limit=%d"%self.num
self.coin_url = "https://pro-api.coinmarketcap.com/v1/cryptocurrency/listings/latest"
def stop(self):
self.is_stop = True
curses.endwin()
print('stopped')
def start(self):
print(self.coin_url)
#self.stdscr = curses.initscr()
#self.stdscr = curses.initscr()
#self.stdscr = curses.newwin(15, 80, 0, 0)
self.stdscr = curses.newwin(self.display_pos['height'], self.display_pos['width'], self.display_pos['y'], self.display_pos['x'])
#self.stdscr = curses.newpad(600, 800)
curses.start_color()
curses.init_pair(1, curses.COLOR_GREEN, curses.COLOR_BLACK)
curses.init_pair(2, curses.COLOR_RED, curses.COLOR_BLACK)
curses.init_pair(3, curses.COLOR_YELLOW, curses.COLOR_BLACK)
while not self.is_stop:
cur_pos_x = 2;
headers = {
'Accepts': 'application/json',
'X-CMC_PRO_API_KEY': 'b22f9e6d-6c09-431d-ac9a-fd87131fc9a5',
}
req = urllib.request.Request(url=self.coin_url, headers=headers)
res = urllib.request.urlopen(req)
page = res.read()
json_obj = json.loads(page)
print(json_obj)
self.stdscr.box(curses.ACS_VLINE, curses.ACS_HLINE)
self.stdscr.addstr(cur_pos_x,self.pos_y,'Coin market cap', curses.color_pair(3))
cur_pos_x += 1;
self.stdscr.addstr(cur_pos_x,self.pos_y,time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()) ), curses.color_pair(3))
cur_pos_x += 1;
print_head = "Symbol \tPrice($) \tPercent(24h)"
self.stdscr.addstr(cur_pos_x,self.pos_y,print_head,curses.color_pair(3))
cur_pos_x += 1;
for i in range(self.num):
color_index = 1
if json_obj[i]['symbol'] in self.targetSymbol:
#print_content = "sym:%7s \tprice:%10s \tper:%5s"%(json_obj[i]['symbol'], json_obj[i]['price_usd'], json_obj[i]['percent_change_24h']);
print_content = "%7s \t%7s \t%7s"%(json_obj[i]['symbol'], json_obj[i]['price_usd'], json_obj[i]['percent_change_24h']);
if json_obj[i]['percent_change_24h'][0] == '-':
color_index = 2
self.stdscr.addstr(cur_pos_x,self.pos_y,print_content,curses.color_pair(color_index))
cur_pos_x += 1
#stdscr.addstr(i, 0, "hi:%d"%i)
#sys.stdout.flush()
self.stdscr.refresh()
time.sleep(10)
if __name__ == "__main__":
curses.initscr()
coin_market = fetch_coinmarket()
try:
coin_market.start()
except KeyboardInterrupt as e:
coin_market.stop()
| {"/fetch_huobi.py": ["/conf.py", "/console_view.py"], "/fetch_kraken.py": ["/console_view.py", "/conf.py"], "/fetch_poloniex.py": ["/conf.py", "/console_view.py"], "/console_view.py": ["/conf.py"], "/trade.py": ["/conf.py"], "/fetch_coinmarket.py": ["/console_view.py"], "/poloniex_bot.py": ["/conf.py", "/console_view.py"], "/monitor.py": ["/fetch_web.py", "/fetch_coinmarket.py", "/fetch_poloniex.py", "/fetch_kraken.py"], "/main.py": ["/fetch_web.py", "/fetch_coinmarket.py", "/fetch_poloniex.py", "/fetch_kraken.py", "/auto_monitor.py"]} |
60,892 | kswapd/crypto-trading-bot | refs/heads/master | /poloniex_bot.py | #! /usr/bin/python
# -*-coding:utf-8-*-
import urllib.request
import json
import sys
import time
import hmac
import hashlib
import conf
import console_view as cv
import logging
import requests
class poloniex_bot():
def __init__(self, x=0, y=16, width=80, height=15, is_view=True):
self.is_stop = False
self.num = 50
self.pos_y = 2
self.fee_rate = 0.0025
self.target_symbol = ('USDT_BTC', 'USDT_LTC', 'USDT_BCH',
'USDT_ETH', 'USDT_XRP', 'USDT_DASH', 'BTC_DOGE')
self.method = ('depth', 'ticker', 'trades', 'info')
self.trade_list = ('ltc_usd', 'btc_usd', 'eth_usd',
'bcc_usd', 'dash_usd', 'doge_usd')
# self.coin_url = "https://api.coinmarketcap.com/v1/ticker/?limit=%d"%self.num
self.base_url = 'https://poloniex.com/public?command=returnTicker'
self.trade_base_url = 'https://poloniex.com/tradingApi'
self.order_book_url = 'https://poloniex.com/public?command=returnOrderBook&¤cyPair=all&depth=1'
self.send_headers = {
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
'User-Agent': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:55.0) Gecko/20100101 Firefox/55.0',
'Cookie': '__cfduid=d92eb21c1dd0e150a8e730ef1e8780fd61516264900; cf_clearance=e61fba35a2c2bdc9cd35af99cb5ca9112244f353-1516613184-1800'
}
keys_conf = conf.TradeKeys()
self.cur_balances = {}
self.open_orders = {}
self.apikey = keys_conf.keys_info['poloniex']['public']
self.secret = keys_conf.keys_info['poloniex']['secret']
# self.apikey = 'aaa'
# self.secret = 'bbb'
# self.display_pos = {'x':0, 'y':16, 'width':80, 'height':15}
# print(self.secret)
# print(self.apikey)
self.monitor_info = {
'time': time.time(),
'BTC': {'last': {'price': -1, 'num': -1}, 'bid': {'price': -1, 'num': -1}, 'ask': {'price': -1, 'num': -1}, 'change': -1, 'isFrozen': -1},
'LTC': {'last': {'price': -1, 'num': -1}, 'bid': {'price': -1, 'num': -1}, 'ask': {'price': -1, 'num': -1}, 'change': -1, 'isFrozen': -1},
'ETH': {'last': {'price': -1, 'num': -1}, 'bid': {'price': -1, 'num': -1}, 'ask': {'price': -1, 'num': -1}, 'change': -1, 'isFrozen': -1},
'XRP': {'last': {'price': -1, 'num': -1}, 'bid': {'price': -1, 'num': -1}, 'ask': {'price': -1, 'num': -1}, 'change': -1, 'isFrozen': -1},
'DASH': {'last': {'price': -1, 'num': -1}, 'bid': {'price': -1, 'num': -1}, 'ask': {'price': -1, 'num': -1}, 'change': -1, 'isFrozen': -1},
'DOGE': {'last': {'price': -1, 'num': -1}, 'bid': {'price': -1, 'num': -1}, 'ask': {'price': -1, 'num': -1}, 'change': -1, 'isFrozen': -1}
}
self.symbol_info_pair = {'USDT_BTC': 'BTC', 'USDT_LTC': 'LTC',
'USDT_ETH': 'ETH', 'USDT_XRP': 'XRP', 'BTC_DOGE': 'DOGE', 'USDT_DASH': 'DASH'}
self.symbol_info_pair_inv = {}
for key, val in self.symbol_info_pair.items():
self.symbol_info_pair_inv[val] = key
def stop(self):
self.is_stop = True
print('stopped')
def sell(self, symbol, price, num):
logging.info('start sell:%s,%.2f,%.5f' % (symbol, price, num))
self.get_balance()
if(symbol not in self.cur_balances):
logging.info('not get this symbol:%s, return' % symbol)
return
to_sell_num = num
if self.cur_balances[symbol] < to_sell_num:
to_sell_num = self.cur_balances[symbol]
if to_sell_num*price < 1:
logging.info('total must > 1, drop this order')
return
logging.info('selling num:%.5f' % to_sell_num)
self.send_headers = {}
myreq = {}
myreq['currencyPair'] = self.symbol_info_pair_inv[symbol]
myreq['rate'] = price
myreq['amount'] = to_sell_num
myreq['command'] = 'sell'
myreq['nonce'] = int(time.time()*1000)
post_data = urllib.parse.urlencode(myreq)
mysign = hmac.new(self.secret.encode('utf-8'),
post_data.encode('utf-8'), hashlib.sha512).hexdigest()
self.send_headers['Sign'] = mysign
self.send_headers['Key'] = self.apikey
req = urllib.request.Request(
self.trade_base_url, post_data.encode('utf-8'), headers=self.send_headers)
req.set_proxy('127.0.0.1:8001', 'http')
req.set_proxy('127.0.0.1:8001', 'https')
# ret = requests.post(self.trade_base_url,
# data=myreq, headers=self.send_headers)
# json_obj = json.loads(ret.text)
res = urllib.request.urlopen(url=req, timeout=5000)
page = res.read()
json_obj = json.loads(page)
logging.info('sell success'+'{:}'.format(json_obj))
def buy(self, symbol, price, num):
logging.info('start buy:%s,%.2f,%.5f' % (symbol, price, num))
self.get_balance()
if('USDT' not in self.cur_balances):
logging.info('not have money usdt, return')
return
to_buy_num = num
if self.cur_balances['USDT'] < to_buy_num*price:
to_buy_num = self.cur_balances['USDT']/(price)
logging.info('not have enough money:%.2f,change buy amount %.2f-->%.2f',
self.cur_balances['USDT'], num, to_buy_num)
if to_buy_num*price < 1:
logging.info('total must > 1, drop this order')
return
logging.info('buy amount:%.5f' % to_buy_num)
self.send_headers = {}
myreq = {}
myreq['currencyPair'] = self.symbol_info_pair_inv[symbol]
myreq['rate'] = price
myreq['amount'] = to_buy_num
myreq['command'] = 'buy'
myreq['nonce'] = int(time.time()*1000)
post_data = urllib.parse.urlencode(myreq)
mysign = hmac.new(self.secret.encode('utf-8'),
post_data.encode('utf-8'), hashlib.sha512).hexdigest()
self.send_headers['Sign'] = mysign
self.send_headers['Key'] = self.apikey
req = urllib.request.Request(
self.trade_base_url, post_data.encode('utf-8'), headers=self.send_headers)
req.set_proxy('127.0.0.1:8001', 'http')
req.set_proxy('127.0.0.1:8001', 'https')
res = urllib.request.urlopen(req, timeout=5000)
page = res.read()
json_obj = json.loads(page)
# ret = requests.post(self.trade_base_url,
# data=myreq, headers=self.send_headers)
# json_obj = json.loads(ret.text)
logging.info('buy success'+'{:}'.format(json_obj))
def get_open_orders(self):
self.cur_balances = {}
self.send_headers = {}
myreq = {}
myreq['command'] = 'returnOpenOrders'
myreq['currencyPair'] = 'USDT_XRP'
myreq['nonce'] = int(time.time()*1000)
post_data = urllib.parse.urlencode(myreq, encoding='utf-8')
# print("secret:", self.secret)
mysign = hmac.new(self.secret.encode('utf-8'), post_data.encode('utf-8'),
hashlib.sha512).hexdigest()
self.send_headers['Sign'] = mysign
self.send_headers['Key'] = self.apikey
# print('{:}'.format(self.send_headers))
req = urllib.request.Request(
self.trade_base_url, post_data.encode('utf-8'), headers=self.send_headers)
req.set_proxy('127.0.0.1:8001', 'http')
req.set_proxy('127.0.0.1:8001', 'https')
res = urllib.request.urlopen(url=req, timeout=5000)
page = res.read()
json_obj = json.loads(page)
# print(json_obj['SDC'])
# print('{:}'.format(json_obj))
for k in json_obj:
# print(k['orderNumber'])
self.open_orders[k['orderNumber']] = k
#logging.info('get open orders:'+'{:}'.format(json_obj))
logging.info('get open orders:'+'{:}'.format(self.open_orders))
def get_balance(self):
self.cur_balances = {}
self.send_headers = {}
myreq = {}
myreq['command'] = 'returnBalances'
myreq['nonce'] = int(time.time()*1000)
post_data = urllib.parse.urlencode(myreq, encoding='utf-8')
# print("secret:", self.secret)
mysign = hmac.new(self.secret.encode('utf-8'), post_data.encode('utf-8'),
hashlib.sha512).hexdigest()
self.send_headers['Sign'] = mysign
self.send_headers['Key'] = self.apikey
# print('{:}'.format(self.send_headers))
req = urllib.request.Request(
self.trade_base_url, post_data.encode('utf-8'), headers=self.send_headers)
req.set_proxy('127.0.0.1:8001', 'http')
req.set_proxy('127.0.0.1:8001', 'https')
# ret = urllib.request.urlopen(urllib.request.Request('https://poloniex.com/tradingApi', post_data, headers))
# elf.send_headers['Key'] = self.apikey
# 'Sign': mysign,
# 'Key': self.apikey
# }
# try:
res = urllib.request.urlopen(url=req, timeout=5000)
page = res.read()
json_obj = json.loads(page)
# print(json_obj['SDC'])
# print('{:}'.format(json_obj))
for (k, v) in json_obj.items():
if float(v) > 0.000001:
self.cur_balances[k] = float(v)
logging.info('get balances:'+'{:}'.format(self.cur_balances))
def get_ticker(self):
ticker_url = self.base_url
# myreq = {}
# myreq['command'] = 'returnTicker'
# myreq['nonce'] = int(time.time()*1000)
# post_data = urllib.urlencode(myreq)
# mysign = hmac.new(self.secret, post_data, hashlib.sha512).hexdigest()
# self.send_headers['Sign'] = mysign
# elf.send_headers['Key'] = self.apikey
# 'Sign': mysign,
# 'Key': self.apikey
# }
req = urllib.request.Request(ticker_url, headers=self.send_headers)
req.set_proxy('127.0.0.1:8001', 'http')
req.set_proxy('127.0.0.1:8001', 'https')
res = urllib.request.urlopen(req, timeout=5)
page = res.read()
json_obj = json.loads(page)
self.monitor_info['time'] = time.strftime(
"%Y-%m-%d %H:%M:%S", time.localtime())
for pair in self.target_symbol:
if pair in self.symbol_info_pair:
self.monitor_info[self.symbol_info_pair[pair]]['last']['price'] = float(
json_obj[pair]['last'])
self.monitor_info[self.symbol_info_pair[pair]]['bid']['price'] = float(
json_obj[pair]['highestBid'])
self.monitor_info[self.symbol_info_pair[pair]]['ask']['price'] = float(
json_obj[pair]['lowestAsk'])
self.monitor_info[self.symbol_info_pair[pair]]['change'] = float(
json_obj[pair]['percentChange'])
# print(
# pair, self.monitor_info[self.symbol_info_pair[pair]]['last']['price'])
def get_order_book(self):
ticker_url = self.order_book_url
req = urllib.request.Request(ticker_url, headers=self.send_headers)
req.set_proxy('127.0.0.1:8001', 'http')
req.set_proxy('127.0.0.1:8001', 'https')
res = urllib.request.urlopen(req, timeout=5000)
page = res.read()
json_obj = json.loads(page)
self.monitor_info['time'] = time.strftime(
"%Y-%m-%d %H:%M:%S", time.localtime())
for pair in self.target_symbol:
if pair in self.symbol_info_pair:
self.monitor_info[self.symbol_info_pair[pair]]['bid']['price'] = float(
json_obj[pair]['bids'][0][0])
self.monitor_info[self.symbol_info_pair[pair]]['ask']['price'] = float(
json_obj[pair]['asks'][0][0])
self.monitor_info[self.symbol_info_pair[pair]]['bid']['num'] = float(
json_obj[pair]['bids'][0][1])
self.monitor_info[self.symbol_info_pair[pair]]['ask']['num'] = float(
json_obj[pair]['asks'][0][1])
self.monitor_info[self.symbol_info_pair[pair]]['isFrozen'] = int(
json_obj[pair]['isFrozen'])
# print(
# pair, self.monitor_info[self.symbol_info_pair[pair]]['bid']['num'])
def list_price(self):
while not self.is_stop:
self.get_ticker()
self.get_order_book()
for k, v in self.monitor_info.items():
if k == 'time':
print("List time:", v)
else:
print(k, v['last']['price'], v['bid']
['price'], v['ask']['price'], v['bid']['num'], v['ask']['num'], v['isFrozen'])
time.sleep(2)
if __name__ == "__main__":
logging.basicConfig(level=logging.DEBUG,
format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',
datefmt='%a, %d %b %Y %H:%M:%S',
filename='test.log',
filemode='w')
console = logging.StreamHandler()
console.setLevel(logging.INFO)
formatter = logging.Formatter(
'%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s')
console.setFormatter(formatter)
logging.getLogger('').addHandler(console)
bot = poloniex_bot()
try:
# bot.list_price()
bot.get_balance()
# bot.sell('LTC', 130.0, 0.01)
# bot.sell('XRP', 5, 1)
# bot.get_open_orders()
# bot.buy('XRP', 0.01, 1000)
except KeyboardInterrupt as e:
bot.stop()
| {"/fetch_huobi.py": ["/conf.py", "/console_view.py"], "/fetch_kraken.py": ["/console_view.py", "/conf.py"], "/fetch_poloniex.py": ["/conf.py", "/console_view.py"], "/console_view.py": ["/conf.py"], "/trade.py": ["/conf.py"], "/fetch_coinmarket.py": ["/console_view.py"], "/poloniex_bot.py": ["/conf.py", "/console_view.py"], "/monitor.py": ["/fetch_web.py", "/fetch_coinmarket.py", "/fetch_poloniex.py", "/fetch_kraken.py"], "/main.py": ["/fetch_web.py", "/fetch_coinmarket.py", "/fetch_poloniex.py", "/fetch_kraken.py", "/auto_monitor.py"]} |
60,893 | kswapd/crypto-trading-bot | refs/heads/master | /poloniex_sample.py | import urllib.request
import json
import time
import hmac,hashlib
def createTimeStamp(datestr, format="%Y-%m-%d %H:%M:%S"):
return time.mktime(time.strptime(datestr, format))
class poloniex:
def __init__(self, APIKey, Secret):
self.APIKey = APIKey
self.Secret = Secret
def post_process(self, before):
after = before
# Add timestamps if there isnt one but is a datetime
if('return' in after):
if(isinstance(after['return'], list)):
for x in xrange(0, len(after['return'])):
if(isinstance(after['return'][x], dict)):
if('datetime' in after['return'][x] and 'timestamp' not in after['return'][x]):
after['return'][x]['timestamp'] = float(createTimeStamp(after['return'][x]['datetime']))
return after
def api_query(self, command, req={}):
if(command == "returnTicker" or command == "return24Volume"):
ret = urllib.request.urlopen(urllib.request.Request('https://poloniex.com/public?command=' + command))
return json.loads(ret.read())
elif(command == "returnOrderBook"):
ret = urllib.request.urlopen(urllib.request.Request('https://poloniex.com/public?command=' + command + '¤cyPair=' + str(req['currencyPair'])))
return json.loads(ret.read())
elif(command == "returnMarketTradeHistory"):
ret = urllib.request.urlopen(urllib.request.Request('https://poloniex.com/public?command=' + "returnTradeHistory" + '¤cyPair=' + str(req['currencyPair'])))
return json.loads(ret.read())
else:
req['command'] = command
req['nonce'] = int(time.time()*1000)
post_data = urllib.urlencode(req)
sign = hmac.new(self.Secret, post_data, hashlib.sha512).hexdigest()
headers = {
'Sign': sign,
'Key': self.APIKey
}
ret = urllib.request.urlopen(urllib.request.Request('https://poloniex.com/tradingApi', post_data, headers))
jsonRet = json.loads(ret.read())
return self.post_process(jsonRet)
def returnTicker(self):
return self.api_query("returnTicker")
def return24Volume(self):
return self.api_query("return24Volume")
def returnOrderBook (self, currencyPair):
return self.api_query("returnOrderBook", {'currencyPair': currencyPair})
def returnMarketTradeHistory (self, currencyPair):
return self.api_query("returnMarketTradeHistory", {'currencyPair': currencyPair})
# Returns all of your balances.
# Outputs:
# {"BTC":"0.59098578","LTC":"3.31117268", ... }
def returnBalances(self):
return self.api_query('returnBalances')
# Returns your open orders for a given market, specified by the "currencyPair" POST parameter, e.g. "BTC_XCP"
# Inputs:
# currencyPair The currency pair e.g. "BTC_XCP"
# Outputs:
# orderNumber The order number
# type sell or buy
# rate Price the order is selling or buying at
# Amount Quantity of order
# total Total value of order (price * quantity)
def returnOpenOrders(self,currencyPair):
return self.api_query('returnOpenOrders',{"currencyPair":currencyPair})
# Returns your trade history for a given market, specified by the "currencyPair" POST parameter
# Inputs:
# currencyPair The currency pair e.g. "BTC_XCP"
# Outputs:
# date Date in the form: "2014-02-19 03:44:59"
# rate Price the order is selling or buying at
# amount Quantity of order
# total Total value of order (price * quantity)
# type sell or buy
def returnTradeHistory(self,currencyPair):
return self.api_query('returnTradeHistory',{"currencyPair":currencyPair})
# Places a buy order in a given market. Required POST parameters are "currencyPair", "rate", and "amount". If successful, the method will return the order number.
# Inputs:
# currencyPair The curreny pair
# rate price the order is buying at
# amount Amount of coins to buy
# Outputs:
# orderNumber The order number
def buy(self,currencyPair,rate,amount):
return self.api_query('buy',{"currencyPair":currencyPair,"rate":rate,"amount":amount})
# Places a sell order in a given market. Required POST parameters are "currencyPair", "rate", and "amount". If successful, the method will return the order number.
# Inputs:
# currencyPair The curreny pair
# rate price the order is selling at
# amount Amount of coins to sell
# Outputs:
# orderNumber The order number
def sell(self,currencyPair,rate,amount):
return self.api_query('sell',{"currencyPair":currencyPair,"rate":rate,"amount":amount})
# Cancels an order you have placed in a given market. Required POST parameters are "currencyPair" and "orderNumber".
# Inputs:
# currencyPair The curreny pair
# orderNumber The order number to cancel
# Outputs:
# succes 1 or 0
def cancel(self,currencyPair,orderNumber):
return self.api_query('cancelOrder',{"currencyPair":currencyPair,"orderNumber":orderNumber})
# Immediately places a withdrawal for a given currency, with no email confirmation. In order to use this method, the withdrawal privilege must be enabled for your API key. Required POST parameters are "currency", "amount", and "address". Sample output: {"response":"Withdrew 2398 NXT."}
# Inputs:
# currency The currency to withdraw
# amount The amount of this coin to withdraw
# address The withdrawal address
# Outputs:
# response Text containing message about the withdrawal
def withdraw(self, currency, amount, address):
return self.api_query('withdraw',{"currency":currency, "amount":amount, "address":address})
| {"/fetch_huobi.py": ["/conf.py", "/console_view.py"], "/fetch_kraken.py": ["/console_view.py", "/conf.py"], "/fetch_poloniex.py": ["/conf.py", "/console_view.py"], "/console_view.py": ["/conf.py"], "/trade.py": ["/conf.py"], "/fetch_coinmarket.py": ["/console_view.py"], "/poloniex_bot.py": ["/conf.py", "/console_view.py"], "/monitor.py": ["/fetch_web.py", "/fetch_coinmarket.py", "/fetch_poloniex.py", "/fetch_kraken.py"], "/main.py": ["/fetch_web.py", "/fetch_coinmarket.py", "/fetch_poloniex.py", "/fetch_kraken.py", "/auto_monitor.py"]} |
60,894 | kswapd/crypto-trading-bot | refs/heads/master | /monitor.py | import pprint as pp
#import trade
import time
import fetch_web
import fetch_coinmarket
import fetch_yobit
import fetch_poloniex
import fetch_kraken
import _thread
import curses
class trade_monitor:
def __init__(self):
a = 1
def start2(self):
print('aaaa')
def start(self):
time.sleep(5)
self.stdscr = curses.newwin(15, 80, 0, 0)
curses.start_color()
curses.init_pair(1, curses.COLOR_GREEN, curses.COLOR_BLACK)
curses.init_pair(2, curses.COLOR_RED, curses.COLOR_BLACK)
curses.init_pair(3, curses.COLOR_YELLOW, curses.COLOR_BLACK)
while True:
pos_x = 2
pos_y = 2
self.stdscr.box(curses.ACS_VLINE, curses.ACS_HLINE)
self.stdscr.addstr(pos_x,pos_y,'Monitor', curses.color_pair(3))
pos_x += 1
self.stdscr.addstr(pos_x,pos_y,time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()) ), curses.color_pair(3))
pos_x += 1
print_head = "Symbol \tLast($) \tBuy \t\tSell"
self.stdscr.addstr(pos_x,pos_y,print_head,curses.color_pair(3))
pos_x += 1
self.stdscr.addstr(pos_x,pos_y,print_head,curses.color_pair(3))
pos_x += 1
self.stdscr.refresh()
time.sleep(2)
| {"/fetch_huobi.py": ["/conf.py", "/console_view.py"], "/fetch_kraken.py": ["/console_view.py", "/conf.py"], "/fetch_poloniex.py": ["/conf.py", "/console_view.py"], "/console_view.py": ["/conf.py"], "/trade.py": ["/conf.py"], "/fetch_coinmarket.py": ["/console_view.py"], "/poloniex_bot.py": ["/conf.py", "/console_view.py"], "/monitor.py": ["/fetch_web.py", "/fetch_coinmarket.py", "/fetch_poloniex.py", "/fetch_kraken.py"], "/main.py": ["/fetch_web.py", "/fetch_coinmarket.py", "/fetch_poloniex.py", "/fetch_kraken.py", "/auto_monitor.py"]} |
60,895 | kswapd/crypto-trading-bot | refs/heads/master | /stock_simu.py | #! /usr/bin/python
# -*-coding:utf-8-*-
import urllib.request
import json
import sys
import time
import _thread
import logging
import sched
import time
import random
from datetime import datetime
import yaml
def print_time(sc, a='default'):
logging.info("From print_time", time.time(), a)
sc.enter(2, 1, print_time, (sc, a))
def print_time2(a='default'):
logging.info("From print_time2", time.time(), a)
# def cur_random_price(delta_value=1):
class timer_loop():
def __init__(self, interval, duration, func, *args):
self.interval = interval
self.duration = duration
self.func = func
self.param = args
self.run = False
self.schedule = sched.scheduler(time.time, time.sleep)
#self.schedule.enter(self.interval, 1, self.event_func,())
# self.schedule.run()
self.start_time = time.time()
self.end_time = time.time()
self.is_stop = False
# self.event_func()
def event_func(self):
#logging.info("ddddd:", self.param)
self.end_time = time.time()
self.func(self.param)
#logging.info("time:%.2f,%d", self.end_time - self.start_time, self.duration)
if self.end_time - self.start_time > self.duration or self.is_stop:
# self.schedule.cancel(self.event)
return
self.event = self.schedule.enter(self.interval, 1, self.event_func, ())
# if not self.run:
# self.schedule.run()
# self.run = True
def start(self):
self.event_func()
#self.thread = _thread.start_new_thread(self.event_func,())
self.thread = _thread.start_new_thread(self.sched_start, ())
# self.schedule.run()
def stop(self):
self.is_stop = True
def sched_start(self):
self.schedule.run()
#td1 = _thread.start_new_thread( start_coin_market,('55',2) )
class stock_market():
def __init__(self, cfg):
self.is_stop = False
self.coin_url = "https://coinmarketcap.com/"
self.duration = cfg['stock']['day-duration']
self.cur_price = cfg['stock']['stock-open-price']
self.base_price = cfg['stock']['stock-open-price']
self.stock_hold = cfg['stock']['stock-trade-unit']
self.cur_money = 0.0
self.price_change_count = 1
self.change_stock_unit = cfg['stock']['stock-trade-unit']
self.change_price_unit = cfg['stock']['price-step-unit']
self.max_change_price_percent = cfg['stock']['max-change-percent']
sellAIndex = cfg['stock']['sellA-index']
buyBIndex = cfg['stock']['buyB-index']
buyCIndex = cfg['stock']['buyC-index']
buyAIndex = cfg['stock']['buyA-index']
sellBIndex = cfg['stock']['sellB-index']
sellCIndex = cfg['stock']['sellC-index']
# 卖出价A
self.sellA = round(self.cur_price*sellAIndex, 2)
# 赚钱买入价B
self.buyB = round(self.cur_price*buyBIndex, 2)
# 补仓买入价C
self.buyC = round(self.cur_price*buyCIndex, 2)
# 补仓买入价D
self.buyD = round(self.cur_price, 2)
# 买入价A
self.buyA = round(self.cur_price*buyAIndex, 2)
# 赚钱卖出价B
self.sellB = round(self.cur_price*sellBIndex, 2)
# 补仓卖出价C
self.sellC = round(self.cur_price*sellCIndex, 2)
# 补仓卖出价D
self.sellD = round(self.cur_price, 2)
self.status = 'init'
self.changeList = []
logging.info("Max duration:%d", self.duration)
def auto_trade_stock(self):
self.thread2 = _thread.start_new_thread(self.auto_trade_stock_thrd, ())
def auto_trade_stock_thrd(self):
logging.info("auto_trade_stock start.")
global g_market_cur_time
global g_all_changed_asset
while not self.is_stop:
cur = time.time()
curStr = datetime.today().strftime('%Y-%m-%d-%H:%M:%S')
#logging.info("auto_trade_stock start loop. %s",self.status)
if self.status == 'init':
# if self.cur_price >= self.sellA:
if self.cur_price == self.sellA:
self.status = 'sellA'
changed_money = round(
self.cur_price * self.change_stock_unit, 2)
self.changeList.append(
(curStr, 'sell', self.status, self.cur_price, -1*self.change_stock_unit, changed_money))
self.stock_hold -= self.change_stock_unit
self.cur_money += changed_money
logging.info("%d-%d Sell by sellA price %.2f .",
g_market_cur_time, self.price_change_count, self.sellA)
# elif self.cur_price <= self.buyA:
elif self.cur_price == self.buyA:
self.status = 'buyA'
changed_money = -1 * \
round(self.cur_price * self.change_stock_unit, 2)
self.changeList.append(
(curStr, 'buy', self.status, self.cur_price, self.change_stock_unit, changed_money))
self.stock_hold += self.change_stock_unit
self.cur_money += changed_money
logging.info("%d-%d Buy by buyA price %.2f .",
g_market_cur_time, self.price_change_count, self.buyA)
elif self.status == 'sellA':
# if self.cur_price <= self.buyB:
if self.cur_price == self.buyB:
self.status = 'buyB'
changed_money = -1 * \
round(self.cur_price * self.change_stock_unit, 2)
self.changeList.append(
(curStr, 'buy', self.status, self.cur_price, self.change_stock_unit, changed_money))
self.stock_hold += self.change_stock_unit
self.cur_money += changed_money
self.status = 'finish'
assetChanged = round(
self.changeList[0][-1] + self.changeList[1][-1], 2)
g_all_changed_asset += assetChanged
logging.info("%d-%d Trade finished today, asset changed: %.2f, all changed: %.2f",
g_market_cur_time, self.price_change_count, assetChanged, g_all_changed_asset)
logging.info("%d-%d Trading flow:",
g_market_cur_time, self.price_change_count)
for i in self.changeList:
logging.info(i)
# elif self.cur_price <= self.buyC:
elif self.cur_price == self.buyC:
self.status = 'buyC'
changed_money = -1 * \
round(self.cur_price * self.change_stock_unit, 2)
self.changeList.append(
(curStr, 'buy', self.status, self.cur_price, self.change_stock_unit, changed_money))
self.stock_hold += self.change_stock_unit
self.cur_money += changed_money
self.status = 'finish'
assetChanged = round(
self.changeList[0][-1] + self.changeList[1][-1], 2)
g_all_changed_asset += assetChanged
logging.info("%d-%d Trade finished today, asset changed: %.2f, all changed: %.2f",
g_market_cur_time, self.price_change_count, assetChanged, g_all_changed_asset)
logging.info("%d-%d Trading flow:",
g_market_cur_time, self.price_change_count)
for i in self.changeList:
logging.info(i)
# Closing market in 2 seconds:
elif cur - self.start_time >= self.duration - 2:
self.status = 'buyD'
changed_money = -1 * \
round(self.cur_price * self.change_stock_unit, 2)
self.changeList.append(
(curStr, 'buy', self.status, self.cur_price, self.change_stock_unit, changed_money))
self.stock_hold += self.change_stock_unit
self.cur_money += changed_money
self.status = 'finish'
assetChanged = round(
self.changeList[0][-1] + self.changeList[1][-1], 2)
g_all_changed_asset += assetChanged
logging.info("%d-%d Trade finished today, asset changed: %.2f, all changed: %.2f",
g_market_cur_time, self.price_change_count, assetChanged, g_all_changed_asset)
logging.info("%d-%d Trading flow:",
g_market_cur_time, self.price_change_count)
for i in self.changeList:
logging.info(i)
elif self.status == 'buyA':
# if self.cur_price >= self.sellB:
if self.cur_price == self.sellB:
self.status = 'sellB'
changed_money = round(
self.cur_price * self.change_stock_unit, 2)
self.changeList.append(
(curStr, 'sell', self.status, self.cur_price, -1*self.change_stock_unit, changed_money))
self.stock_hold -= self.change_stock_unit
self.cur_money += changed_money
self.status = 'finish'
assetChanged = round(
self.changeList[0][-1] + self.changeList[1][-1], 2)
g_all_changed_asset += assetChanged
logging.info("%d-%d Trade finished today, asset changed: %.2f, all changed: %.2f",
g_market_cur_time, self.price_change_count, assetChanged, g_all_changed_asset)
logging.info("%d-%d Trading flow:",
g_market_cur_time, self.price_change_count)
for i in self.changeList:
logging.info(i)
# elif self.cur_price >= self.sellC:
elif self.cur_price == self.sellC:
self.status = 'sellC'
changed_money = round(
self.cur_price * self.change_stock_unit, 2)
self.changeList.append(
(curStr, 'sell', self.status, self.cur_price, -1*self.change_stock_unit, changed_money))
self.stock_hold -= self.change_stock_unit
self.cur_money += changed_money
self.status = 'finish'
assetChanged = round(
self.changeList[0][-1] + self.changeList[1][-1], 2)
g_all_changed_asset += assetChanged
logging.info("%d-%d Trade finished today, asset changed: %.2f, all changed: %.2f",
g_market_cur_time, self.price_change_count, assetChanged, g_all_changed_asset)
logging.info("%d-%d Trading flow:",
g_market_cur_time, self.price_change_count)
for i in self.changeList:
logging.info(i)
# Closing market in 2 seconds:
elif cur - self.start_time >= self.duration - 2:
self.status = 'sellD'
changed_money = round(
self.cur_price * self.change_stock_unit, 2)
self.changeList.append(
(curStr, 'sell', self.status, self.cur_price, -1*self.change_stock_unit, changed_money))
self.stock_hold -= self.change_stock_unit
self.cur_money += changed_money
self.status = 'finish'
assetChanged = round(
self.changeList[0](-1) + self.changeList[1](-1), 2)
g_all_changed_asset += assetChanged
logging.info("%d-%d Trade finished today, asset changed: %.2f, all changed: %.2f",
g_market_cur_time, self.price_change_count, assetChanged, g_all_changed_asset)
logging.info("%d-%d Trading flow:",
g_market_cur_time, self.price_change_count)
for i in self.changeList:
logging.info(i)
elif self.status == 'finish':
#logging.info("Trading finished..")
self.stop()
pass
else:
logging.info("No trading here..")
time.sleep(0.1)
logging.info("auto_trade_stock finished.")
def print_time3(self, a='default'):
logging.info("From print_time3,%s,%s", time.time(), a)
def change_stock_price(self, delta_value=1):
flag = 'up'
if bool(random.getrandbits(1)):
self.cur_price += self.change_price_unit
else:
flag = 'down'
self.cur_price -= self.change_price_unit
self.cur_price = round(self.cur_price, 2)
logging.info("%d-%d current price:%.2f, %s", g_market_cur_time,
self.price_change_count, self.cur_price, flag)
self.price_change_count += 1
def change_stock_price_by_percent(self, delta_value=1):
flag = 'up'
ref_price = self.cur_price
cur_delta = (self.cur_price - self.base_price) / self.base_price
probability_delta = cur_delta/self.max_change_price_percent*0.5
cur_random = 0.5 + probability_delta
cur_random = 0 if cur_random < 0 else 1 if cur_random > 1 else cur_random
if random.random() > cur_random:
self.cur_price += self.change_price_unit
else:
flag = 'down'
self.cur_price -= self.change_price_unit
self.cur_price = round(self.cur_price, 2)
#logging.info("%d-%d current probability:%.2f,%.2f,%s", g_market_cur_time, self.price_change_count,self.cur_price, 1-cur_random, flag)
logging.info("%d-%d current price:(%.2f->%.2f, %s), up pb:%.2f", g_market_cur_time,
self.price_change_count, ref_price, self.cur_price, flag, 1-cur_random)
self.price_change_count += 1
def stop(self):
self.is_stop = True
self.stock_market.stop()
logging.info('stopped')
def start(self):
self.start_time = time.time()
self.stock_market = timer_loop(
1, self.duration, self.change_stock_price_by_percent)
self.stock_market.start()
self.auto_trade_stock()
while not self.is_stop:
if time.time() - self.start_time > self.duration:
self.stop()
else:
pass
time.sleep(1)
time.sleep(1)
g_market_cur_time = 1
g_all_changed_asset = 0
if __name__ == "__main__":
#logging.basicConfig(format='%(asctime)s %(message)s')
with open("stock.yml", "r") as ymlfile:
cfg = yaml.safe_load(ymlfile)
print('Get configure file.', cfg)
if cfg['log']['level'] == 'INFO':
logLevel = logging.INFO
elif cfg['log']['level'] == 'WARN':
logLevel = logging.WARN
elif cfg['log']['level'] == 'ERROR':
logLevel = logging.ERROR
elif cfg['log']['level'] == 'DEBUG':
logLevel = logging.DEBUG
else:
logLevel = logging.INFO
logging.basicConfig(format='%(asctime)s %(message)s',
filename=cfg['log']['file-name'], level=logLevel)
logging.info('Stock simu started......')
logging.info('Get configure file.')
logging.info(cfg)
#logging.basicConfig(format='%(asctime)s %(message)s', level=logging.INFO)
# logging.basicConfig(filename='./stock.log')
#stock_simu = stock_market(duration=10)
if cfg['stock']['loop-days'] < 1:
while True:
logging.info('Stock market times: %d.', g_market_cur_time)
stock_simu = stock_market(cfg)
try:
stock_simu.start()
except KeyboardInterrupt as e:
stock_simu.stop()
logging.info('Stock simu loop finished by key......')
g_market_cur_time += 1
else:
loop_days = cfg['stock']['loop-days']
while loop_days > 0:
logging.info('Stock market times: %d.', g_market_cur_time)
stock_simu = stock_market(cfg)
try:
stock_simu.start()
except KeyboardInterrupt as e:
stock_simu.stop()
logging.info('Stock simu finished by key......')
g_market_cur_time += 1
loop_days -= 1
logging.info('Stock simu finished......')
| {"/fetch_huobi.py": ["/conf.py", "/console_view.py"], "/fetch_kraken.py": ["/console_view.py", "/conf.py"], "/fetch_poloniex.py": ["/conf.py", "/console_view.py"], "/console_view.py": ["/conf.py"], "/trade.py": ["/conf.py"], "/fetch_coinmarket.py": ["/console_view.py"], "/poloniex_bot.py": ["/conf.py", "/console_view.py"], "/monitor.py": ["/fetch_web.py", "/fetch_coinmarket.py", "/fetch_poloniex.py", "/fetch_kraken.py"], "/main.py": ["/fetch_web.py", "/fetch_coinmarket.py", "/fetch_poloniex.py", "/fetch_kraken.py", "/auto_monitor.py"]} |
60,896 | kswapd/crypto-trading-bot | refs/heads/master | /main.py | #! /usr/bin/python
#! /usr/bin/python
#-*-coding:utf-8-*-
#import ccxt as ct
import pprint as pp
#import trade
import time
import fetch_web
import fetch_coinmarket
import fetch_yobit
import fetch_poloniex
import fetch_kraken
import _thread
import curses
import auto_monitor
if __name__ == "__main__":
monitor = auto_monitor.auto_monitor()
try:
monitor.start()
except KeyboardInterrupt as e:
monitor.stop()
| {"/fetch_huobi.py": ["/conf.py", "/console_view.py"], "/fetch_kraken.py": ["/console_view.py", "/conf.py"], "/fetch_poloniex.py": ["/conf.py", "/console_view.py"], "/console_view.py": ["/conf.py"], "/trade.py": ["/conf.py"], "/fetch_coinmarket.py": ["/console_view.py"], "/poloniex_bot.py": ["/conf.py", "/console_view.py"], "/monitor.py": ["/fetch_web.py", "/fetch_coinmarket.py", "/fetch_poloniex.py", "/fetch_kraken.py"], "/main.py": ["/fetch_web.py", "/fetch_coinmarket.py", "/fetch_poloniex.py", "/fetch_kraken.py", "/auto_monitor.py"]} |
60,897 | kswapd/crypto-trading-bot | refs/heads/master | /coinmarket_bot.py | #! /usr/bin/python
# -*-coding:utf-8-*-
import json
import sys
import time
import requests
from bs4 import BeautifulSoup
from requests.adapters import HTTPAdapter
from requests.packages.urllib3.util.retry import Retry
session = requests.Session()
proxyDict = {
'http': 'socks5://127.0.0.1:1081',
'https': 'socks5://127.0.0.1:1081'
}
proxyDict2 = {
'http': 'http://127.0.0.1:8001',
'https': 'https://127.0.0.1:8001'
}
session.proxies.update(proxyDict2)
retry = Retry(connect=3, backoff_factor=0.5)
adapter = HTTPAdapter(max_retries=retry)
session.mount('http://', adapter)
session.mount('https://', adapter)
class coinmarket_bot():
def __init__(self, x=0, y=0, width=80, height=15, is_view=True):
self.is_stop = False
self.num = 50
self.pos_y = 2
self.targetSymbol = ('BTC', 'ETH', 'XRP', 'BCH',
'LTC', 'DASH', 'USDT', 'DOGE')
#self.coin_url = "https://pro-api.coinmarketcap.com/v1/ticker/?limit=%d"%self.num
self.base_url = "https://coinmarketcap.com/"
def stop(self):
self.is_stop = True
print('stopped')
def list_price(self):
print("Getting cryptocurrency info from url:", self.base_url)
while not self.is_stop:
cur_pos_x = 2
headers = {
'Accepts': 'application/json',
'X-CMC_PRO_API_KEY': 'b22f9e6d-6c09-431d-ac9a-fd87131fc9a5',
}
#content = requests.get(self.coin_url).content
content = session.get(self.base_url).content
goods_title_imgs = []
goods_detail_imgs = []
soup = BeautifulSoup(content, "html.parser")
coin_table = soup.find('table', class_='cmc-table')
tb = coin_table.find('tbody')
# print(soup)
trs = tb.find_all('tr')
print("List time:", time.strftime(
"%Y-%m-%d %H:%M:%S", time.localtime()))
for tr in trs[0:10]:
# print(len(trs))
# print(tr.get_text())
all_td = tr.find_all('td')
coin_seq = all_td[1].find('p').get_text()
coin_name = all_td[2].find(
'div', class_='sc-16r8icm-0').find('p').get_text()
coin_name_simp = all_td[2].find(
'div', class_='sc-1teo54s-2').find('p').get_text()
coin_price = all_td[3].get_text()
coin_price_change_24h = all_td[4].get_text()
coin_price_change_7d = all_td[5].get_text()
coin_market_cap = all_td[6].get_text()
coin_volume = all_td[7].get_text()
coin_image = all_td[9].find('img').get('src')
print(coin_seq, coin_name, coin_name_simp, coin_price, coin_price_change_24h, coin_price_change_7d,
coin_market_cap, coin_volume)
# return
time.sleep(10)
if __name__ == "__main__":
coinmarket_bot = coinmarket_bot()
try:
coinmarket_bot.list_price()
except KeyboardInterrupt as e:
coinmarket_bot.stop()
| {"/fetch_huobi.py": ["/conf.py", "/console_view.py"], "/fetch_kraken.py": ["/console_view.py", "/conf.py"], "/fetch_poloniex.py": ["/conf.py", "/console_view.py"], "/console_view.py": ["/conf.py"], "/trade.py": ["/conf.py"], "/fetch_coinmarket.py": ["/console_view.py"], "/poloniex_bot.py": ["/conf.py", "/console_view.py"], "/monitor.py": ["/fetch_web.py", "/fetch_coinmarket.py", "/fetch_poloniex.py", "/fetch_kraken.py"], "/main.py": ["/fetch_web.py", "/fetch_coinmarket.py", "/fetch_poloniex.py", "/fetch_kraken.py", "/auto_monitor.py"]} |
60,898 | kswapd/crypto-trading-bot | refs/heads/master | /fetch_images.py | #! /usr/bin/python3
#-*-coding:utf-8-*-
'''
批量下载豆瓣首页的图片
采用伪装浏览器的方式爬取豆瓣网站首页的图片,保存到指定路径文件夹下
'''
#导入所需的库
import urllib.request.request,socket,re,sys,os
#定义文件保存路径
targetPath = "./images"
def saveFile(path):
#检测当前路径的有效性
if not os.path.isdir(targetPath):
os.mkdir(targetPath)
#设置每个图片的路径
pos = path.rindex('/')
t = os.path.join(targetPath,path[pos+1:])
print(t)
return t
#用if __name__ == '__main__'来判断是否是在直接运行该.py文件
# 网址
url = "https://www.douban.com/"
#headers = {
# 'User-Agent':'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36'
# }
headers = {
'User-Agent':'Mozilla/6.0 (Macintosh; Intel Mac OS X 10_12_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36'
}
req = urllib.request.Request(url=url, headers=headers)
res = urllib.request.urlopen(req)
data = res.read()
for link,t in set(re.findall(r'(https:[^s]*?(jpg|png|gif))', str(data))):
#link = 'http://img.jandan.net/news'+link
#link = link[:-7]
print(link)
try:
urllib.request.urlretrieve(link,saveFile(link))
#urllib.request.urlretrieve(link)
except:
print('失败')
| {"/fetch_huobi.py": ["/conf.py", "/console_view.py"], "/fetch_kraken.py": ["/console_view.py", "/conf.py"], "/fetch_poloniex.py": ["/conf.py", "/console_view.py"], "/console_view.py": ["/conf.py"], "/trade.py": ["/conf.py"], "/fetch_coinmarket.py": ["/console_view.py"], "/poloniex_bot.py": ["/conf.py", "/console_view.py"], "/monitor.py": ["/fetch_web.py", "/fetch_coinmarket.py", "/fetch_poloniex.py", "/fetch_kraken.py"], "/main.py": ["/fetch_web.py", "/fetch_coinmarket.py", "/fetch_poloniex.py", "/fetch_kraken.py", "/auto_monitor.py"]} |
60,899 | kswapd/crypto-trading-bot | refs/heads/master | /auto_monitor.py | #! /usr/bin/python
#-*-coding:utf-8-*-
#import ccxt as ct
import pprint as pp
#import trade
import time
import fetch_web
import fetch_coinmarket
import fetch_yobit
import fetch_poloniex
import fetch_kraken
import fetch_binance
import fetch_huobi
import _thread
import curses
import monitor
import logging
from logging.handlers import TimedRotatingFileHandler
from logging.handlers import RotatingFileHandler
import re
import console_view as cv
class auto_monitor(cv.console_view):
def __init__(self, x = 0, y = 0, width = 130, height = 15, is_view = True):
#cv.console_view.__init__(self, x, y, width, height, is_view)
self.p_info = {}
self.k_info = {}
self.log_init()
self.min_w = 30
self.min_h = 15
self.min_y = 16
def log_init(self):
'''
log_fmt = '%(asctime)s\tFile \"%(filename)s\",line %(lineno)s\t%(levelname)s: %(message)s'
formatter = logging.Formatter(log_fmt)
log_file_handler = TimedRotatingFileHandler(filename="monitor"+"_thread", when="D", interval=1, backupCount=7)
log_file_handler.suffix = "%Y-%m-%d_%H-%M.log"
log_file_handler.extMatch = re.compile(r"^\d{4}-\d{2}-\d{2}_\d{2}-\d{2}.log$")
log_file_handler.setFormatter(formatter)
log_file_handler.setLevel(logging.DEBUG)
log = logging.getLogger()
log.addHandler(log_file_handler)
'''
logging.basicConfig(level=logging.DEBUG,
format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',
#datefmt='%a, %d %b %Y %H:%M:%S',
filename='monitor.log',
filemode='w')
def start_coin_market(self, thrd_name, delay):
coin_market = fetch_coinmarket.fetch_coinmarket()
coin_market.start()
def start_yobit(self, thrd_name,delay):
self.yobit = fetch_yobit.fetch_yobit(self.min_w*2,self.min_y,self.min_w,self.min_h)
self.y_info = self.yobit.monitor_info
self.yobit.get_ticker()
def start_binance(self, thrd_name,delay):
self.binance = fetch_binance.fetch_binance(self.min_w*3,self.min_y,self.min_w,self.min_h)
self.binance_info = self.binance.monitor_info
self.binance.get_ticker()
def start_poloniex(self, thrd_name,delay):
self.poloniex = fetch_poloniex.fetch_poloniex(0,self.min_y,self.min_w,self.min_h)
self.p_info = self.poloniex.monitor_info
self.poloniex.get_open_info()
def start_huobi(self, thrd_name,delay):
self.huobi = fetch_huobi.fetch_huobi(0,self.min_y,self.min_w,self.min_h)
self.huobi_info = self.huobi.monitor_info
self.huobi.get_open_info()
def start_kraken(self, thrd_name,delay):
self.kraken = fetch_kraken.fetch_kraken(self.min_w,self.min_y,self.min_w,self.min_h)
self.k_info = self.kraken.monitor_info
self.kraken.get_open_info()
def start_monitor(self, thrd_name,delay):
logging.info('start monitor...')
print('start monitor...')
time.sleep(2)
#stdscr = curses.newwin(15, 140, 0, 0)
#stdscr = curses.newwin(self.display_pos['height'], self.display_pos['width'], self.display_pos['y'], self.display_pos['x'])
#curses.start_color()
#curses.init_pair(1, curses.COLOR_GREEN, curses.COLOR_BLACK)
#curses.init_pair(2, curses.COLOR_RED, curses.COLOR_BLACK)
#curses.init_pair(3, curses.COLOR_YELLOW, curses.COLOR_BLACK)
while True:
self.p_info = self.poloniex.monitor_info
self.k_info = self.kraken.monitor_info
#self.y_info = self.yobit.monitor_info
#self.binance_info = self.binance.monitor_info
self.huobi_info = self.huobi.monitor_info
pos_x = 2
pos_y = 2
#stdscr.box(curses.ACS_VLINE, curses.ACS_HLINE)
#stdscr.addstr(pos_x,pos_y,'Cryptocurrency exchange Monitor', curses.color_pair(3))
pos_x += 1
nowtime = time.time()
ptime = time.strftime('%H:%M:%S', time.localtime(self.p_info['time']))
ktime = time.strftime('%H:%M:%S', time.localtime(self.k_info['time']))
huobitime = time.strftime('%H:%M:%S', time.localtime(self.huobi_info['time']))
sub_ptime = self.p_info['time'] - nowtime
#sub_ytime = self.y_info['time'] - nowtime
sub_ktime = self.k_info['time'] - nowtime
#sub_binancetime = self.binance_info['time'] - nowtime
sub_huobitime = self.huobi_info['time'] - nowtime
#stdscr.addstr(pos_x,pos_y,time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(nowtime) ), curses.color_pair(3))
pos_x += 1
time_comp = ' P:%.2fs|huobi:%.2fs|K:%.2fs'%(sub_ptime, sub_huobitime, sub_ktime)
alltime_info = 'P:'+ptime + '|huobi:' + huobitime +'|K:'+ktime + time_comp
#stdscr.addstr(pos_x, pos_y, alltime_info, curses.color_pair(3))
pos_x += 1
print_head = "Symbol \tP \thuobi"
#stdscr.addstr(pos_x,pos_y,print_head,curses.color_pair(3))
pos_x += 1
all_coin = [ 'LTC']
for coin in all_coin:
cur = coin
#print('{:}'.format(self.k_info[cur]))
pbp = self.p_info[cur]['bid']['price']
pbn = self.p_info[cur]['bid']['num']
pap = self.p_info[cur]['ask']['price']
pan = self.p_info[cur]['ask']['num']
hap = self.huobi_info[cur]['ask']['price']
han = self.huobi_info[cur]['ask']['num']
hbp = self.huobi_info[cur]['bid']['price']
hbn = self.huobi_info[cur]['bid']['num']
kbp = self.k_info[cur]['bid']['price']
kbn = self.k_info[cur]['bid']['num']
kap = self.k_info[cur]['ask']['price']
kan = self.k_info[cur]['ask']['num']
all_exchanges_info = {'poloniex':self.p_info[cur], 'huobi':self.huobi_info, 'kraken':self.k_info}
max_bid = sorted(dict,key=lambda x:all_exchanges_info[x]['bid']['price'])[-1]
min_ask = sorted(dict,key=lambda x:all_exchanges_info[x]['ask']['price'])[0]
print('maxbid:%s, minask:%s'%(max_bid, min_ask))
#bid_price = [pbp, hbp, kbp]
#ask_price = [pap, hap, kap]
sub1 = pbp - hap
percent1 = sub1*100/hap
if percent1 < -100 or percent1 > 100:
percent1 = -1.00
if percent1 > 1.0 and cur=='LTC':
logging.info('get chance:%.2f,%.2f, %.2f,%.2f, %.2f'%(pbp, pbn,hap,han, percent1))
trade_num = pbn if pbn < han else han
self.poloniex.sell('LTC', pbp, trade_num)
self.huobi.buy('ltc', hap, trade_num)
sub2 = hbp - pap
percent2 = sub2*100/pap
if percent2 < -100 or percent2 > 100:
percent2 = -1.00
if percent2 > 1.0 and cur == 'LTC':
logging.info('get chance2:%.2f,%.2f, %.2f,%.2f, %.2f'%(hbp, hbn,pap,pan, percent2))
trade_num2 = hbn if hbn < pan else pan
self.huobi.sell('ltc', hbp, trade_num2)
self.poloniex.buy('LTC', pap, trade_num2)
sub3 = hbp - kap
percent3 = sub3*100/kap
if percent3 < -100 or percent3 > 100:
percent3 = -1.00
if percent3 > 1.0 and cur == 'LTC':
logging.info('get chance3:%.2f,%.2f, %.2f,%.2f, %.2f'%(hbp, hbn,kap,kan, percent3))
trade_num3 = hbn if hbn < kan else kan
self.huobi.sell('ltc', hbp, trade_num3)
self.kraken.buy('LTC', kap, trade_num3)
sub4 = kbp - hap
percent4 = sub4*100/hap
if percent4 < -100 or percent4 > 100:
percent4 = -1.00
if percent4 > 1.0 and cur=='LTC':
logging.info('get chance4:%.2f,%.2f, %.2f,%.2f, %.2f'%(kbp, kbn,hap,han, percent4))
trade_num4 = kbn if kbn < han else han
self.kraken.sell('LTC', kbp, trade_num4)
self.huobi.buy('ltc', hap, trade_num4)
sub5 = pbp - kap
percent5 = sub5*100/kap
if percent5 < -100 or percent5 > 100:
percent5 = -1.00
if percent5 > 1.0 and cur=='LTC':
logging.info('get chance5:%.2f,%.2f, %.2f,%.2f, %.2f'%(pbp, pbn,kap,kan, percent5))
trade_num5 = pbn if pbn < kan else kan
self.poloniex.sell('LTC', pbp, trade_num5)
self.kraken.buy('LTC', kap, trade_num5)
sub6 = kbp - pap
percent6 = sub6*100/pap
if percent6 < -100 or percent6 > 100:
percent6 = -1.00
if percent6 > 1.0 and cur=='LTC':
logging.info('get chance6:%.2f,%.2f, %.2f,%.2f, %.2f'%(kbp, kbn,pap,pan, percent6))
trade_num6 = kbn if kbn < pan else pan
self.kraken.sell('LTC', kbp, trade_num6)
self.poloniex.buy('LTC', pap, trade_num6)
prt_str = coin + " \t\t%7.2f \t%7.2f \t%7.2f"%(pbp, hbp, kbp)
log_str_price = coin + ",%.2f,%.2f,%.2f,%.2f,%.2f,%.2f"%(percent1,percent2,percent3,percent4,percent5,percent6)
#log_str_num = ",%.2f,%.2f,%.2f,%.2f"%(pbn, han, hbn, pan)
#prt_str = re.sub(r'(-1.00)','--\t', prt_str)
#stdscr.addstr(pos_x,pos_y,prt_str,curses.color_pair(3))
pos_x += 1
log_str = log_str_price
#log_str = re.sub(r'(-1.00)','--', log_str)
logging.info(log_str)
#stdscr.refresh()
time.sleep(2)
def start(self):
try:
#curses.initscr()
#curses.noecho()
#curses.cbreak()
#curses.curs_set(0)
#td1 = _thread.start_new_thread( start_coin_market,('55',2) )
#td2 = _thread.start_new_thread( self.start_yobit,('5',2) )
#td6 = _thread.start_new_thread( self.start_binance,('9',2) )
#td3 = _thread.start_new_thread( self.start_poloniex,('6',2) )
#td4 = _thread.start_new_thread( self.start_kraken,('7',2) )
#td5 = _thread.start_new_thread( self.start_monitor,('8',2) )
#td7 = _thread.start_new_thread( self.start_huobi,('9',2) )
#time.sleep(0.5)
except KeyboardInterrupt as e:
#coin_market.stop()
print('over')
try:
while 1:
pass
except KeyboardInterrupt as e:
#coin_market.stop()
#curses.endwin()
print('over')
def stop(self):
print('over')
#curses.endwin()
if __name__ == "__main__":
#curses.initscr()
#curses.noecho()
info = auto_monitor()
try:
info.start()
except KeyboardInterrupt as e:
info.stop()
| {"/fetch_huobi.py": ["/conf.py", "/console_view.py"], "/fetch_kraken.py": ["/console_view.py", "/conf.py"], "/fetch_poloniex.py": ["/conf.py", "/console_view.py"], "/console_view.py": ["/conf.py"], "/trade.py": ["/conf.py"], "/fetch_coinmarket.py": ["/console_view.py"], "/poloniex_bot.py": ["/conf.py", "/console_view.py"], "/monitor.py": ["/fetch_web.py", "/fetch_coinmarket.py", "/fetch_poloniex.py", "/fetch_kraken.py"], "/main.py": ["/fetch_web.py", "/fetch_coinmarket.py", "/fetch_poloniex.py", "/fetch_kraken.py", "/auto_monitor.py"]} |
60,900 | funyoo/sinny | refs/heads/master | /module/video/video_player.py | """
视频播放者 video_player
使用 omxlayer 播放视频
提供两种播放方式:循环播放 和 播放一次
@author: funyoo
"""
from omxplayer import OMXPlayer
from pathlib import Path
from time import sleep
from module.video import sys_video_list
PLAYING = False
HAVE_STOP = True
SLEEP_STEP = 0.5
NOW_PLAYING = sys_video_list.SLEEP_VIDEO
# 循环播放
def loopPlay(file, clock):
global PLAYING, HAVE_STOP
# 停止之前播放的视频
PLAYING = False
while HAVE_STOP is False:
continue
# 播放新视频
PLAYING = True
HAVE_STOP = False
video_path = Path(file)
clock = float(clock)
contin = True
while PLAYING:
player = OMXPlayer(video_path)
now_clock = 0
while contin:
sleep(SLEEP_STEP)
now_clock += SLEEP_STEP
if now_clock == clock:
break
if PLAYING is False:
contin = False
HAVE_STOP = True
# 播放一次
def playOnce(file, clock):
global PLAYING, HAVE_STOP
# 停止之前播放的视频
PLAYING = False
while HAVE_STOP is False:
continue
# 播放新视频
PLAYING = True
HAVE_STOP = False
video_path = Path(file)
clock = float(clock)
contin = True
player = OMXPlayer(video_path)
now_clock = 0
while contin:
sleep(SLEEP_STEP)
now_clock += SLEEP_STEP
if now_clock == clock:
PLAYING = False
break
if PLAYING is False:
contin = False
HAVE_STOP = True | {"/module/voice_module.py": ["/module/base_module.py"], "/module/rgb_module.py": ["/module/base_module.py"], "/main.py": ["/module_register.py", "/wake_up.py"], "/wake_up.py": ["/commander.py"], "/module/picture_module.py": ["/module/base_module.py"], "/commander.py": ["/reader.py", "/module_register.py"]} |
60,901 | funyoo/sinny | refs/heads/master | /module/voice_module.py | """
控制树莓派rgb灯:
通过udp接收命令完成相应控制
@author: funyoo
"""
import socket
import threading
import time
from module.base_module import BaseModule
from module.voice import voice_operator
BUFFSIZE = 1024
COMMANDS = ["command:.*", ".*播放音.*"]
ip_port = ('127.0.0.1', 9003)
server = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
START = False
COMMAND_ID = 0
class Voice(BaseModule):
def ip_port(self):
global ip_port
return ip_port
def startup(self):
global START, server
server.bind(ip_port)
START = True
working_thread = threading.Thread(target=self.working, args=())
working_thread.start()
print("voice 服务已启动")
def shutdown(self):
global START, server
START = False
server.close()
def commands(self):
global COMMANDS
return COMMANDS
def working(self):
global BUFFSIZE, START, COMMAND_ID
while START:
command, client_addr = server.recvfrom(BUFFSIZE)
command_str = command.decode("utf-8")
print("收到来自 " + str(client_addr) + " 的指令: " + command_str + " ", time.time())
# 取命令编号 记录并判断 防止重复执行同一命令 系统命令编号 0
data = str(command_str).split("-")
id = int(data[1])
if COMMAND_ID >= id > 0:
continue
if id is not 0:
COMMAND_ID = id
voice_operator.operate(data[0])
| {"/module/voice_module.py": ["/module/base_module.py"], "/module/rgb_module.py": ["/module/base_module.py"], "/main.py": ["/module_register.py", "/wake_up.py"], "/wake_up.py": ["/commander.py"], "/module/picture_module.py": ["/module/base_module.py"], "/commander.py": ["/reader.py", "/module_register.py"]} |
60,902 | funyoo/sinny | refs/heads/master | /module/rgb/rgb_operator.py | """
rgb操作者
过滤命令,再委托给 rgb_worker执行
@author: funyoo
"""
from module.rgb import rgb_worker
import threading
# 操作入口
def operate(msg):
if "command:" in msg:
sysCommand(msg)
else:
userCommand(msg)
# 用户命令
def userCommand(msg):
if "开" in msg:
# 彩虹渐变灯命令
if "渐变" in msg or "彩虹" in msg or "彩色" in msg:
print("正在开启彩虹。。。")
thread = threading.Thread(target=rgb_worker.gradualChange, args=())
thread.start()
else:
if "打" in msg:
msg = msg.replace("打", "")
if "开" in msg:
msg = msg.replace("开", "")
if "LED" in msg:
msg = msg.replace("LED", "")
if "灯" in msg:
msg = msg.replace("灯", "")
msg = msg.replace(".", "")
msg = msg.replace("。", "")
msg = msg.replace(" ", "")
print("过滤结果:" + msg)
rgb_worker.openRgbByName(msg)
if "关" in msg:
rgb_worker.close()
# 系统命令
def sysCommand(command):
clock = command.replace("command:", "")
rgb_worker.openRgbByRGB([255, 255, 255], clock)
| {"/module/voice_module.py": ["/module/base_module.py"], "/module/rgb_module.py": ["/module/base_module.py"], "/main.py": ["/module_register.py", "/wake_up.py"], "/wake_up.py": ["/commander.py"], "/module/picture_module.py": ["/module/base_module.py"], "/commander.py": ["/reader.py", "/module_register.py"]} |
60,903 | funyoo/sinny | refs/heads/master | /module/rgb_module.py | """
控制树莓派rgb灯:
通过udp接收命令完成相应控制
@author: funyoo
"""
import socket
import threading
import time
from module.base_module import BaseModule
from module.rgb import rgb_operator
BUFFSIZE = 1024
COMMANDS = [".*[开,关].*[灯,彩虹,LED]", "command:.*"]
IP_PORT = ('127.0.0.1', 9001)
SERVER = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
START = False
COMMAND_ID = 0
class Rgb(BaseModule):
def ip_port(self):
global IP_PORT
return IP_PORT
def startup(self):
global START, SERVER
SERVER.bind(IP_PORT)
START = True
working_thread = threading.Thread(target=self.working, args=())
working_thread.start()
print("rgb 服务已启动")
def shutdown(self):
global START, server
START = False
server.close()
def commands(self):
global COMMANDS
return COMMANDS
def working(self):
global BUFFSIZE, START, COMMAND_ID
while START:
command_str, client_addr = SERVER.recvfrom(BUFFSIZE)
command_str = command_str.decode("utf-8")
print("收到来自 " + str(client_addr) + " 的指令: " + command_str + " ", time.time())
# 取命令编号
data = str(command_str).split("-")
id = int(data[1])
if 0 < id <= COMMAND_ID:
continue
if COMMAND_ID is not 0:
COMMAND_ID = id
rgb_operator.operate(data[0])
if __name__ == "__main__":
rgb = Rgb()
rgb.startup()
workingThread = threading.Thread(target=rgb.working, args=())
workingThread.start()
workingThread.join()
| {"/module/voice_module.py": ["/module/base_module.py"], "/module/rgb_module.py": ["/module/base_module.py"], "/main.py": ["/module_register.py", "/wake_up.py"], "/wake_up.py": ["/commander.py"], "/module/picture_module.py": ["/module/base_module.py"], "/commander.py": ["/reader.py", "/module_register.py"]} |
60,904 | funyoo/sinny | refs/heads/master | /module/picture/picture_player.py | """
图片操作者
"""
import threading
import time
LOOP = False
STOP = True
def playPic(file):
print("ss")
def playPics(pics, space=0.03, loop=False):
print(pics)
print(space)
print(loop)
global LOOP, STOP
while LOOP:
for pic in pics:
print("显示图片")
time.sleep(space)
# 显示图片
if loop:
continue
else:
break
STOP = True
def loopPlayPics(pics):
global LOOP
if LOOP:
LOOP = False
while STOP is False:
continue
LOOP = True
thread = threading.Thread(target=playPics, args=(pics, 0.03, True))
thread.start()
if __name__ == "__main__":
loopPlayPics("lll") | {"/module/voice_module.py": ["/module/base_module.py"], "/module/rgb_module.py": ["/module/base_module.py"], "/main.py": ["/module_register.py", "/wake_up.py"], "/wake_up.py": ["/commander.py"], "/module/picture_module.py": ["/module/base_module.py"], "/commander.py": ["/reader.py", "/module_register.py"]} |
60,905 | funyoo/sinny | refs/heads/master | /main.py | """
项目启动主程序
@author: funyoo
"""
import sys
import module_register
import wake_up
import signal
# 检查唤醒词
if len(sys.argv) == 1:
print("Error: need to specify model name")
print("Usage: python xxx.py your.model")
sys.exit(-1)
# 定义信号处理函数 参数:用来识别信号 进程栈状态
def signal_handle(signal, frame):
wake_up.setInterrupt(True)
wake_up.stop()
while wake_up.STOP is False:
continue
sys.exit(-1)
# 中断信号
signal.signal(signal.SIGINT, signal_handle)
model = sys.argv[1]
module_register.startup()
wake_up.startup(model)
| {"/module/voice_module.py": ["/module/base_module.py"], "/module/rgb_module.py": ["/module/base_module.py"], "/main.py": ["/module_register.py", "/wake_up.py"], "/wake_up.py": ["/commander.py"], "/module/picture_module.py": ["/module/base_module.py"], "/commander.py": ["/reader.py", "/module_register.py"]} |
60,906 | funyoo/sinny | refs/heads/master | /module/voice/voice_operator.py | """
音频操作者
负责处理音频命令 交由 voice_player 播放
"""
from module.voice import voice_player
from module.voice import sys_voice_list
# 处理命令
def operate(command):
if "command:" in command:
# 系统命令
sysCommand(command)
else:
# 用户命令
userCommand(command)
# 系统命令处理
def sysCommand(command):
sys_command = command.replace("command:", "")
if sys_command == "wozai":
voice_player.play(sys_voice_list.WO_ZAI)
if sys_command == "hao":
voice_player.play(sys_voice_list.HAO)
if sys_command == "err":
voice_player.play(sys_voice_list.ERR)
# 用户命令处理
def userCommand(command):
# TODO more and more
return | {"/module/voice_module.py": ["/module/base_module.py"], "/module/rgb_module.py": ["/module/base_module.py"], "/main.py": ["/module_register.py", "/wake_up.py"], "/wake_up.py": ["/commander.py"], "/module/picture_module.py": ["/module/base_module.py"], "/commander.py": ["/reader.py", "/module_register.py"]} |
60,907 | funyoo/sinny | refs/heads/master | /module/voice/sys_voice_list.py | """
系统声音列表
"""
ROOT_PATH = "/home/pi/Sinny/resources/voice/"
WO_ZAI = ROOT_PATH + "wozai.mp3"
HAO = ROOT_PATH + "hao.wav"
ERR = ROOT_PATH + "err.wav" | {"/module/voice_module.py": ["/module/base_module.py"], "/module/rgb_module.py": ["/module/base_module.py"], "/main.py": ["/module_register.py", "/wake_up.py"], "/wake_up.py": ["/commander.py"], "/module/picture_module.py": ["/module/base_module.py"], "/commander.py": ["/reader.py", "/module_register.py"]} |
60,908 | funyoo/sinny | refs/heads/master | /module/picture/picture_operate.py | """
图片控制者
@author: funyoo
"""
# 处理命令
def operate(command):
if "command:" in command:
# 系统命令
sysCommand(command)
else:
# 用户命令
userCommand(command)
# 系统命令处理
def sysCommand(command):
sys_command = command.replace("command:", "")
if sys_command == "sleep":
# 显示睡眠图片组
return
if sys_command == "wozai":
# 显示我在图片组
return
# 用户命令处理
def userCommand(command):
# TODO
return | {"/module/voice_module.py": ["/module/base_module.py"], "/module/rgb_module.py": ["/module/base_module.py"], "/main.py": ["/module_register.py", "/wake_up.py"], "/wake_up.py": ["/commander.py"], "/module/picture_module.py": ["/module/base_module.py"], "/commander.py": ["/reader.py", "/module_register.py"]} |
60,909 | funyoo/sinny | refs/heads/master | /module/voice/voice_player.py | """
声音播放
@author funyoo
"""
import os
import pygame
import threading
# 播放音频
def play(file):
# frequency用来控制速度
# pygame.mixer.init(frequency=16000, size=0)
#
# pygame.mixer.music.load(file)
# pygame.mixer.music.play()
# while pygame.mixer.music.get_busy():
# continue
# pygame.mixer.music.stop()
os.system("omxplayer -o local " + file)
# 异步播放音频
def playOnThread(file):
thread = threading.Thread(target=play, args=file)
thread.start() | {"/module/voice_module.py": ["/module/base_module.py"], "/module/rgb_module.py": ["/module/base_module.py"], "/main.py": ["/module_register.py", "/wake_up.py"], "/wake_up.py": ["/commander.py"], "/module/picture_module.py": ["/module/base_module.py"], "/commander.py": ["/reader.py", "/module_register.py"]} |
60,910 | funyoo/sinny | refs/heads/master | /wake_up.py | """
唤醒程序:借助 snowboy 唤醒
@author: funyoo
"""
import sys
sys.path.append('./snowboy/examples/Python3/')
import snowboydecoder
import signal
import logging
import commander
interrupted = False
detector = object
STOP = False
def startup(model):
global detector
# 初始化探测器 参数:唤醒词文件 灵敏度
detector = snowboydecoder.HotwordDetector(model, sensitivity=0.5)
print('Listening... Press Ctrl+C to exit')
# main loop
start()
def interrupt_callback():
global interrupted
return interrupted
def setInterrupt(value):
global interrupted
interrupted = bool(value)
# 被唤醒回调函数
def detected():
global detector
snowboydecoder.play_audio_file()
print("Now! I was waken up!")
logging.info("Now! I was waken up!")
# 侦听命令
stop()
commander.command()
print("重新开启唤醒功能00")
start()
def start():
global detector
detector.start(detected_callback=detected,
interrupt_check=interrupt_callback,
sleep_time=0.03)
def stop():
global detector, STOP
detector.terminate()
STOP = True
| {"/module/voice_module.py": ["/module/base_module.py"], "/module/rgb_module.py": ["/module/base_module.py"], "/main.py": ["/module_register.py", "/wake_up.py"], "/wake_up.py": ["/commander.py"], "/module/picture_module.py": ["/module/base_module.py"], "/commander.py": ["/reader.py", "/module_register.py"]} |
60,911 | funyoo/sinny | refs/heads/master | /module/picture_module.py | """
控制树莓派图片模块:
通过udp接收命令完成相应控制
@author: funyoo
"""
import socket
import threading
import time
from module.base_module import BaseModule
from module.picture import picture_operate
BUFFSIZE = 1024
COMMANDS = ["command:.*"]
IP_PORT = ('127.0.0.1', 9004)
SERVER = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
START = False
COMMAND_ID = 0
class Picture(BaseModule):
def ip_port(self):
global IP_PORT
return IP_PORT
def startup(self):
global START, SERVER
SERVER.bind(IP_PORT)
START = True
working_thread = threading.Thread(target=self.working, args=())
working_thread.start()
print("picture 服务已启动")
def shutdown(self):
global START, SERVER
START = False
SERVER.close()
def commands(self):
global COMMANDS
return COMMANDS
def working(self):
global BUFFSIZE, START, COMMAND_ID
while START:
command_str, client_addr = SERVER.recvfrom(BUFFSIZE)
command_str = command_str.decode("utf-8")
print("收到来自 " + str(client_addr) + " 的指令: " + command_str + " ", time.time())
# 取命令编号
data = str(command_str).split("-")
id = int(data[1])
if 0 < id <= COMMAND_ID:
continue
if COMMAND_ID is not 0:
COMMAND_ID = id
picture_operate.operate(data[0])
| {"/module/voice_module.py": ["/module/base_module.py"], "/module/rgb_module.py": ["/module/base_module.py"], "/main.py": ["/module_register.py", "/wake_up.py"], "/wake_up.py": ["/commander.py"], "/module/picture_module.py": ["/module/base_module.py"], "/commander.py": ["/reader.py", "/module_register.py"]} |
60,912 | funyoo/sinny | refs/heads/master | /module/base_module.py | """
为所有module提供基类
所有功能模块都要实现以下方法:
ip_port:获取功能模块地址
startup: 开启服务
shutdown:关闭
commands: 服务识别关键信息
working: 服务方法
@author: funyoo
"""
import abc
class BaseModule(object):
@abc.abstractmethod
def ip_port(self):
pass
@abc.abstractmethod
def startup(self):
pass
@abc.abstractmethod
def shutdown(self):
pass
@abc.abstractmethod
def commands(self):
pass
@abc.abstractmethod
def working(self):
pass
| {"/module/voice_module.py": ["/module/base_module.py"], "/module/rgb_module.py": ["/module/base_module.py"], "/main.py": ["/module_register.py", "/wake_up.py"], "/wake_up.py": ["/commander.py"], "/module/picture_module.py": ["/module/base_module.py"], "/commander.py": ["/reader.py", "/module_register.py"]} |
60,913 | funyoo/sinny | refs/heads/master | /module_register.py | """
服务注册中心
负责扫描 module 下的各服务,并通过反射启动服务
@author: funyoo
"""
import importlib
import os
# 服务文件列表
service_filenames = []
# 命令匹配列表 [[命令正则,(ip,port)]]
commands_list = []
def startup(dirPath="./module"):
search_services("./module")
load_services()
def search_services(dirPath):
global service_filenames
print("开始扫描服务 path:" + str(dirPath))
if not os.path.isdir(dirPath):
print("ERROR! 找不到" + str(dirPath) + "文件夹")
return
for filename in os.listdir(str(dirPath)):
print(filename)
if "module" not in filename:
continue
if os.path.isdir(dirPath + "/" + filename):
continue
if str(filename) in "base_module.py":
continue
print(filename)
service_filenames.append(filename)
def load_services():
global service_filenames, commands_list
print("开始加载服务")
for file in service_filenames:
# 分解service
print("加载 " + str(file) + " 中")
# rgb_module.py -> rgb_module
importName = file.replace(".py", "")
m = importlib.import_module("module." + importName)
# rgb_module -> Rgb
class_name = importName.replace("_module", "").capitalize()
klass = getattr(m, class_name)
# 初始化服务类
service = klass()
# 获取命令信息
commandsFunc = getattr(service, "commands")
commands = commandsFunc()
# 获取服务地址
ipPortFunc = getattr(service, "ip_port")
ip_port = ipPortFunc()
# 登记命令和地址
for command in commands:
commands_list.append([command, ip_port])
# 启动服务
startupFunc = getattr(service, "startup")
startupFunc()
print("加载 " + class_name + " 成功")
if __name__ == "__main__":
search_services("./module")
load_services()
print(commands_list)
| {"/module/voice_module.py": ["/module/base_module.py"], "/module/rgb_module.py": ["/module/base_module.py"], "/main.py": ["/module_register.py", "/wake_up.py"], "/wake_up.py": ["/commander.py"], "/module/picture_module.py": ["/module/base_module.py"], "/commander.py": ["/reader.py", "/module_register.py"]} |
60,914 | funyoo/sinny | refs/heads/master | /module/video/video_operator.py | """
video 命令操作者
处理系统命令和用户命令,下达给video_player执行播放
@author: funyoo
"""
from module.video import sys_video_list
from module.video import video_player
import threading
# 命令编号 用于两种唤醒视频交替播放
COMMAND_ID = 0
# 处理命令
def operate(command):
if "command:" in command:
# 系统命令
sysCommand(command)
else:
# 用户命令
userCommand(command)
# 系统命令处理
def sysCommand(command):
sys_command = command.replace("command:", "")
# 睡眠模式
if sys_command == "sleep":
video = sys_video_list.SLEEP_VIDEO
thread = threading.Thread(target=video_player.loopPlay, args=(video[0], video[1]))
thread.start()
# 唤醒模式
if sys_command == "wake_up":
# 两种唤醒模式交替执行
if COMMAND_ID % 2 == 0:
video = sys_video_list.WAKE_UP_VIDEO
thread = threading.Thread(target=video_player.playOnce, args=(video[0], video[1]))
thread.start()
else:
video = sys_video_list.WAKE_UP_VIDEO_2
thread = threading.Thread(target=video_player.playOnce, args=(video[0], video[1]))
thread.start()
# 忙碌模式
if sys_command == "busy":
video = sys_video_list.BUSY_VIDEO
thread = threading.Thread(target=video_player.playOnce, args=(video[0], video[1]))
thread.start()
# 用户命令处理
def userCommand(command):
if "停止" in command:
video = sys_video_list.SLEEP_VIDEO
thread = threading.Thread(target=video_player.loopPlay, args=(video[0], video[1]))
thread.start()
# TODO more and more
| {"/module/voice_module.py": ["/module/base_module.py"], "/module/rgb_module.py": ["/module/base_module.py"], "/main.py": ["/module_register.py", "/wake_up.py"], "/wake_up.py": ["/commander.py"], "/module/picture_module.py": ["/module/base_module.py"], "/commander.py": ["/reader.py", "/module_register.py"]} |
60,915 | funyoo/sinny | refs/heads/master | /module/rgb/rgb_worker.py | """
rgb 工作者
控制rgb灯光的开关
这里用两个标志FLAG和THREAD_EXIT来避免产生大量线程造成的线程泄露
@author: funyoo
"""
from module.rgb import rgb_color
import time
from module.rgb.pixels import Pixels, pixels
from module.rgb.alexa_led_pattern import AlexaLedPattern
from module.rgb.google_home_led_pattern import GoogleHomeLedPattern
import threading
pixels.pattern = GoogleHomeLedPattern(show=pixels.show)
FLAG = False # 亮灯线程正在运行中?
THREAD_EXIT = True # 亮灯线程已退出
# 通过RGB开灯 参数 [255, 255, 255]
def openRgbByRGB(RGB, clock=-1):
global FLAG, THREAD_EXIT
if RGB is None or len(RGB) < 1:
# 无法完成
return
close()
FLAG = True
THREAD_EXIT = False
thread = threading.Thread(target=lightThead, args=(RGB, clock))
thread.start()
# 通过颜色名开灯
def openRgbByName(name, clock=-1):
print("根据 " + name + "开灯")
rgb = rgb_color.getRGBByName(name)
print("取得RGB " + str(rgb))
openRgbByRGB(rgb, clock)
# 关灯
def close():
global FLAG, THREAD_EXIT
# 关闭灯光线程
if FLAG is True:
FLAG = False
while THREAD_EXIT is False:
continue
pixels.off()
# 亮灯线程
def lightThead(RGB, clock=-1):
global FLAG, THREAD_EXIT
while FLAG:
try:
data = RGB * 12
pixels.show(data)
if int(clock) > 0:
time.sleep(int(clock))
pixels.off()
except InterruptedError:
break
THREAD_EXIT = True
# 渐变色特效
def gradualChange():
global FLAG, THREAD_EXIT
close()
r = [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
240, 220, 200, 180, 160, 140, 120, 100, 80, 60, 40, 20, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 20, 40, 60, 80, 100, 120, 140, 160, 180, 200, 220, 240]
g = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 20, 40, 60, 80, 100, 120, 140, 160, 180, 200, 220, 240,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255]
b = [0, 20, 40, 60, 80, 100, 120, 140, 160, 180, 200, 220, 240,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
240, 220, 200, 180, 160, 140, 120, 100, 80, 60, 40, 20, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
index = 0 # 当前渐变下标
direction = 0 # 方向:从小到大
length = len(r)
FLAG = True
THREAD_EXIT = False
while FLAG:
try:
data = [r[index], g[index], b[index]] * 12
pixels.show(data)
time.sleep(0.05)
# 上升方向
if direction == 0:
index += 1
if index == length:
direction = 1
index -= 1
else:
index -= 1
if index == -1:
direction = 0
index += 1
except InterruptedError:
break
THREAD_EXIT = True | {"/module/voice_module.py": ["/module/base_module.py"], "/module/rgb_module.py": ["/module/base_module.py"], "/main.py": ["/module_register.py", "/wake_up.py"], "/wake_up.py": ["/commander.py"], "/module/picture_module.py": ["/module/base_module.py"], "/commander.py": ["/reader.py", "/module_register.py"]} |
60,916 | funyoo/sinny | refs/heads/master | /reader.py | """
reader: 读取者
提供语音识别的方法
readOffLine: 离线识别
readOnLine: 在线识别
@author: funyoo
"""
from aip import AipSpeech
import speech_recognition as sr
# 百度需要的参数
APP_ID = 'xxxxxxxxxx'
API_KEY = 'xxxxxxxxxxxxxxxxxx'
SECRET_KEY = 'xxxxxxxxxxxxxxxxxxxxxxxx'
CLIENT = AipSpeech(APP_ID, API_KEY, SECRET_KEY)
# 离线识别
def readOffLine():
r = sr.Recognizer() #调用识别器
test = sr.AudioFile("command.wav") #导入语音文件
with test as source:
audio = r.record(source)
type(audio)
c = r.recognize_sphinx(audio, language='zh-cn') #识别输出
return c
# 在线识别
def readOnLine():
# 语音转成文字的内容
global CLIENT
ret = CLIENT.asr(get_data("command.wav"), 'wav', 16000, {'dev_pid': 1537}, )
print(ret)
input_message = ret['result']
return input_message[0]
def get_data(file_path):
with open(file_path, 'rb') as fp:
return fp.read()
if __name__ == '__main__':
readOnLine()
| {"/module/voice_module.py": ["/module/base_module.py"], "/module/rgb_module.py": ["/module/base_module.py"], "/main.py": ["/module_register.py", "/wake_up.py"], "/wake_up.py": ["/commander.py"], "/module/picture_module.py": ["/module/base_module.py"], "/commander.py": ["/reader.py", "/module_register.py"]} |
60,917 | funyoo/sinny | refs/heads/master | /commander.py | """
commander 即指挥者,指令处理中心
负责处理和发送指令
@author: funyoo
"""
import socket
import wave
import reader
import pyaudio
import time
import re
import module_register
BUFFSIZE = 1024
# 命令发送客户端
CLIENT = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
CHUNK = 1024
FORMAT = pyaudio.paInt16
CHANNELS = 1
RATE = 16000
RECORD_SECONDS = 3
WAVE_OUTPUT_FILENAME = "command.wav"
# 命令列表
COMMANDS_LIST = module_register.commands_list
# 命令标号,避免一条命令被同一个服务多次执行
COMMAND_ID = 0
def command():
global CLIENT, COMMAND_ID
beforeRecord()
# 录音
record()
# 解析
msg = reader.readOnLine()
print("解析到语音命令:" + msg + " ", time.time())
COMMAND_ID += 1
msg = msg + "-" + str(COMMAND_ID)
# 选择成员下命令
has = False
for soldier in COMMANDS_LIST:
if match(soldier[0], msg):
has = True
CLIENT.sendto(msg.encode("utf-8"), soldier[1])
if has:
CLIENT.sendto("command:hao-0".encode("utf-8"), ("127.0.0.1", 9003))
else:
CLIENT.sendto("command:err-0".encode("utf-8"), ("127.0.0.1", 9003))
def record():
global CLIENT
print("开始录音:", time.time())
p = pyaudio.PyAudio()
stream = p.open(format=FORMAT,
channels=CHANNELS,
rate=RATE,
input=True,
frames_per_buffer=CHUNK)
frames = []
for i in range(0, int(RATE / CHUNK * RECORD_SECONDS)):
data = stream.read(CHUNK)
frames.append(data)
stream.stop_stream()
stream.close()
p.terminate()
wf = wave.open(WAVE_OUTPUT_FILENAME, 'wb')
wf.setnchannels(CHANNELS)
wf.setsampwidth(p.get_sample_size(FORMAT))
wf.setframerate(RATE)
wf.writeframes(b''.join(frames))
wf.close()
print("录音已生成文件 ", time.time())
def close():
global CLIENT
CLIENT.close()
# 正则表达式匹配
def match(pattern, strs):
pattern = re.compile(r'(' + pattern + ')')
m = pattern.match(strs)
return m
# 录音前
def beforeRecord():
CLIENT.sendto("command:3-0".encode("utf-8"), ("127.0.0.1", 9001))
#CLIENT.sendto("command:wake_up-0".encode("utf-8"), ("127.0.0.1", 9002))
CLIENT.sendto("command:wozai-0".encode("utf-8"), ("127.0.0.1", 9003))
if __name__ == '__main__':
module_register.startup()
command()
| {"/module/voice_module.py": ["/module/base_module.py"], "/module/rgb_module.py": ["/module/base_module.py"], "/main.py": ["/module_register.py", "/wake_up.py"], "/wake_up.py": ["/commander.py"], "/module/picture_module.py": ["/module/base_module.py"], "/commander.py": ["/reader.py", "/module_register.py"]} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.