index
int64 | repo_name
string | branch_name
string | path
string | content
string | import_graph
string |
|---|---|---|---|---|---|
16,594,518
|
rav4kumar/openpilot
|
refs/heads/DP08
|
/selfdrive/controls/lib/planner.py
|
#!/usr/bin/env python3
import math
import numpy as np
from common.params import Params
from common.numpy_fast import interp
from datetime import datetime
import time
import cereal.messaging as messaging
from cereal import car
from common.realtime import sec_since_boot
from selfdrive.swaglog import cloudlog
from selfdrive.config import Conversions as CV
from selfdrive.controls.lib.speed_smoother import speed_smoother
from selfdrive.controls.lib.longcontrol import LongCtrlState
from selfdrive.controls.lib.fcw import FCWChecker
from selfdrive.controls.lib.long_mpc import LongitudinalMpc
from selfdrive.controls.lib.drive_helpers import V_CRUISE_MAX
from common.op_params import opParams
op_params = opParams()
osm = op_params.get('osm')
smart_speed = op_params.get('smart_speed')
smart_speed_max_vego = op_params.get('smart_speed_max_vego')
offset_limit = op_params.get('offset_limit')
default_brake_distance = op_params.get('default_brake_distance')
curvature_factor = opParams().get('curvature_factor')
MAX_SPEED = 255.0
NO_CURVATURE_SPEED = 90.0
LON_MPC_STEP = 0.2 # first step is 0.2s
AWARENESS_DECEL = -0.2 # car smoothly decel at .2m/s^2 when user is distracted
# lookup tables VS speed to determine min and max accels in cruise
# make sure these accelerations are smaller than mpc limits
_A_CRUISE_MIN_V = [-1.0, -.8, -.67, -.5, -.30]
_A_CRUISE_MIN_BP = [ 0., 5., 10., 20., 40.]
# need fast accel at very low speed for stop and go
# make sure these accelerations are smaller than mpc limits
_A_CRUISE_MAX_V = [1.2, 1.2, 0.65, .4]
_A_CRUISE_MAX_V_FOLLOWING = [1.6, 1.6, 0.65, .4]
_A_CRUISE_MAX_BP = [0., 6.4, 22.5, 40.]
# Lookup table for turns
_A_TOTAL_MAX_V = [3.5, 4.0, 5.0]
_A_TOTAL_MAX_BP = [0., 25., 55.]
# 75th percentile
SPEED_PERCENTILE_IDX = 7
# dp
DP_OFF = 0
DP_ECO = 1
DP_NORMAL = 2
DP_SPORT = 3
# accel profile by @arne182
_DP_CRUISE_MIN_V = [-2.0, -1.5, -1.0, -0.7, -0.5]
_DP_CRUISE_MIN_V_ECO = [-1.0, -0.7, -0.6, -0.5, -0.3]
_DP_CRUISE_MIN_V_SPORT = [-3.0, -2.6, -2.3, -2.0, -1.0]
_DP_CRUISE_MIN_V_FOLLOWING = [-3.0, -2.5, -2.0, -1.5, -1.0]
_DP_CRUISE_MIN_BP = [0.0, 5.0, 10.0, 20.0, 55.0]
_DP_CRUISE_MAX_V = [2.0, 2.0, 1.5, .5, .3]
_DP_CRUISE_MAX_V_ECO = [0.8, 0.9, 1.0, 0.4, 0.2]
_DP_CRUISE_MAX_V_SPORT = [3.0, 3.5, 3.0, 2.0, 2.0]
_DP_CRUISE_MAX_V_FOLLOWING = [1.6, 1.4, 1.4, .7, .3]
_DP_CRUISE_MAX_BP = [0., 5., 10., 20., 55.]
# Lookup table for turns
_DP_TOTAL_MAX_V = [3.3, 3.0, 3.9]
_DP_TOTAL_MAX_BP = [0., 25., 55.]
def dp_calc_cruise_accel_limits(v_ego, following, dp_profile):
if following:
a_cruise_min = interp(v_ego, _DP_CRUISE_MIN_BP, _DP_CRUISE_MIN_V_FOLLOWING)
a_cruise_max = interp(v_ego, _DP_CRUISE_MAX_BP, _DP_CRUISE_MAX_V_FOLLOWING)
else:
if dp_profile == DP_ECO:
a_cruise_min = interp(v_ego, _DP_CRUISE_MIN_BP, _DP_CRUISE_MIN_V_ECO)
a_cruise_max = interp(v_ego, _DP_CRUISE_MAX_BP, _DP_CRUISE_MAX_V_ECO)
elif dp_profile == DP_SPORT:
a_cruise_min = interp(v_ego, _DP_CRUISE_MIN_BP, _DP_CRUISE_MIN_V_SPORT)
a_cruise_max = interp(v_ego, _DP_CRUISE_MAX_BP, _DP_CRUISE_MAX_V_SPORT)
else:
a_cruise_min = interp(v_ego, _DP_CRUISE_MIN_BP, _DP_CRUISE_MIN_V)
a_cruise_max = interp(v_ego, _DP_CRUISE_MAX_BP, _DP_CRUISE_MAX_V)
return np.vstack([a_cruise_min, a_cruise_max])
def calc_cruise_accel_limits(v_ego, following):
a_cruise_min = interp(v_ego, _A_CRUISE_MIN_BP, _A_CRUISE_MIN_V)
if following:
a_cruise_max = interp(v_ego, _A_CRUISE_MAX_BP, _A_CRUISE_MAX_V_FOLLOWING)
else:
a_cruise_max = interp(v_ego, _A_CRUISE_MAX_BP, _A_CRUISE_MAX_V)
return np.vstack([a_cruise_min, a_cruise_max])
def limit_accel_in_turns(v_ego, angle_steers, a_target, CP):
"""
This function returns a limited long acceleration allowed, depending on the existing lateral acceleration
this should avoid accelerating when losing the target in turns
"""
a_total_max = interp(v_ego, _A_TOTAL_MAX_BP, _A_TOTAL_MAX_V)
a_y = v_ego**2 * angle_steers * CV.DEG_TO_RAD / (CP.steerRatio * CP.wheelbase)
a_x_allowed = math.sqrt(max(a_total_max**2 - a_y**2, 0.))
return [a_target[0], min(a_target[1], a_x_allowed)]
class Planner():
def __init__(self, CP):
self.CP = CP
self.mpc1 = LongitudinalMpc(1)
self.mpc2 = LongitudinalMpc(2)
self.v_acc_start = 0.0
self.a_acc_start = 0.0
self.v_acc = 0.0
self.v_acc_future = 0.0
self.a_acc = 0.0
self.v_cruise = 0.0
self.a_cruise = 0.0
self.osm = True
self.longitudinalPlanSource = 'cruise'
self.fcw_checker = FCWChecker()
self.path_x = np.arange(192)
self.params = Params()
self.first_loop = True
self.offset = 0
self.last_time = 0
# dp
self.dp_profile = DP_OFF
# dp - slow on curve from 0.7.6.1
self.dp_slow_on_curve = False
self.v_model = 0.0
self.a_model = 0.0
def choose_solution(self, v_cruise_setpoint, enabled, lead_1, lead_2, steeringAngle):
center_x = -2.5 # Wheel base 2.5m
lead1_check = True
lead2_check = True
if steeringAngle > 100: # only at high angles
center_y = -1+2.5/math.tan(steeringAngle/1800.*math.pi) # Car Width 2m. Left side considered in left hand turn
lead1_check = math.sqrt((lead_1.dRel-center_x)**2+(lead_1.yRel-center_y)**2) < abs(2.5/math.sin(steeringAngle/1800.*math.pi))+1. # extra meter clearance to car
lead2_check = math.sqrt((lead_2.dRel-center_x)**2+(lead_2.yRel-center_y)**2) < abs(2.5/math.sin(steeringAngle/1800.*math.pi))+1.
elif steeringAngle < -100: # only at high angles
center_y = +1+2.5/math.tan(steeringAngle/1800.*math.pi) # Car Width 2m. Right side considered in right hand turn
lead1_check = math.sqrt((lead_1.dRel-center_x)**2+(lead_1.yRel-center_y)**2) < abs(2.5/math.sin(steeringAngle/1800.*math.pi))+1.
lead2_check = math.sqrt((lead_2.dRel-center_x)**2+(lead_2.yRel-center_y)**2) < abs(2.5/math.sin(steeringAngle/1800.*math.pi))+1.
if enabled:
# dp - slow on curve from 0.7.6.1
if self.dp_slow_on_curve:
solutions = {'model': self.v_model, 'cruise': self.v_cruise}
else:
solutions = {'cruise': self.v_cruise}
if self.mpc1.prev_lead_status and lead1_check:
solutions['mpc1'] = self.mpc1.v_mpc
if self.mpc2.prev_lead_status and lead2_check:
solutions['mpc2'] = self.mpc2.v_mpc
slowest = min(solutions, key=solutions.get)
self.longitudinalPlanSource = slowest
# Choose lowest of MPC and cruise
if slowest == 'mpc1':
self.v_acc = self.mpc1.v_mpc
self.a_acc = self.mpc1.a_mpc
elif slowest == 'mpc2':
self.v_acc = self.mpc2.v_mpc
self.a_acc = self.mpc2.a_mpc
elif slowest == 'cruise':
self.v_acc = self.v_cruise
self.a_acc = self.a_cruise
# dp - slow on curve from 0.7.6.1
elif self.dp_slow_on_curve and slowest == 'model':
self.v_acc = self.v_model
self.a_acc = self.a_model
self.v_acc_future = v_cruise_setpoint
if lead1_check:
self.v_acc_future = min([self.mpc1.v_mpc_future, self.v_acc_future])
if lead2_check:
self.v_acc_future = min([self.mpc2.v_mpc_future, self.v_acc_future])
def update(self, sm, pm, CP, VM, PP):
"""Gets called when new radarState is available"""
cur_time = sec_since_boot()
v_ego = sm['carState'].vEgo
# we read offset value every 5 seconds
fixed_offset = 0.0
fixed_offset = op_params.get('speed_offset')
if self.last_time > 5:
try:
self.offset = int(self.params.get("SpeedLimitOffset", encoding='utf8'))
except (TypeError,ValueError):
self.params.delete("SpeedLimitOffset")
self.offset = 0
self.osm = self.params.get("LimitSetSpeed", encoding='utf8') == "1"
self.last_time = 0
self.last_time = self.last_time + 1
long_control_state = sm['controlsState'].longControlState
v_cruise_kph = sm['controlsState'].vCruise
force_slow_decel = sm['controlsState'].forceDecel
v_cruise_kph = min(v_cruise_kph, V_CRUISE_MAX)
v_cruise_setpoint = v_cruise_kph * CV.KPH_TO_MS
lead_1 = sm['radarState'].leadOne
lead_2 = sm['radarState'].leadTwo
enabled = (long_control_state == LongCtrlState.pid) or (long_control_state == LongCtrlState.stopping)
following = (lead_1.status and lead_1.dRel < 45.0 and lead_1.vRel < 0.0) or (lead_2.status and lead_2.dRel < 45.0 and lead_2.vRel < 0.0) #lead_1.status and lead_1.dRel < 45.0 and lead_1.vLeadK > v_ego and lead_1.aLeadK > 0.0
speed_ahead_distance = default_brake_distance
v_speedlimit = NO_CURVATURE_SPEED
v_curvature_map = NO_CURVATURE_SPEED
v_speedlimit_ahead = NO_CURVATURE_SPEED
now = datetime.now()
try:
if sm['liveMapData'].speedLimitValid and osm and self.osm and (sm['liveMapData'].lastGps.timestamp -time.mktime(now.timetuple()) * 1000) < 10000 and (smart_speed or smart_speed_max_vego > v_ego):
speed_limit = sm['liveMapData'].speedLimit
if speed_limit is not None:
v_speedlimit = speed_limit
# offset is in percentage,.
if v_ego > offset_limit:
v_speedlimit = v_speedlimit * (1. + self.offset/100.0)
if v_speedlimit > fixed_offset:
v_speedlimit = v_speedlimit + fixed_offset
else:
speed_limit = None
if sm['liveMapData'].speedLimitAheadValid and osm and self.osm and sm['liveMapData'].speedLimitAheadDistance < speed_ahead_distance and (sm['liveMapData'].lastGps.timestamp -time.mktime(now.timetuple()) * 1000) < 10000 and (smart_speed or smart_speed_max_vego > v_ego): # noqa: E501
distanceatlowlimit = 50
if sm['liveMapData'].speedLimitAhead < 21/3.6:
distanceatlowlimit = speed_ahead_distance = (v_ego - sm['liveMapData'].speedLimitAhead)*3.6*2
if distanceatlowlimit < 50:
distanceatlowlimit = 0
distanceatlowlimit = min(distanceatlowlimit,100)
speed_ahead_distance = (v_ego - sm['liveMapData'].speedLimitAhead)*3.6*5
speed_ahead_distance = min(speed_ahead_distance,300)
speed_ahead_distance = max(speed_ahead_distance,50)
if speed_limit is not None and sm['liveMapData'].speedLimitAheadDistance > distanceatlowlimit and v_ego + 3 < sm['liveMapData'].speedLimitAhead + (speed_limit - sm['liveMapData'].speedLimitAhead)*sm['liveMapData'].speedLimitAheadDistance/speed_ahead_distance: # noqa: E501
speed_limit_ahead = sm['liveMapData'].speedLimitAhead + (speed_limit - sm['liveMapData'].speedLimitAhead)*(sm['liveMapData'].speedLimitAheadDistance - distanceatlowlimit)/(speed_ahead_distance - distanceatlowlimit)
else:
speed_limit_ahead = sm['liveMapData'].speedLimitAhead
if speed_limit_ahead is not None:
v_speedlimit_ahead = speed_limit_ahead
if v_ego > offset_limit:
v_speedlimit_ahead = v_speedlimit_ahead * (1. + self.offset/100.0)
if v_speedlimit_ahead > fixed_offset:
v_speedlimit_ahead = v_speedlimit_ahead + fixed_offset
if sm['liveMapData'].curvatureValid and sm['liveMapData'].distToTurn < speed_ahead_distance and osm and self.osm and (sm['liveMapData'].lastGps.timestamp -time.mktime(now.timetuple()) * 1000) < 10000:
curvature = abs(sm['liveMapData'].curvature)
radius = 1/max(1e-4, curvature) * curvature_factor
radius = radius * 1.5
if radius > 500:
c=0.9 # 0.9 at 1000m = 108 kph
elif radius > 250:
c = 3.5-13/2500*radius # 2.2 at 250m 84 kph
else:
c= 3.0 - 2/625 *radius # 3.0 at 15m 24 kph
v_curvature_map = math.sqrt(c*radius)
v_curvature_map = min(NO_CURVATURE_SPEED, v_curvature_map)
except KeyError:
pass
decel_for_turn = bool(v_curvature_map < min([v_cruise_setpoint, v_speedlimit, v_ego + 1.]))
# dp
self.dp_profile = sm['dragonConf'].dpAccelProfile
self.dp_slow_on_curve = sm['dragonConf'].dpSlowOnCurve
# dp - slow on curve from 0.7.6.1
if self.dp_slow_on_curve and len(sm['model'].path.poly):
path = list(sm['model'].path.poly)
# Curvature of polynomial https://en.wikipedia.org/wiki/Curvature#Curvature_of_the_graph_of_a_function
# y = a x^3 + b x^2 + c x + d, y' = 3 a x^2 + 2 b x + c, y'' = 6 a x + 2 b
# k = y'' / (1 + y'^2)^1.5
# TODO: compute max speed without using a list of points and without numpy
y_p = 3 * path[0] * self.path_x**2 + 2 * path[1] * self.path_x + path[2]
y_pp = 6 * path[0] * self.path_x + 2 * path[1]
curv = y_pp / (1. + y_p**2)**1.5
a_y_max = 2.975 - v_ego * 0.0375 # ~1.85 @ 75mph, ~2.6 @ 25mph
v_curvature = np.sqrt(a_y_max / np.clip(np.abs(curv), 1e-4, None))
model_speed = np.min(v_curvature)
model_speed = max(20.0 * CV.MPH_TO_MS, model_speed) # Don't slow down below 20mph
else:
model_speed = MAX_SPEED
# Calculate speed for normal cruise control
pedal_pressed = sm['carState'].gasPressed or sm['carState'].brakePressed
if enabled and not self.first_loop and not pedal_pressed:
if self.dp_profile == DP_OFF:
accel_limits = [float(x) for x in calc_cruise_accel_limits(v_ego, following)]
else:
accel_limits = [float(x) for x in dp_calc_cruise_accel_limits(v_ego, following, self.dp_profile and (self.longitudinalPlanSource == 'mpc1' or self.longitudinalPlanSource == 'mpc2'))]
jerk_limits = [min(-0.1, accel_limits[0]), max(0.1, accel_limits[1])] # TODO: make a separate lookup for jerk tuning
accel_limits_turns = limit_accel_in_turns(v_ego, sm['carState'].steeringAngle, accel_limits, self.CP)
if force_slow_decel:
# if required so, force a smooth deceleration
accel_limits_turns[1] = min(accel_limits_turns[1], AWARENESS_DECEL)
accel_limits_turns[0] = min(accel_limits_turns[0], accel_limits_turns[1])
if decel_for_turn and sm['liveMapData'].distToTurn < speed_ahead_distance and not following:
time_to_turn = max(1.0, sm['liveMapData'].distToTurn / max((v_ego + v_curvature_map)/2, 1.))
required_decel = min(0, (v_curvature_map - v_ego) / time_to_turn)
accel_limits[0] = max(accel_limits[0], required_decel)
if v_speedlimit_ahead < v_speedlimit and v_ego > v_speedlimit_ahead and sm['liveMapData'].speedLimitAheadDistance > 1.0 and not following:
required_decel = min(0, (v_speedlimit_ahead*v_speedlimit_ahead - v_ego*v_ego)/(sm['liveMapData'].speedLimitAheadDistance*2))
required_decel = max(required_decel, -3.0)
decel_for_turn = True
accel_limits[0] = required_decel
accel_limits[1] = required_decel
self.a_acc_start = required_decel
v_speedlimit_ahead = v_ego
v_cruise_setpoint = min([v_cruise_setpoint, v_curvature_map, v_speedlimit, v_speedlimit_ahead])
self.v_cruise, self.a_cruise = speed_smoother(self.v_acc_start, self.a_acc_start,
v_cruise_setpoint,
accel_limits_turns[1], accel_limits_turns[0],
jerk_limits[1], jerk_limits[0],
LON_MPC_STEP)
# dp - slow on curve from 0.7.6.1
if self.dp_slow_on_curve:
self.v_model, self.a_model = speed_smoother(self.v_acc_start, self.a_acc_start,
model_speed, 2*accel_limits[1],
accel_limits[0], 2*jerk_limits[1], jerk_limits[0],
LON_MPC_STEP)
# cruise speed can't be negative even is user is distracted
self.v_cruise = max(self.v_cruise, 0.)
else:
starting = long_control_state == LongCtrlState.starting
a_ego = min(sm['carState'].aEgo, 0.0)
reset_speed = self.CP.minSpeedCan if starting else v_ego
reset_accel = self.CP.startAccel if starting else a_ego
self.v_acc = reset_speed
self.a_acc = reset_accel
self.v_acc_start = reset_speed
self.a_acc_start = reset_accel
self.v_cruise = reset_speed
self.a_cruise = reset_accel
self.mpc1.set_cur_state(self.v_acc_start, self.a_acc_start)
self.mpc2.set_cur_state(self.v_acc_start, self.a_acc_start)
self.mpc1.update(pm, sm['carState'], lead_1)
self.mpc2.update(pm, sm['carState'], lead_2)
self.choose_solution(v_cruise_setpoint, enabled, lead_1, lead_2, sm['carState'].steeringAngle)
# determine fcw
if self.mpc1.new_lead:
self.fcw_checker.reset_lead(cur_time)
blinkers = sm['carState'].leftBlinker or sm['carState'].rightBlinker
fcw = self.fcw_checker.update(self.mpc1.mpc_solution, cur_time,
sm['controlsState'].active,
v_ego, sm['carState'].aEgo,
lead_1.dRel, lead_1.vLead, lead_1.aLeadK,
lead_1.yRel, lead_1.vLat,
lead_1.fcw, blinkers) and not sm['carState'].brakePressed
if fcw:
cloudlog.info("FCW triggered %s", self.fcw_checker.counters)
radar_dead = not sm.alive['radarState']
radar_errors = list(sm['radarState'].radarErrors)
radar_fault = car.RadarData.Error.fault in radar_errors
radar_can_error = car.RadarData.Error.canError in radar_errors
# **** send the plan ****
plan_send = messaging.new_message('plan')
plan_send.valid = sm.all_alive_and_valid(service_list=['carState', 'controlsState', 'radarState'])
plan_send.plan.mdMonoTime = sm.logMonoTime['model']
plan_send.plan.radarStateMonoTime = sm.logMonoTime['radarState']
# longitudal plan
plan_send.plan.vCruise = float(self.v_cruise)
plan_send.plan.aCruise = float(self.a_cruise)
plan_send.plan.vStart = float(self.v_acc_start)
plan_send.plan.aStart = float(self.a_acc_start)
plan_send.plan.vTarget = float(self.v_acc)
plan_send.plan.aTarget = float(self.a_acc)
plan_send.plan.vTargetFuture = float(self.v_acc_future)
plan_send.plan.hasLead = self.mpc1.prev_lead_status
plan_send.plan.longitudinalPlanSource = self.longitudinalPlanSource
plan_send.plan.vCurvature = float(v_curvature_map)
plan_send.plan.decelForTurn = bool(decel_for_turn)
plan_send.plan.mapValid = True
radar_valid = not (radar_dead or radar_fault)
plan_send.plan.radarValid = bool(radar_valid)
plan_send.plan.radarCanError = bool(radar_can_error)
plan_send.plan.processingDelay = (plan_send.logMonoTime / 1e9) - sm.rcv_time['radarState']
# Send out fcw
plan_send.plan.fcw = fcw
pm.send('plan', plan_send)
# Interpolate 0.05 seconds and save as starting point for next iteration
a_acc_sol = self.a_acc_start + (CP.radarTimeStep / LON_MPC_STEP) * (self.a_acc - self.a_acc_start)
v_acc_sol = self.v_acc_start + CP.radarTimeStep * (a_acc_sol + self.a_acc_start) / 2.0
self.v_acc_start = v_acc_sol
self.a_acc_start = a_acc_sol
self.first_loop = False
|
{"/selfdrive/debug/internal/sounds/test_sounds.py": ["/common/basedir.py"], "/selfdrive/debug/internal/sounds/test_sound_stability.py": ["/common/basedir.py"], "/selfdrive/test/process_replay/model_replay.py": ["/tools/lib/logreader.py"], "/selfdrive/controls/lib/dynamic_follow/__init__.py": ["/common/params.py", "/common/dp_time.py", "/common/dp_common.py", "/selfdrive/controls/lib/dynamic_follow/auto_df.py", "/selfdrive/controls/lib/dynamic_follow/support.py"], "/selfdrive/test/test_cpu_usage.py": ["/common/basedir.py", "/common/params.py"], "/common/i18n.py": ["/common/hardware.py"], "/laika_repo/tests/test_fetch_sat_info.py": ["/laika/__init__.py"], "/common/hardware.py": ["/common/hardware_tici.py", "/common/hardware_base.py"], "/selfdrive/interbridge/interbridged.py": ["/selfdrive/interbridge/unisocket.py"], "/common/dp_common.py": ["/common/params.py", "/common/travis_checker.py"], "/tools/carcontrols/debug_controls.py": ["/common/params.py"], "/common/op_params.py": ["/common/travis_checker.py", "/common/colors.py"], "/laika_repo/laika/astro_dog.py": ["/laika_repo/laika/helpers.py", "/laika_repo/laika/downloader.py"], "/laika_repo/tests/test_positioning.py": ["/laika/__init__.py", "/laika/downloader.py"], "/selfdrive/test/test_openpilot.py": ["/common/params.py"], "/tools/replay/camera.py": ["/common/basedir.py"], "/common/hardware_tici.py": ["/common/hardware_base.py"], "/laika_repo/laika/raw_gnss.py": ["/laika_repo/laika/helpers.py"], "/selfdrive/test/process_replay/update_model.py": ["/tools/lib/logreader.py", "/selfdrive/test/process_replay/inject_model.py"], "/selfdrive/car/volkswagen/carstate.py": ["/selfdrive/car/volkswagen/values.py"], "/selfdrive/controls/lib/dynamic_follow/auto_df.py": ["/common/travis_checker.py"], "/selfdrive/test/process_replay/camera_replay.py": ["/common/hardware.py", "/tools/lib/logreader.py"], "/selfdrive/data_collection/gps_uploader.py": ["/common/params.py", "/common/op_params.py"], "/common/travis_checker.py": ["/common/basedir.py"], "/tools/replay/sensorium.py": ["/tools/replay/lib/ui_helpers.py"], "/tools/replay/unlogger.py": ["/tools/lib/logreader.py", "/tools/lib/route_framereader.py"], "/selfdrive/dragonpilot/appd.py": ["/common/params.py", "/common/dp_conf.py"], "/selfdrive/crash.py": ["/common/params.py", "/common/hardware.py", "/common/op_params.py"], "/laika_repo/tests/test_ephemerides.py": ["/laika/__init__.py"], "/selfdrive/test/testing_closet_client.py": ["/common/params.py"], "/selfdrive/test/model_replay.py": ["/tools/lib/logreader.py", "/selfdrive/test/process_replay/camera_replay.py"], "/tools/webcam/accept_terms.py": ["/common/params.py"], "/laika/astro_dog.py": ["/laika/helpers.py", "/laika/downloader.py", "/laika/__init__.py"], "/selfdrive/mapd/mapd.py": ["/selfdrive/crash.py", "/common/params.py"], "/selfdrive/dragonpilot/systemd.py": ["/common/dp_conf.py", "/common/params.py", "/common/i18n.py", "/common/dp_common.py", "/common/dp_time.py", "/selfdrive/dragonpilot/dashcam.py", "/common/travis_checker.py"], "/op_edit.py": ["/common/op_params.py", "/common/colors.py"], "/selfdrive/test/profiling/profiler.py": ["/common/params.py", "/tools/lib/logreader.py"], "/selfdrive/controls/lib/planner.py": ["/common/params.py", "/common/op_params.py"], "/common/basedir.py": ["/common/hardware.py"], "/selfdrive/car/toyota/carstate.py": ["/common/params.py", "/common/travis_checker.py", "/common/op_params.py"], "/laika_repo/tests/test_prns.py": ["/laika/helpers.py"], "/selfdrive/golden/can_bridge.py": ["/common/params.py"]}
|
16,594,519
|
rav4kumar/openpilot
|
refs/heads/DP08
|
/tools/lib/logreader.py
|
#!/usr/bin/env python3
import os
import sys
import bz2
import tempfile
import subprocess
import urllib.parse
import capnp
import numpy as np
from tools.lib.exceptions import DataUnreadableError
try:
from xx.chffr.lib.filereader import FileReader
except ImportError:
from tools.lib.filereader import FileReader
from cereal import log as capnp_log
OP_PATH = os.path.dirname(os.path.dirname(capnp_log.__file__))
def index_log(fn):
index_log_dir = os.path.join(os.path.dirname(os.path.realpath(__file__)), "index_log")
index_log = os.path.join(index_log_dir, "index_log")
if not os.path.exists(index_log):
phonelibs_dir = os.path.join(OP_PATH, 'phonelibs')
subprocess.check_call(["make", "PHONELIBS=" + phonelibs_dir], cwd=index_log_dir, stdout=subprocess.DEVNULL)
try:
dat = subprocess.check_output([index_log, fn, "-"])
except subprocess.CalledProcessError as e:
raise DataUnreadableError("%s capnp is corrupted/truncated" % fn) from e
return np.frombuffer(dat, dtype=np.uint64)
def event_read_multiple_bytes(dat):
with tempfile.NamedTemporaryFile() as dat_f:
dat_f.write(dat)
dat_f.flush()
idx = index_log(dat_f.name)
end_idx = np.uint64(len(dat))
idx = np.append(idx, end_idx)
return [capnp_log.Event.from_bytes(dat[idx[i]:idx[i+1]])
for i in range(len(idx)-1)]
# this is an iterator itself, and uses private variables from LogReader
class MultiLogIterator(object):
def __init__(self, log_paths, wraparound=True):
self._log_paths = log_paths
self._wraparound = wraparound
self._first_log_idx = next(i for i in range(len(log_paths)) if log_paths[i] is not None)
self._current_log = self._first_log_idx
self._idx = 0
self._log_readers = [None]*len(log_paths)
self.start_time = self._log_reader(self._first_log_idx)._ts[0]
def _log_reader(self, i):
if self._log_readers[i] is None and self._log_paths[i] is not None:
log_path = self._log_paths[i]
print("LogReader:%s" % log_path)
self._log_readers[i] = LogReader(log_path)
return self._log_readers[i]
def __iter__(self):
return self
def _inc(self):
lr = self._log_reader(self._current_log)
if self._idx < len(lr._ents)-1:
self._idx += 1
else:
self._idx = 0
self._current_log = next(i for i in range(self._current_log + 1, len(self._log_readers) + 1)
if i == len(self._log_readers) or self._log_paths[i] is not None)
# wraparound
if self._current_log == len(self._log_readers):
if self._wraparound:
self._current_log = self._first_log_idx
else:
raise StopIteration
def __next__(self):
while 1:
lr = self._log_reader(self._current_log)
ret = lr._ents[self._idx]
self._inc()
return ret
def tell(self):
# returns seconds from start of log
return (self._log_reader(self._current_log)._ts[self._idx] - self.start_time) * 1e-9
def seek(self, ts):
# seek to nearest minute
minute = int(ts/60)
if minute >= len(self._log_paths) or self._log_paths[minute] is None:
return False
self._current_log = minute
# HACK: O(n) seek afterward
self._idx = 0
while self.tell() < ts:
self._inc()
return True
class LogReader(object):
def __init__(self, fn, canonicalize=True, only_union_types=False):
data_version = None
_, ext = os.path.splitext(urllib.parse.urlparse(fn).path)
with FileReader(fn) as f:
dat = f.read()
if ext == "":
# old rlogs weren't bz2 compressed
ents = event_read_multiple_bytes(dat)
elif ext == ".bz2":
dat = bz2.decompress(dat)
ents = event_read_multiple_bytes(dat)
else:
raise Exception(f"unknown extension {ext}")
self._ts = [x.logMonoTime for x in ents]
self.data_version = data_version
self._only_union_types = only_union_types
self._ents = ents
def __iter__(self):
for ent in self._ents:
if self._only_union_types:
try:
ent.which()
yield ent
except capnp.lib.capnp.KjException:
pass
else:
yield ent
if __name__ == "__main__":
log_path = sys.argv[1]
lr = LogReader(log_path)
for msg in lr:
print(msg)
|
{"/selfdrive/debug/internal/sounds/test_sounds.py": ["/common/basedir.py"], "/selfdrive/debug/internal/sounds/test_sound_stability.py": ["/common/basedir.py"], "/selfdrive/test/process_replay/model_replay.py": ["/tools/lib/logreader.py"], "/selfdrive/controls/lib/dynamic_follow/__init__.py": ["/common/params.py", "/common/dp_time.py", "/common/dp_common.py", "/selfdrive/controls/lib/dynamic_follow/auto_df.py", "/selfdrive/controls/lib/dynamic_follow/support.py"], "/selfdrive/test/test_cpu_usage.py": ["/common/basedir.py", "/common/params.py"], "/common/i18n.py": ["/common/hardware.py"], "/laika_repo/tests/test_fetch_sat_info.py": ["/laika/__init__.py"], "/common/hardware.py": ["/common/hardware_tici.py", "/common/hardware_base.py"], "/selfdrive/interbridge/interbridged.py": ["/selfdrive/interbridge/unisocket.py"], "/common/dp_common.py": ["/common/params.py", "/common/travis_checker.py"], "/tools/carcontrols/debug_controls.py": ["/common/params.py"], "/common/op_params.py": ["/common/travis_checker.py", "/common/colors.py"], "/laika_repo/laika/astro_dog.py": ["/laika_repo/laika/helpers.py", "/laika_repo/laika/downloader.py"], "/laika_repo/tests/test_positioning.py": ["/laika/__init__.py", "/laika/downloader.py"], "/selfdrive/test/test_openpilot.py": ["/common/params.py"], "/tools/replay/camera.py": ["/common/basedir.py"], "/common/hardware_tici.py": ["/common/hardware_base.py"], "/laika_repo/laika/raw_gnss.py": ["/laika_repo/laika/helpers.py"], "/selfdrive/test/process_replay/update_model.py": ["/tools/lib/logreader.py", "/selfdrive/test/process_replay/inject_model.py"], "/selfdrive/car/volkswagen/carstate.py": ["/selfdrive/car/volkswagen/values.py"], "/selfdrive/controls/lib/dynamic_follow/auto_df.py": ["/common/travis_checker.py"], "/selfdrive/test/process_replay/camera_replay.py": ["/common/hardware.py", "/tools/lib/logreader.py"], "/selfdrive/data_collection/gps_uploader.py": ["/common/params.py", "/common/op_params.py"], "/common/travis_checker.py": ["/common/basedir.py"], "/tools/replay/sensorium.py": ["/tools/replay/lib/ui_helpers.py"], "/tools/replay/unlogger.py": ["/tools/lib/logreader.py", "/tools/lib/route_framereader.py"], "/selfdrive/dragonpilot/appd.py": ["/common/params.py", "/common/dp_conf.py"], "/selfdrive/crash.py": ["/common/params.py", "/common/hardware.py", "/common/op_params.py"], "/laika_repo/tests/test_ephemerides.py": ["/laika/__init__.py"], "/selfdrive/test/testing_closet_client.py": ["/common/params.py"], "/selfdrive/test/model_replay.py": ["/tools/lib/logreader.py", "/selfdrive/test/process_replay/camera_replay.py"], "/tools/webcam/accept_terms.py": ["/common/params.py"], "/laika/astro_dog.py": ["/laika/helpers.py", "/laika/downloader.py", "/laika/__init__.py"], "/selfdrive/mapd/mapd.py": ["/selfdrive/crash.py", "/common/params.py"], "/selfdrive/dragonpilot/systemd.py": ["/common/dp_conf.py", "/common/params.py", "/common/i18n.py", "/common/dp_common.py", "/common/dp_time.py", "/selfdrive/dragonpilot/dashcam.py", "/common/travis_checker.py"], "/op_edit.py": ["/common/op_params.py", "/common/colors.py"], "/selfdrive/test/profiling/profiler.py": ["/common/params.py", "/tools/lib/logreader.py"], "/selfdrive/controls/lib/planner.py": ["/common/params.py", "/common/op_params.py"], "/common/basedir.py": ["/common/hardware.py"], "/selfdrive/car/toyota/carstate.py": ["/common/params.py", "/common/travis_checker.py", "/common/op_params.py"], "/laika_repo/tests/test_prns.py": ["/laika/helpers.py"], "/selfdrive/golden/can_bridge.py": ["/common/params.py"]}
|
16,594,520
|
rav4kumar/openpilot
|
refs/heads/DP08
|
/tools/lib/auth.py
|
#!/usr/bin/env python3
import sys
import webbrowser
from http.server import HTTPServer, BaseHTTPRequestHandler
from urllib.parse import urlencode, parse_qs
from tools.lib.api import CommaApi, APIError
from tools.lib.auth_config import set_token
from typing import Dict, Any
class ClientRedirectServer(HTTPServer):
query_params: Dict[str, Any] = {}
class ClientRedirectHandler(BaseHTTPRequestHandler):
def do_GET(self):
if not self.path.startswith('/auth_redirect'):
self.send_response(204)
return
query = self.path.split('?', 1)[-1]
query = parse_qs(query, keep_blank_values=True)
self.server.query_params = query
self.send_response(200)
self.send_header('Content-type', 'text/plain')
self.end_headers()
self.wfile.write(b'Return to the CLI to continue')
def log_message(self, format, *args): # pylint: disable=redefined-builtin
pass # this prevent http server from dumping messages to stdout
def auth_redirect_link(port):
redirect_uri = f'http://localhost:{port}/auth_redirect'
params = {
'type': 'web_server',
'client_id': '45471411055-ornt4svd2miog6dnopve7qtmh5mnu6id.apps.googleusercontent.com',
'redirect_uri': redirect_uri,
'response_type': 'code',
'scope': 'https://www.googleapis.com/auth/userinfo.email',
'prompt': 'select_account',
}
return (redirect_uri, 'https://accounts.google.com/o/oauth2/auth?' + urlencode(params))
def login():
port = 9090
redirect_uri, oauth_uri = auth_redirect_link(port)
web_server = ClientRedirectServer(('localhost', port), ClientRedirectHandler)
print(f'To sign in, use your browser and navigate to {oauth_uri}')
webbrowser.open(oauth_uri, new=2)
while True:
web_server.handle_request()
if 'code' in web_server.query_params:
code = web_server.query_params['code']
break
elif 'error' in web_server.query_params:
print('Authentication Error: "%s". Description: "%s" ' % (
web_server.query_params['error'],
web_server.query_params.get('error_description')), file=sys.stderr)
break
try:
auth_resp = CommaApi().post('v2/auth/', data={'code': code, 'redirect_uri': redirect_uri})
set_token(auth_resp['access_token'])
print('Authenticated')
except APIError as e:
print(f'Authentication Error: {e}', file=sys.stderr)
if __name__ == '__main__':
login()
|
{"/selfdrive/debug/internal/sounds/test_sounds.py": ["/common/basedir.py"], "/selfdrive/debug/internal/sounds/test_sound_stability.py": ["/common/basedir.py"], "/selfdrive/test/process_replay/model_replay.py": ["/tools/lib/logreader.py"], "/selfdrive/controls/lib/dynamic_follow/__init__.py": ["/common/params.py", "/common/dp_time.py", "/common/dp_common.py", "/selfdrive/controls/lib/dynamic_follow/auto_df.py", "/selfdrive/controls/lib/dynamic_follow/support.py"], "/selfdrive/test/test_cpu_usage.py": ["/common/basedir.py", "/common/params.py"], "/common/i18n.py": ["/common/hardware.py"], "/laika_repo/tests/test_fetch_sat_info.py": ["/laika/__init__.py"], "/common/hardware.py": ["/common/hardware_tici.py", "/common/hardware_base.py"], "/selfdrive/interbridge/interbridged.py": ["/selfdrive/interbridge/unisocket.py"], "/common/dp_common.py": ["/common/params.py", "/common/travis_checker.py"], "/tools/carcontrols/debug_controls.py": ["/common/params.py"], "/common/op_params.py": ["/common/travis_checker.py", "/common/colors.py"], "/laika_repo/laika/astro_dog.py": ["/laika_repo/laika/helpers.py", "/laika_repo/laika/downloader.py"], "/laika_repo/tests/test_positioning.py": ["/laika/__init__.py", "/laika/downloader.py"], "/selfdrive/test/test_openpilot.py": ["/common/params.py"], "/tools/replay/camera.py": ["/common/basedir.py"], "/common/hardware_tici.py": ["/common/hardware_base.py"], "/laika_repo/laika/raw_gnss.py": ["/laika_repo/laika/helpers.py"], "/selfdrive/test/process_replay/update_model.py": ["/tools/lib/logreader.py", "/selfdrive/test/process_replay/inject_model.py"], "/selfdrive/car/volkswagen/carstate.py": ["/selfdrive/car/volkswagen/values.py"], "/selfdrive/controls/lib/dynamic_follow/auto_df.py": ["/common/travis_checker.py"], "/selfdrive/test/process_replay/camera_replay.py": ["/common/hardware.py", "/tools/lib/logreader.py"], "/selfdrive/data_collection/gps_uploader.py": ["/common/params.py", "/common/op_params.py"], "/common/travis_checker.py": ["/common/basedir.py"], "/tools/replay/sensorium.py": ["/tools/replay/lib/ui_helpers.py"], "/tools/replay/unlogger.py": ["/tools/lib/logreader.py", "/tools/lib/route_framereader.py"], "/selfdrive/dragonpilot/appd.py": ["/common/params.py", "/common/dp_conf.py"], "/selfdrive/crash.py": ["/common/params.py", "/common/hardware.py", "/common/op_params.py"], "/laika_repo/tests/test_ephemerides.py": ["/laika/__init__.py"], "/selfdrive/test/testing_closet_client.py": ["/common/params.py"], "/selfdrive/test/model_replay.py": ["/tools/lib/logreader.py", "/selfdrive/test/process_replay/camera_replay.py"], "/tools/webcam/accept_terms.py": ["/common/params.py"], "/laika/astro_dog.py": ["/laika/helpers.py", "/laika/downloader.py", "/laika/__init__.py"], "/selfdrive/mapd/mapd.py": ["/selfdrive/crash.py", "/common/params.py"], "/selfdrive/dragonpilot/systemd.py": ["/common/dp_conf.py", "/common/params.py", "/common/i18n.py", "/common/dp_common.py", "/common/dp_time.py", "/selfdrive/dragonpilot/dashcam.py", "/common/travis_checker.py"], "/op_edit.py": ["/common/op_params.py", "/common/colors.py"], "/selfdrive/test/profiling/profiler.py": ["/common/params.py", "/tools/lib/logreader.py"], "/selfdrive/controls/lib/planner.py": ["/common/params.py", "/common/op_params.py"], "/common/basedir.py": ["/common/hardware.py"], "/selfdrive/car/toyota/carstate.py": ["/common/params.py", "/common/travis_checker.py", "/common/op_params.py"], "/laika_repo/tests/test_prns.py": ["/laika/helpers.py"], "/selfdrive/golden/can_bridge.py": ["/common/params.py"]}
|
16,594,521
|
rav4kumar/openpilot
|
refs/heads/DP08
|
/common/basedir.py
|
import os
BASEDIR = os.path.abspath(os.path.join(os.path.dirname(os.path.realpath(__file__)), "../"))
from common.hardware import PC
if PC:
PERSIST = os.path.join(BASEDIR, "persist")
else:
PERSIST = "/persist"
|
{"/selfdrive/debug/internal/sounds/test_sounds.py": ["/common/basedir.py"], "/selfdrive/debug/internal/sounds/test_sound_stability.py": ["/common/basedir.py"], "/selfdrive/test/process_replay/model_replay.py": ["/tools/lib/logreader.py"], "/selfdrive/controls/lib/dynamic_follow/__init__.py": ["/common/params.py", "/common/dp_time.py", "/common/dp_common.py", "/selfdrive/controls/lib/dynamic_follow/auto_df.py", "/selfdrive/controls/lib/dynamic_follow/support.py"], "/selfdrive/test/test_cpu_usage.py": ["/common/basedir.py", "/common/params.py"], "/common/i18n.py": ["/common/hardware.py"], "/laika_repo/tests/test_fetch_sat_info.py": ["/laika/__init__.py"], "/common/hardware.py": ["/common/hardware_tici.py", "/common/hardware_base.py"], "/selfdrive/interbridge/interbridged.py": ["/selfdrive/interbridge/unisocket.py"], "/common/dp_common.py": ["/common/params.py", "/common/travis_checker.py"], "/tools/carcontrols/debug_controls.py": ["/common/params.py"], "/common/op_params.py": ["/common/travis_checker.py", "/common/colors.py"], "/laika_repo/laika/astro_dog.py": ["/laika_repo/laika/helpers.py", "/laika_repo/laika/downloader.py"], "/laika_repo/tests/test_positioning.py": ["/laika/__init__.py", "/laika/downloader.py"], "/selfdrive/test/test_openpilot.py": ["/common/params.py"], "/tools/replay/camera.py": ["/common/basedir.py"], "/common/hardware_tici.py": ["/common/hardware_base.py"], "/laika_repo/laika/raw_gnss.py": ["/laika_repo/laika/helpers.py"], "/selfdrive/test/process_replay/update_model.py": ["/tools/lib/logreader.py", "/selfdrive/test/process_replay/inject_model.py"], "/selfdrive/car/volkswagen/carstate.py": ["/selfdrive/car/volkswagen/values.py"], "/selfdrive/controls/lib/dynamic_follow/auto_df.py": ["/common/travis_checker.py"], "/selfdrive/test/process_replay/camera_replay.py": ["/common/hardware.py", "/tools/lib/logreader.py"], "/selfdrive/data_collection/gps_uploader.py": ["/common/params.py", "/common/op_params.py"], "/common/travis_checker.py": ["/common/basedir.py"], "/tools/replay/sensorium.py": ["/tools/replay/lib/ui_helpers.py"], "/tools/replay/unlogger.py": ["/tools/lib/logreader.py", "/tools/lib/route_framereader.py"], "/selfdrive/dragonpilot/appd.py": ["/common/params.py", "/common/dp_conf.py"], "/selfdrive/crash.py": ["/common/params.py", "/common/hardware.py", "/common/op_params.py"], "/laika_repo/tests/test_ephemerides.py": ["/laika/__init__.py"], "/selfdrive/test/testing_closet_client.py": ["/common/params.py"], "/selfdrive/test/model_replay.py": ["/tools/lib/logreader.py", "/selfdrive/test/process_replay/camera_replay.py"], "/tools/webcam/accept_terms.py": ["/common/params.py"], "/laika/astro_dog.py": ["/laika/helpers.py", "/laika/downloader.py", "/laika/__init__.py"], "/selfdrive/mapd/mapd.py": ["/selfdrive/crash.py", "/common/params.py"], "/selfdrive/dragonpilot/systemd.py": ["/common/dp_conf.py", "/common/params.py", "/common/i18n.py", "/common/dp_common.py", "/common/dp_time.py", "/selfdrive/dragonpilot/dashcam.py", "/common/travis_checker.py"], "/op_edit.py": ["/common/op_params.py", "/common/colors.py"], "/selfdrive/test/profiling/profiler.py": ["/common/params.py", "/tools/lib/logreader.py"], "/selfdrive/controls/lib/planner.py": ["/common/params.py", "/common/op_params.py"], "/common/basedir.py": ["/common/hardware.py"], "/selfdrive/car/toyota/carstate.py": ["/common/params.py", "/common/travis_checker.py", "/common/op_params.py"], "/laika_repo/tests/test_prns.py": ["/laika/helpers.py"], "/selfdrive/golden/can_bridge.py": ["/common/params.py"]}
|
16,594,522
|
rav4kumar/openpilot
|
refs/heads/DP08
|
/selfdrive/tombstoned.py
|
#!/usr/bin/env python3
import os
import time
from raven import Client
from raven.transport.http import HTTPTransport
from selfdrive.version import version, dirty
from selfdrive.swaglog import cloudlog
MAX_SIZE = 100000 * 10 # Normal size is 40-100k, allow up to 1M
def get_tombstones():
"""Returns list of (filename, ctime) for all tombstones in /data/tombstones
and apport crashlogs in /var/crash"""
files = []
for folder in ["/data/tombstones/", "/var/crash/"]:
if os.path.exists(folder):
with os.scandir(folder) as d:
# Loop over first 1000 directory entries
for _, f in zip(range(1000), d):
if f.name.startswith("tombstone"):
files.append((f.path, int(f.stat().st_ctime)))
elif f.name.endswith(".crash") and f.stat().st_mode == 0o100640:
files.append((f.path, int(f.stat().st_ctime)))
return files
def report_tombstone(fn, client):
f_size = os.path.getsize(fn)
if f_size > MAX_SIZE:
cloudlog.error(f"Tombstone {fn} too big, {f_size}. Skipping...")
return
with open(fn, encoding='ISO-8859-1') as f:
contents = f.read()
# Get summary for sentry title
if fn.endswith(".crash"):
lines = contents.split('\n')
message = lines[6]
status_idx = contents.find('ProcStatus')
if status_idx >= 0:
lines = contents[status_idx:].split('\n')
message += " " + lines[1]
else:
message = " ".join(contents.split('\n')[5:7])
# Cut off pid/tid, since that varies per run
name_idx = message.find('name')
if name_idx >= 0:
message = message[name_idx:]
# Cut off fault addr
fault_idx = message.find(', fault addr')
if fault_idx >= 0:
message = message[:fault_idx]
cloudlog.error({'tombstone': message})
client.captureMessage(
message=message,
sdk={'name': 'tombstoned', 'version': '0'},
extra={
'tombstone_fn': fn,
'tombstone': contents
},
)
def main():
initial_tombstones = set(get_tombstones())
client = Client('https://137e8e621f114f858f4c392c52e18c6d:8aba82f49af040c8aac45e95a8484970@sentry.io/1404547',
install_sys_hook=False, transport=HTTPTransport, release=version, tags={'dirty': dirty}, string_max_length=10000)
client.user_context({'id': os.environ.get('DONGLE_ID')})
while True:
now_tombstones = set(get_tombstones())
for fn, _ in (now_tombstones - initial_tombstones):
try:
cloudlog.info(f"reporting new tombstone {fn}")
report_tombstone(fn, client)
except Exception:
cloudlog.exception(f"Error reporting tombstone {fn}")
initial_tombstones = now_tombstones
time.sleep(5)
if __name__ == "__main__":
main()
|
{"/selfdrive/debug/internal/sounds/test_sounds.py": ["/common/basedir.py"], "/selfdrive/debug/internal/sounds/test_sound_stability.py": ["/common/basedir.py"], "/selfdrive/test/process_replay/model_replay.py": ["/tools/lib/logreader.py"], "/selfdrive/controls/lib/dynamic_follow/__init__.py": ["/common/params.py", "/common/dp_time.py", "/common/dp_common.py", "/selfdrive/controls/lib/dynamic_follow/auto_df.py", "/selfdrive/controls/lib/dynamic_follow/support.py"], "/selfdrive/test/test_cpu_usage.py": ["/common/basedir.py", "/common/params.py"], "/common/i18n.py": ["/common/hardware.py"], "/laika_repo/tests/test_fetch_sat_info.py": ["/laika/__init__.py"], "/common/hardware.py": ["/common/hardware_tici.py", "/common/hardware_base.py"], "/selfdrive/interbridge/interbridged.py": ["/selfdrive/interbridge/unisocket.py"], "/common/dp_common.py": ["/common/params.py", "/common/travis_checker.py"], "/tools/carcontrols/debug_controls.py": ["/common/params.py"], "/common/op_params.py": ["/common/travis_checker.py", "/common/colors.py"], "/laika_repo/laika/astro_dog.py": ["/laika_repo/laika/helpers.py", "/laika_repo/laika/downloader.py"], "/laika_repo/tests/test_positioning.py": ["/laika/__init__.py", "/laika/downloader.py"], "/selfdrive/test/test_openpilot.py": ["/common/params.py"], "/tools/replay/camera.py": ["/common/basedir.py"], "/common/hardware_tici.py": ["/common/hardware_base.py"], "/laika_repo/laika/raw_gnss.py": ["/laika_repo/laika/helpers.py"], "/selfdrive/test/process_replay/update_model.py": ["/tools/lib/logreader.py", "/selfdrive/test/process_replay/inject_model.py"], "/selfdrive/car/volkswagen/carstate.py": ["/selfdrive/car/volkswagen/values.py"], "/selfdrive/controls/lib/dynamic_follow/auto_df.py": ["/common/travis_checker.py"], "/selfdrive/test/process_replay/camera_replay.py": ["/common/hardware.py", "/tools/lib/logreader.py"], "/selfdrive/data_collection/gps_uploader.py": ["/common/params.py", "/common/op_params.py"], "/common/travis_checker.py": ["/common/basedir.py"], "/tools/replay/sensorium.py": ["/tools/replay/lib/ui_helpers.py"], "/tools/replay/unlogger.py": ["/tools/lib/logreader.py", "/tools/lib/route_framereader.py"], "/selfdrive/dragonpilot/appd.py": ["/common/params.py", "/common/dp_conf.py"], "/selfdrive/crash.py": ["/common/params.py", "/common/hardware.py", "/common/op_params.py"], "/laika_repo/tests/test_ephemerides.py": ["/laika/__init__.py"], "/selfdrive/test/testing_closet_client.py": ["/common/params.py"], "/selfdrive/test/model_replay.py": ["/tools/lib/logreader.py", "/selfdrive/test/process_replay/camera_replay.py"], "/tools/webcam/accept_terms.py": ["/common/params.py"], "/laika/astro_dog.py": ["/laika/helpers.py", "/laika/downloader.py", "/laika/__init__.py"], "/selfdrive/mapd/mapd.py": ["/selfdrive/crash.py", "/common/params.py"], "/selfdrive/dragonpilot/systemd.py": ["/common/dp_conf.py", "/common/params.py", "/common/i18n.py", "/common/dp_common.py", "/common/dp_time.py", "/selfdrive/dragonpilot/dashcam.py", "/common/travis_checker.py"], "/op_edit.py": ["/common/op_params.py", "/common/colors.py"], "/selfdrive/test/profiling/profiler.py": ["/common/params.py", "/tools/lib/logreader.py"], "/selfdrive/controls/lib/planner.py": ["/common/params.py", "/common/op_params.py"], "/common/basedir.py": ["/common/hardware.py"], "/selfdrive/car/toyota/carstate.py": ["/common/params.py", "/common/travis_checker.py", "/common/op_params.py"], "/laika_repo/tests/test_prns.py": ["/laika/helpers.py"], "/selfdrive/golden/can_bridge.py": ["/common/params.py"]}
|
16,594,523
|
rav4kumar/openpilot
|
refs/heads/DP08
|
/tools/replay/lib/ui_helpers.py
|
from collections import namedtuple
from typing import Any, Dict, Tuple
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
import pygame # pylint: disable=import-error
from common.transformations.camera import (eon_f_frame_size, eon_f_focal_length,
tici_f_frame_size, tici_f_focal_length)
from selfdrive.config import RADAR_TO_CAMERA
from selfdrive.config import UIParams as UP
from selfdrive.controls.lib.lane_planner import (compute_path_pinv,
model_polyfit)
from tools.lib.lazy_property import lazy_property
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
YELLOW = (255, 255, 0)
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
_PATH_X = np.arange(192.)
_PATH_XD = np.arange(192.)
_PATH_PINV = compute_path_pinv(50)
_FULL_FRAME_SIZE = {
}
_BB_TO_FULL_FRAME = {}
_FULL_FRAME_TO_BB = {}
_INTRINSICS = {}
cams = [(eon_f_frame_size[0], eon_f_frame_size[1], eon_f_focal_length),
(tici_f_frame_size[0], tici_f_frame_size[1], tici_f_focal_length)]
for width, height, focal in cams:
sz = width * height
_BB_SCALE = width / 640.
_BB_TO_FULL_FRAME[sz] = np.asarray([
[_BB_SCALE, 0., 0.],
[0., _BB_SCALE, 0.],
[0., 0., 1.]])
_FULL_FRAME_TO_BB[sz] = np.linalg.inv(_BB_TO_FULL_FRAME[sz])
_FULL_FRAME_SIZE[sz] = (width, height)
_INTRINSICS[sz] = np.array([
[focal, 0., width / 2.],
[0., focal, height / 2.],
[0., 0., 1.]])
METER_WIDTH = 20
ModelUIData = namedtuple("ModelUIData", ["cpath", "lpath", "rpath", "lead", "lead_future"])
_COLOR_CACHE : Dict[Tuple[int, int, int], Any] = {}
def find_color(lidar_surface, color):
if color in _COLOR_CACHE:
return _COLOR_CACHE[color]
tcolor = 0
ret = 255
for x in lidar_surface.get_palette():
#print tcolor, x
if x[0:3] == color:
ret = tcolor
break
tcolor += 1
_COLOR_CACHE[color] = ret
return ret
def warp_points(pt_s, warp_matrix):
# pt_s are the source points, nxm array.
pt_d = np.dot(warp_matrix[:, :-1], pt_s.T) + warp_matrix[:, -1, None]
# Divide by last dimension for representation in image space.
return (pt_d[:-1, :] / pt_d[-1, :]).T
def to_lid_pt(y, x):
px, py = -x * UP.lidar_zoom + UP.lidar_car_x, -y * UP.lidar_zoom + UP.lidar_car_y
if px > 0 and py > 0 and px < UP.lidar_x and py < UP.lidar_y:
return int(px), int(py)
return -1, -1
def draw_path(y, x, color, img, calibration, top_down, lid_color=None):
# TODO: Remove big box.
uv_model_real = warp_points(np.column_stack((x, y)), calibration.car_to_model)
uv_model = np.round(uv_model_real).astype(int)
uv_model_dots = uv_model[np.logical_and.reduce((np.all( # pylint: disable=no-member
uv_model > 0, axis=1), uv_model[:, 0] < img.shape[1] - 1, uv_model[:, 1] <
img.shape[0] - 1))]
for i, j in ((-1, 0), (0, -1), (0, 0), (0, 1), (1, 0)):
img[uv_model_dots[:, 1] + i, uv_model_dots[:, 0] + j] = color
# draw lidar path point on lidar
# find color in 8 bit
if lid_color is not None and top_down is not None:
tcolor = find_color(top_down[0], lid_color)
for i in range(len(x)):
px, py = to_lid_pt(x[i], y[i])
if px != -1:
top_down[1][px, py] = tcolor
def draw_steer_path(speed_ms, curvature, color, img,
calibration, top_down, VM, lid_color=None):
path_x = np.arange(101.)
path_y = np.multiply(path_x, np.tan(np.arcsin(np.clip(path_x * curvature, -0.999, 0.999)) / 2.))
draw_path(path_y, path_x, color, img, calibration, top_down, lid_color)
def draw_lead_car(closest, top_down):
if closest is not None:
closest_y = int(round(UP.lidar_car_y - closest * UP.lidar_zoom))
if closest_y > 0:
top_down[1][int(round(UP.lidar_car_x - METER_WIDTH * 2)):int(
round(UP.lidar_car_x + METER_WIDTH * 2)), closest_y] = find_color(
top_down[0], (255, 0, 0))
def draw_lead_on(img, closest_x_m, closest_y_m, calibration, color, sz=10, img_offset=(0, 0)):
uv = warp_points(np.asarray([closest_x_m, closest_y_m]), calibration.car_to_bb)[0]
u, v = int(uv[0] + img_offset[0]), int(uv[1] + img_offset[1])
if u > 0 and u < 640 and v > 0 and v < 480 - 5:
img[v - 5 - sz:v - 5 + sz, u] = color
img[v - 5, u - sz:u + sz] = color
return u, v
def init_plots(arr, name_to_arr_idx, plot_xlims, plot_ylims, plot_names, plot_colors, plot_styles, bigplots=False):
color_palette = { "r": (1, 0, 0),
"g": (0, 1, 0),
"b": (0, 0, 1),
"k": (0, 0, 0),
"y": (1, 1, 0),
"p": (0, 1, 1),
"m": (1, 0, 1) }
if bigplots:
fig = plt.figure(figsize=(6.4, 7.0))
else:
fig = plt.figure()
fig.set_facecolor((0.2, 0.2, 0.2))
axs = []
for pn in range(len(plot_ylims)):
ax = fig.add_subplot(len(plot_ylims), 1, len(axs)+1)
ax.set_xlim(plot_xlims[pn][0], plot_xlims[pn][1])
ax.set_ylim(plot_ylims[pn][0], plot_ylims[pn][1])
ax.patch.set_facecolor((0.4, 0.4, 0.4))
axs.append(ax)
plots, idxs, plot_select = [], [], []
for i, pl_list in enumerate(plot_names):
for j, item in enumerate(pl_list):
plot, = axs[i].plot(arr[:, name_to_arr_idx[item]],
label=item,
color=color_palette[plot_colors[i][j]],
linestyle=plot_styles[i][j])
plots.append(plot)
idxs.append(name_to_arr_idx[item])
plot_select.append(i)
axs[i].set_title(", ".join("%s (%s)" % (nm, cl)
for (nm, cl) in zip(pl_list, plot_colors[i])), fontsize=10)
if i < len(plot_ylims) - 1:
axs[i].set_xticks([])
fig.canvas.draw()
renderer = fig.canvas.get_renderer()
if matplotlib.get_backend() == "MacOSX":
fig.draw(renderer)
def draw_plots(arr):
for ax in axs:
ax.draw_artist(ax.patch)
for i in range(len(plots)):
plots[i].set_ydata(arr[:, idxs[i]])
axs[plot_select[i]].draw_artist(plots[i])
if matplotlib.get_backend() == "QT4Agg":
fig.canvas.update()
fig.canvas.flush_events()
raw_data = renderer.tostring_rgb()
x, y = fig.canvas.get_width_height()
# Handle 2x scaling
if len(raw_data) == 4 * x * y * 3:
plot_surface = pygame.image.frombuffer(raw_data, (2*x, 2*y), "RGB").convert()
plot_surface = pygame.transform.scale(plot_surface, (x, y))
else:
plot_surface = pygame.image.frombuffer(raw_data, fig.canvas.get_width_height(), "RGB").convert()
return plot_surface
return draw_plots
def draw_mpc(liveMpc, top_down):
mpc_color = find_color(top_down[0], (0, 255, 0))
for p in zip(liveMpc.x, liveMpc.y):
px, py = to_lid_pt(*p)
top_down[1][px, py] = mpc_color
class CalibrationTransformsForWarpMatrix(object):
def __init__(self, num_px, model_to_full_frame, K, E):
self._model_to_full_frame = model_to_full_frame
self._K = K
self._E = E
self.num_px = num_px
@property
def model_to_bb(self):
return _FULL_FRAME_TO_BB[self.num_px].dot(self._model_to_full_frame)
@lazy_property
def model_to_full_frame(self):
return self._model_to_full_frame
@lazy_property
def car_to_model(self):
return np.linalg.inv(self._model_to_full_frame).dot(self._K).dot(
self._E[:, [0, 1, 3]])
@lazy_property
def car_to_bb(self):
return _BB_TO_FULL_FRAME[self.num_px].dot(self._K).dot(self._E[:, [0, 1, 3]])
def pygame_modules_have_loaded():
return pygame.display.get_init() and pygame.font.get_init()
def draw_var(y, x, var, color, img, calibration, top_down):
# otherwise drawing gets stupid
var = max(1e-1, min(var, 0.7))
varcolor = tuple(np.array(color)*0.5)
draw_path(y - var, x, varcolor, img, calibration, top_down)
draw_path(y + var, x, varcolor, img, calibration, top_down)
class ModelPoly(object):
def __init__(self, model_path):
if len(model_path.points) == 0 and len(model_path.poly) == 0:
self.valid = False
return
if len(model_path.poly):
self.poly = np.array(model_path.poly)
else:
self.poly = model_polyfit(model_path.points, _PATH_PINV)
self.prob = model_path.prob
self.std = model_path.std
self.y = np.polyval(self.poly, _PATH_XD)
self.valid = True
def extract_model_data(md):
return ModelUIData(
cpath=ModelPoly(md.path),
lpath=ModelPoly(md.leftLane),
rpath=ModelPoly(md.rightLane),
lead=md.lead,
lead_future=md.leadFuture,
)
def plot_model(m, VM, v_ego, curvature, imgw, calibration, top_down, d_poly, top_down_color=216):
if calibration is None or top_down is None:
return
for lead in [m.lead, m.lead_future]:
if lead.prob < 0.5:
continue
lead_dist_from_radar = lead.dist - RADAR_TO_CAMERA
_, py_top = to_lid_pt(lead_dist_from_radar + lead.std, lead.relY)
px, py_bottom = to_lid_pt(lead_dist_from_radar - lead.std, lead.relY)
top_down[1][int(round(px - 4)):int(round(px + 4)), py_top:py_bottom] = top_down_color
color = (0, int(255 * m.lpath.prob), 0)
for path in [m.cpath, m.lpath, m.rpath]:
if path.valid:
draw_path(path.y, _PATH_XD, color, imgw, calibration, top_down, YELLOW)
draw_var(path.y, _PATH_XD, path.std, color, imgw, calibration, top_down)
if d_poly is not None:
dpath_y = np.polyval(d_poly, _PATH_X)
draw_path(dpath_y, _PATH_X, RED, imgw, calibration, top_down, RED)
# draw user path from curvature
draw_steer_path(v_ego, curvature, BLUE, imgw, calibration, top_down, VM, BLUE)
def maybe_update_radar_points(lt, lid_overlay):
ar_pts = []
if lt is not None:
ar_pts = {}
for track in lt:
ar_pts[track.trackId] = [track.dRel, track.yRel, track.vRel, track.aRel, track.oncoming, track.stationary]
for ids, pt in ar_pts.items():
px, py = to_lid_pt(pt[0], pt[1])
if px != -1:
if pt[-1]:
color = 240
elif pt[-2]:
color = 230
else:
color = 255
if int(ids) == 1:
lid_overlay[px - 2:px + 2, py - 10:py + 10] = 100
else:
lid_overlay[px - 2:px + 2, py - 2:py + 2] = color
def get_blank_lid_overlay(UP):
lid_overlay = np.zeros((UP.lidar_x, UP.lidar_y), 'uint8')
# Draw the car.
lid_overlay[int(round(UP.lidar_car_x - UP.car_hwidth)):int(
round(UP.lidar_car_x + UP.car_hwidth)), int(round(UP.lidar_car_y -
UP.car_front))] = UP.car_color
lid_overlay[int(round(UP.lidar_car_x - UP.car_hwidth)):int(
round(UP.lidar_car_x + UP.car_hwidth)), int(round(UP.lidar_car_y +
UP.car_back))] = UP.car_color
lid_overlay[int(round(UP.lidar_car_x - UP.car_hwidth)), int(
round(UP.lidar_car_y - UP.car_front)):int(round(
UP.lidar_car_y + UP.car_back))] = UP.car_color
lid_overlay[int(round(UP.lidar_car_x + UP.car_hwidth)), int(
round(UP.lidar_car_y - UP.car_front)):int(round(
UP.lidar_car_y + UP.car_back))] = UP.car_color
return lid_overlay
|
{"/selfdrive/debug/internal/sounds/test_sounds.py": ["/common/basedir.py"], "/selfdrive/debug/internal/sounds/test_sound_stability.py": ["/common/basedir.py"], "/selfdrive/test/process_replay/model_replay.py": ["/tools/lib/logreader.py"], "/selfdrive/controls/lib/dynamic_follow/__init__.py": ["/common/params.py", "/common/dp_time.py", "/common/dp_common.py", "/selfdrive/controls/lib/dynamic_follow/auto_df.py", "/selfdrive/controls/lib/dynamic_follow/support.py"], "/selfdrive/test/test_cpu_usage.py": ["/common/basedir.py", "/common/params.py"], "/common/i18n.py": ["/common/hardware.py"], "/laika_repo/tests/test_fetch_sat_info.py": ["/laika/__init__.py"], "/common/hardware.py": ["/common/hardware_tici.py", "/common/hardware_base.py"], "/selfdrive/interbridge/interbridged.py": ["/selfdrive/interbridge/unisocket.py"], "/common/dp_common.py": ["/common/params.py", "/common/travis_checker.py"], "/tools/carcontrols/debug_controls.py": ["/common/params.py"], "/common/op_params.py": ["/common/travis_checker.py", "/common/colors.py"], "/laika_repo/laika/astro_dog.py": ["/laika_repo/laika/helpers.py", "/laika_repo/laika/downloader.py"], "/laika_repo/tests/test_positioning.py": ["/laika/__init__.py", "/laika/downloader.py"], "/selfdrive/test/test_openpilot.py": ["/common/params.py"], "/tools/replay/camera.py": ["/common/basedir.py"], "/common/hardware_tici.py": ["/common/hardware_base.py"], "/laika_repo/laika/raw_gnss.py": ["/laika_repo/laika/helpers.py"], "/selfdrive/test/process_replay/update_model.py": ["/tools/lib/logreader.py", "/selfdrive/test/process_replay/inject_model.py"], "/selfdrive/car/volkswagen/carstate.py": ["/selfdrive/car/volkswagen/values.py"], "/selfdrive/controls/lib/dynamic_follow/auto_df.py": ["/common/travis_checker.py"], "/selfdrive/test/process_replay/camera_replay.py": ["/common/hardware.py", "/tools/lib/logreader.py"], "/selfdrive/data_collection/gps_uploader.py": ["/common/params.py", "/common/op_params.py"], "/common/travis_checker.py": ["/common/basedir.py"], "/tools/replay/sensorium.py": ["/tools/replay/lib/ui_helpers.py"], "/tools/replay/unlogger.py": ["/tools/lib/logreader.py", "/tools/lib/route_framereader.py"], "/selfdrive/dragonpilot/appd.py": ["/common/params.py", "/common/dp_conf.py"], "/selfdrive/crash.py": ["/common/params.py", "/common/hardware.py", "/common/op_params.py"], "/laika_repo/tests/test_ephemerides.py": ["/laika/__init__.py"], "/selfdrive/test/testing_closet_client.py": ["/common/params.py"], "/selfdrive/test/model_replay.py": ["/tools/lib/logreader.py", "/selfdrive/test/process_replay/camera_replay.py"], "/tools/webcam/accept_terms.py": ["/common/params.py"], "/laika/astro_dog.py": ["/laika/helpers.py", "/laika/downloader.py", "/laika/__init__.py"], "/selfdrive/mapd/mapd.py": ["/selfdrive/crash.py", "/common/params.py"], "/selfdrive/dragonpilot/systemd.py": ["/common/dp_conf.py", "/common/params.py", "/common/i18n.py", "/common/dp_common.py", "/common/dp_time.py", "/selfdrive/dragonpilot/dashcam.py", "/common/travis_checker.py"], "/op_edit.py": ["/common/op_params.py", "/common/colors.py"], "/selfdrive/test/profiling/profiler.py": ["/common/params.py", "/tools/lib/logreader.py"], "/selfdrive/controls/lib/planner.py": ["/common/params.py", "/common/op_params.py"], "/common/basedir.py": ["/common/hardware.py"], "/selfdrive/car/toyota/carstate.py": ["/common/params.py", "/common/travis_checker.py", "/common/op_params.py"], "/laika_repo/tests/test_prns.py": ["/laika/helpers.py"], "/selfdrive/golden/can_bridge.py": ["/common/params.py"]}
|
16,594,524
|
rav4kumar/openpilot
|
refs/heads/DP08
|
/selfdrive/car/toyota/carstate.py
|
from cereal import car
from common.numpy_fast import mean
from opendbc.can.can_define import CANDefine
from selfdrive.car.interfaces import CarStateBase
from opendbc.can.parser import CANParser
from selfdrive.config import Conversions as CV
from selfdrive.car.toyota.values import CAR, DBC, STEER_THRESHOLD, TSS2_CAR, NO_STOP_TIMER_CAR
from common.params import Params
import cereal.messaging as messaging
from common.travis_checker import travis
from common.op_params import opParams
op_params = opParams()
rsa_max_speed = op_params.get('rsa_max_speed')
limit_rsa = op_params.get('limit_rsa')
class CarState(CarStateBase):
def __init__(self, CP):
super().__init__(CP)
can_define = CANDefine(DBC[CP.carFingerprint]['pt'])
self.shifter_values = can_define.dv["GEAR_PACKET"]['GEAR']
# dp
self.dp_toyota_zss = Params().get('dp_toyota_zss') == b'1'
# All TSS2 car have the accurate sensor
self.accurate_steer_angle_seen = CP.carFingerprint in TSS2_CAR or CP.carFingerprint in [CAR.LEXUS_ISH] or self.dp_toyota_zss
self.setspeedcounter = 0
self.pcm_acc_active = False
self.main_on = False
self.gas_pressed = False
self.smartspeed = 0
self.spdval1 = 0
self.distance = 0
self.engineRPM = 0
#self.read_distance_lines = 0
if not travis:
self.pm = messaging.PubMaster(['liveTrafficData'])
self.sm = messaging.SubMaster(['liveMapData'])#',latControl',])
# On NO_DSU cars but not TSS2 cars the cp.vl["STEER_TORQUE_SENSOR"]['STEER_ANGLE']
# is zeroed to where the steering angle is at start.
# Need to apply an offset as soon as the steering angle measurements are both received
self.needs_angle_offset = True #CP.carFingerprint not in TSS2_CAR or CP.carFingerprint in [CAR.LEXUS_ISH] or self.dp_toyota_zss
self.angle_offset = 0.
def update(self, cp, cp_cam):
ret = car.CarState.new_message()
ret.doorOpen = any([cp.vl["SEATS_DOORS"]['DOOR_OPEN_FL'], cp.vl["SEATS_DOORS"]['DOOR_OPEN_FR'],
cp.vl["SEATS_DOORS"]['DOOR_OPEN_RL'], cp.vl["SEATS_DOORS"]['DOOR_OPEN_RR']])
ret.seatbeltUnlatched = cp.vl["SEATS_DOORS"]['SEATBELT_DRIVER_UNLATCHED'] != 0
ret.brakePressed = (cp.vl["BRAKE_MODULE"]['BRAKE_PRESSED'] != 0) or not bool(cp.vl["PCM_CRUISE"]['CRUISE_ACTIVE'])
ret.brakeLights = bool(cp.vl["ESP_CONTROL"]['BRAKE_LIGHTS_ACC'] or ret.brakePressed)
if self.CP.enableGasInterceptor:
ret.gas = (cp.vl["GAS_SENSOR"]['INTERCEPTOR_GAS'] + cp.vl["GAS_SENSOR"]['INTERCEPTOR_GAS2']) / 2.
ret.gasPressed = ret.gas > 15
elif self.CP.carFingerprint in [CAR.LEXUS_ISH, CAR.LEXUS_GSH]:
ret.gas = cp.vl["GAS_PEDAL_ALT"]['GAS_PEDAL']
ret.gasPressed = ret.gas > 1e-5
else:
ret.gas = cp.vl["GAS_PEDAL"]['GAS_PEDAL']
ret.gasPressed = cp.vl["PCM_CRUISE"]['GAS_RELEASED'] == 0
ret.wheelSpeeds.fl = cp.vl["WHEEL_SPEEDS"]['WHEEL_SPEED_FL'] * CV.KPH_TO_MS
ret.wheelSpeeds.fr = cp.vl["WHEEL_SPEEDS"]['WHEEL_SPEED_FR'] * CV.KPH_TO_MS
ret.wheelSpeeds.rl = cp.vl["WHEEL_SPEEDS"]['WHEEL_SPEED_RL'] * CV.KPH_TO_MS
ret.wheelSpeeds.rr = cp.vl["WHEEL_SPEEDS"]['WHEEL_SPEED_RR'] * CV.KPH_TO_MS
ret.vEgoRaw = mean([ret.wheelSpeeds.fl, ret.wheelSpeeds.fr, ret.wheelSpeeds.rl, ret.wheelSpeeds.rr])
ret.vEgo, ret.aEgo = self.update_speed_kf(ret.vEgoRaw)
ret.standstill = ret.vEgoRaw < 0.001
# Some newer models have a more accurate angle measurement in the TORQUE_SENSOR message. Use if non-zero
if abs(cp.vl["STEER_TORQUE_SENSOR"]['STEER_ANGLE']) > 1e-3:
self.accurate_steer_angle_seen = True
if self.accurate_steer_angle_seen:
if self.dp_toyota_zss:
ret.steeringAngle = cp.vl["SECONDARY_STEER_ANGLE"]['ZORRO_STEER'] - self.angle_offset
else:
ret.steeringAngle = cp.vl["STEER_TORQUE_SENSOR"]['STEER_ANGLE'] - self.angle_offset
if self.needs_angle_offset:
angle_wheel = cp.vl["STEER_ANGLE_SENSOR"]['STEER_ANGLE'] + cp.vl["STEER_ANGLE_SENSOR"]['STEER_FRACTION']
if (abs(angle_wheel) > 1e-3 and abs(ret.steeringAngle) > 1e-3) or self.dp_toyota_zss:
self.needs_angle_offset = False
self.angle_offset = ret.steeringAngle - angle_wheel
else:
ret.steeringAngle = cp.vl["STEER_ANGLE_SENSOR"]['STEER_ANGLE'] + cp.vl["STEER_ANGLE_SENSOR"]['STEER_FRACTION']
ret.steeringRate = cp.vl["STEER_ANGLE_SENSOR"]['STEER_RATE']
can_gear = int(cp.vl["GEAR_PACKET"]['GEAR'])
ret.gearShifter = self.parse_gear_shifter(self.shifter_values.get(can_gear, None))
#if self.read_distance_lines != cp.vl["PCM_CRUISE_SM"]['DISTANCE_LINES']:
#self.read_distance_lines = cp.vl["PCM_CRUISE_SM"]['DISTANCE_LINES']
#Params().put('dp_dynamic_follow', str(int(max(self.read_distance_lines - 1, 0))))
if not travis:
self.sm.update(0)
self.smartspeed = self.sm['liveMapData'].speedLimit
ret.leftBlinker = cp.vl["STEERING_LEVERS"]['TURN_SIGNALS'] == 1
ret.rightBlinker = cp.vl["STEERING_LEVERS"]['TURN_SIGNALS'] == 2
self.engineRPM = cp.vl["ENGINE_RPM"]['RPM']
ret.steeringTorque = cp.vl["STEER_TORQUE_SENSOR"]['STEER_TORQUE_DRIVER']
ret.steeringTorqueEps = cp.vl["STEER_TORQUE_SENSOR"]['STEER_TORQUE_EPS']
# we could use the override bit from dbc, but it's triggered at too high torque values
ret.steeringPressed = abs(ret.steeringTorque) > STEER_THRESHOLD
ret.steerWarning = cp.vl["EPS_STATUS"]['LKA_STATE'] not in [1, 5]
if self.CP.carFingerprint in [CAR.LEXUS_IS, CAR.LEXUS_NXT]:
self.main_on = cp.vl["DSU_CRUISE"]['MAIN_ON'] != 0
ret.cruiseState.speed = cp.vl["DSU_CRUISE"]['SET_SPEED'] * CV.KPH_TO_MS
self.low_speed_lockout = False
elif self.CP.carFingerprint in [CAR.LEXUS_ISH, CAR.LEXUS_GSH]:
self.main_on = cp.vl["PCM_CRUISE_ALT"]['MAIN_ON'] != 0
ret.cruiseState.speed = cp.vl["PCM_CRUISE_ALT"]['SET_SPEED'] * CV.KPH_TO_MS
self.low_speed_lockout = False
else:
self.main_on = cp.vl["PCM_CRUISE_2"]['MAIN_ON'] != 0
ret.cruiseState.speed = cp.vl["PCM_CRUISE_2"]['SET_SPEED'] * CV.KPH_TO_MS
self.low_speed_lockout = cp.vl["PCM_CRUISE_2"]['LOW_SPEED_LOCKOUT'] == 2
ret.cruiseState.available = self.main_on
if self.CP.carFingerprint in [CAR.LEXUS_ISH, CAR.LEXUS_GSH]:
# Lexus ISH does not have CRUISE_STATUS value (always 0), so we use CRUISE_ACTIVE value instead
self.pcm_acc_status = cp.vl["PCM_CRUISE"]['CRUISE_ACTIVE']
else:
self.pcm_acc_status = cp.vl["PCM_CRUISE"]['CRUISE_STATE']
if self.CP.carFingerprint in NO_STOP_TIMER_CAR or self.CP.enableGasInterceptor:
# ignore standstill in hybrid vehicles, since pcm allows to restart without
# receiving any special command. Also if interceptor is detected
ret.cruiseState.standstill = False
else:
ret.cruiseState.standstill = self.pcm_acc_status == 7
self.pcm_acc_active = bool(cp.vl["PCM_CRUISE"]['CRUISE_ACTIVE'])
ret.cruiseState.enabled = self.pcm_acc_active
if self.CP.carFingerprint == CAR.PRIUS:
ret.genericToggle = cp.vl["AUTOPARK_STATUS"]['STATE'] != 0
else:
ret.genericToggle = bool(cp.vl["LIGHT_STALK"]['AUTO_HIGH_BEAM'])
ret.stockAeb = bool(cp_cam.vl["PRE_COLLISION"]["PRECOLLISION_ACTIVE"] and cp_cam.vl["PRE_COLLISION"]["FORCE"] < -1e-5)
ret.espDisabled = cp.vl["ESP_CONTROL"]['TC_DISABLED'] != 0
# 2 is standby, 10 is active. TODO: check that everything else is really a faulty state
self.steer_state = cp.vl["EPS_STATUS"]['LKA_STATE']
self.distance = cp_cam.vl["ACC_CONTROL"]['DISTANCE']
if self.CP.carFingerprint in TSS2_CAR:
ret.leftBlindspot = (cp.vl["BSM"]['L_ADJACENT'] == 1) or (cp.vl["BSM"]['L_APPROACHING'] == 1)
ret.rightBlindspot = (cp.vl["BSM"]['R_ADJACENT'] == 1) or (cp.vl["BSM"]['R_APPROACHING'] == 1)
self.tsgn1 = cp_cam.vl["RSA1"]['TSGN1']
if self.spdval1 != cp_cam.vl["RSA1"]['SPDVAL1']:
self.rsa_ignored_speed = 0
self.spdval1 = cp_cam.vl["RSA1"]['SPDVAL1']
self.splsgn1 = cp_cam.vl["RSA1"]['SPLSGN1']
self.tsgn2 = cp_cam.vl["RSA1"]['TSGN2']
#self.spdval2 = cp_cam.vl["RSA1"]['SPDVAL2']
self.splsgn2 = cp_cam.vl["RSA1"]['SPLSGN2']
self.tsgn3 = cp_cam.vl["RSA2"]['TSGN3']
self.splsgn3 = cp_cam.vl["RSA2"]['SPLSGN3']
self.tsgn4 = cp_cam.vl["RSA2"]['TSGN4']
self.splsgn4 = cp_cam.vl["RSA2"]['SPLSGN4']
self.noovertake = self.tsgn1 == 65 or self.tsgn2 == 65 or self.tsgn3 == 65 or self.tsgn4 == 65 or self.tsgn1 == 66 or self.tsgn2 == 66 or self.tsgn3 == 66 or self.tsgn4 == 66
if (self.spdval1 > 0) and not (self.spdval1 == 35 and self.tsgn1 == 1) and self.rsa_ignored_speed != self.spdval1:
dat = messaging.new_message('liveTrafficData')
if self.spdval1 > 0:
dat.liveTrafficData.speedLimitValid = True
if self.tsgn1 == 36:
dat.liveTrafficData.speedLimit = self.spdval1 * 1.60934
elif self.tsgn1 == 1:
dat.liveTrafficData.speedLimit = self.spdval1
else:
dat.liveTrafficData.speedLimit = 0
else:
dat.liveTrafficData.speedLimitValid = False
#if self.spdval2 > 0:
# dat.liveTrafficData.speedAdvisoryValid = True
# dat.liveTrafficData.speedAdvisory = self.spdval2
#else:
dat.liveTrafficData.speedAdvisoryValid = False
if limit_rsa and rsa_max_speed < ret.vEgo:
dat.liveTrafficData.speedLimitValid = False
if not travis:
self.pm.send('liveTrafficData', dat)
if ret.gasPressed and not self.gas_pressed:
self.engaged_when_gas_was_pressed = self.pcm_acc_active
if ((ret.gasPressed) or (self.gas_pressed and not ret.gasPressed)) and self.engaged_when_gas_was_pressed and ret.vEgo > self.smartspeed:
self.rsa_ignored_speed = self.spdval1
dat = messaging.new_message('liveTrafficData')
dat.liveTrafficData.speedLimitValid = True
dat.liveTrafficData.speedLimit = ret.vEgo * 3.6
if not travis:
self.pm.send('liveTrafficData', dat)
self.gas_pressed = ret.gasPressed
return ret
@staticmethod
def get_can_parser(CP):
signals = [
# sig_name, sig_address, default
("STEER_ANGLE", "STEER_ANGLE_SENSOR", 0),
("GEAR", "GEAR_PACKET", 0),
("BRAKE_PRESSED", "BRAKE_MODULE", 0),
("GAS_PEDAL", "GAS_PEDAL", 0),
("RPM", "ENGINE_RPM", 0),
("WHEEL_SPEED_FL", "WHEEL_SPEEDS", 0),
("WHEEL_SPEED_FR", "WHEEL_SPEEDS", 0),
("WHEEL_SPEED_RL", "WHEEL_SPEEDS", 0),
("WHEEL_SPEED_RR", "WHEEL_SPEEDS", 0),
("DOOR_OPEN_FL", "SEATS_DOORS", 1),
("DOOR_OPEN_FR", "SEATS_DOORS", 1),
("DOOR_OPEN_RL", "SEATS_DOORS", 1),
("DOOR_OPEN_RR", "SEATS_DOORS", 1),
("SEATBELT_DRIVER_UNLATCHED", "SEATS_DOORS", 1),
("TC_DISABLED", "ESP_CONTROL", 1),
("STEER_FRACTION", "STEER_ANGLE_SENSOR", 0),
("STEER_RATE", "STEER_ANGLE_SENSOR", 0),
("CRUISE_ACTIVE", "PCM_CRUISE", 0),
("CRUISE_STATE", "PCM_CRUISE", 0),
("GAS_RELEASED", "PCM_CRUISE", 1),
("STEER_TORQUE_DRIVER", "STEER_TORQUE_SENSOR", 0),
("STEER_TORQUE_EPS", "STEER_TORQUE_SENSOR", 0),
("STEER_ANGLE", "STEER_TORQUE_SENSOR", 0),
("TURN_SIGNALS", "STEERING_LEVERS", 3), # 3 is no blinkers
("LKA_STATE", "EPS_STATUS", 0),
("BRAKE_LIGHTS_ACC", "ESP_CONTROL", 0),
("AUTO_HIGH_BEAM", "LIGHT_STALK", 0),
("SPORT_ON", "GEAR_PACKET", 0),
("ECON_ON", "GEAR_PACKET", 0),
("DISTANCE_LINES", "PCM_CRUISE_SM", 0),
]
checks = [
#("BRAKE_MODULE", 40),
#("GAS_PEDAL", 33),
("WHEEL_SPEEDS", 80),
("STEER_ANGLE_SENSOR", 80),
("PCM_CRUISE", 33),
("STEER_TORQUE_SENSOR", 50),
("EPS_STATUS", 25),
]
if CP.carFingerprint in [CAR.LEXUS_ISH, CAR.LEXUS_GSH]:
signals.append(("GAS_PEDAL", "GAS_PEDAL_ALT", 0))
signals.append(("MAIN_ON", "PCM_CRUISE_ALT", 0))
signals.append(("SET_SPEED", "PCM_CRUISE_ALT", 0))
signals.append(("AUTO_HIGH_BEAM", "LIGHT_STALK_ISH", 0))
checks += [
("BRAKE_MODULE", 50),
("GAS_PEDAL_ALT", 50),
("PCM_CRUISE_ALT", 1),
]
else:
signals += [
("AUTO_HIGH_BEAM", "LIGHT_STALK", 0),
("GAS_PEDAL", "GAS_PEDAL", 0),
]
checks += [
("BRAKE_MODULE", 40),
("GAS_PEDAL", 33),
]
if CP.carFingerprint in [CAR.LEXUS_IS, CAR.LEXUS_NXT]:
signals.append(("MAIN_ON", "DSU_CRUISE", 0))
signals.append(("SET_SPEED", "DSU_CRUISE", 0))
checks.append(("DSU_CRUISE", 5))
else:
signals.append(("MAIN_ON", "PCM_CRUISE_2", 0))
signals.append(("SET_SPEED", "PCM_CRUISE_2", 0))
signals.append(("LOW_SPEED_LOCKOUT", "PCM_CRUISE_2", 0))
checks.append(("PCM_CRUISE_2", 33))
if CP.carFingerprint == CAR.PRIUS:
signals += [("STATE", "AUTOPARK_STATUS", 0)]
# add gas interceptor reading if we are using it
if CP.enableGasInterceptor:
signals.append(("INTERCEPTOR_GAS", "GAS_SENSOR", 0))
signals.append(("INTERCEPTOR_GAS2", "GAS_SENSOR", 0))
checks.append(("GAS_SENSOR", 50))
if CP.carFingerprint in TSS2_CAR:
signals += [("L_ADJACENT", "BSM", 0)]
signals += [("L_APPROACHING", "BSM", 0)]
signals += [("R_ADJACENT", "BSM", 0)]
signals += [("R_APPROACHING", "BSM", 0)]
if Params().get('dp_toyota_zss') == b'1':
signals += [("ZORRO_STEER", "SECONDARY_STEER_ANGLE", 0)]
checks = []
return CANParser(DBC[CP.carFingerprint]['pt'], signals, checks, 0)
@staticmethod
def get_cam_can_parser(CP):
signals = [
("FORCE", "PRE_COLLISION", 0),
("PRECOLLISION_ACTIVE", "PRE_COLLISION", 0),
("TSGN1", "RSA1", 0),
("SPDVAL1", "RSA1", 0),
("SPLSGN1", "RSA1", 0),
("TSGN2", "RSA1", 0),
#("SPDVAL2", "RSA1", 0),
("SPLSGN2", "RSA1", 0),
("TSGN3", "RSA2", 0),
("SPLSGN3", "RSA2", 0),
("TSGN4", "RSA2", 0),
("SPLSGN4", "RSA2", 0),
("DISTANCE", "ACC_CONTROL", 0),
]
# use steering message to check if panda is connected to frc
checks = [
("STEERING_LKA", 42)
]
checks = []
return CANParser(DBC[CP.carFingerprint]['pt'], signals, checks, 2)
|
{"/selfdrive/debug/internal/sounds/test_sounds.py": ["/common/basedir.py"], "/selfdrive/debug/internal/sounds/test_sound_stability.py": ["/common/basedir.py"], "/selfdrive/test/process_replay/model_replay.py": ["/tools/lib/logreader.py"], "/selfdrive/controls/lib/dynamic_follow/__init__.py": ["/common/params.py", "/common/dp_time.py", "/common/dp_common.py", "/selfdrive/controls/lib/dynamic_follow/auto_df.py", "/selfdrive/controls/lib/dynamic_follow/support.py"], "/selfdrive/test/test_cpu_usage.py": ["/common/basedir.py", "/common/params.py"], "/common/i18n.py": ["/common/hardware.py"], "/laika_repo/tests/test_fetch_sat_info.py": ["/laika/__init__.py"], "/common/hardware.py": ["/common/hardware_tici.py", "/common/hardware_base.py"], "/selfdrive/interbridge/interbridged.py": ["/selfdrive/interbridge/unisocket.py"], "/common/dp_common.py": ["/common/params.py", "/common/travis_checker.py"], "/tools/carcontrols/debug_controls.py": ["/common/params.py"], "/common/op_params.py": ["/common/travis_checker.py", "/common/colors.py"], "/laika_repo/laika/astro_dog.py": ["/laika_repo/laika/helpers.py", "/laika_repo/laika/downloader.py"], "/laika_repo/tests/test_positioning.py": ["/laika/__init__.py", "/laika/downloader.py"], "/selfdrive/test/test_openpilot.py": ["/common/params.py"], "/tools/replay/camera.py": ["/common/basedir.py"], "/common/hardware_tici.py": ["/common/hardware_base.py"], "/laika_repo/laika/raw_gnss.py": ["/laika_repo/laika/helpers.py"], "/selfdrive/test/process_replay/update_model.py": ["/tools/lib/logreader.py", "/selfdrive/test/process_replay/inject_model.py"], "/selfdrive/car/volkswagen/carstate.py": ["/selfdrive/car/volkswagen/values.py"], "/selfdrive/controls/lib/dynamic_follow/auto_df.py": ["/common/travis_checker.py"], "/selfdrive/test/process_replay/camera_replay.py": ["/common/hardware.py", "/tools/lib/logreader.py"], "/selfdrive/data_collection/gps_uploader.py": ["/common/params.py", "/common/op_params.py"], "/common/travis_checker.py": ["/common/basedir.py"], "/tools/replay/sensorium.py": ["/tools/replay/lib/ui_helpers.py"], "/tools/replay/unlogger.py": ["/tools/lib/logreader.py", "/tools/lib/route_framereader.py"], "/selfdrive/dragonpilot/appd.py": ["/common/params.py", "/common/dp_conf.py"], "/selfdrive/crash.py": ["/common/params.py", "/common/hardware.py", "/common/op_params.py"], "/laika_repo/tests/test_ephemerides.py": ["/laika/__init__.py"], "/selfdrive/test/testing_closet_client.py": ["/common/params.py"], "/selfdrive/test/model_replay.py": ["/tools/lib/logreader.py", "/selfdrive/test/process_replay/camera_replay.py"], "/tools/webcam/accept_terms.py": ["/common/params.py"], "/laika/astro_dog.py": ["/laika/helpers.py", "/laika/downloader.py", "/laika/__init__.py"], "/selfdrive/mapd/mapd.py": ["/selfdrive/crash.py", "/common/params.py"], "/selfdrive/dragonpilot/systemd.py": ["/common/dp_conf.py", "/common/params.py", "/common/i18n.py", "/common/dp_common.py", "/common/dp_time.py", "/selfdrive/dragonpilot/dashcam.py", "/common/travis_checker.py"], "/op_edit.py": ["/common/op_params.py", "/common/colors.py"], "/selfdrive/test/profiling/profiler.py": ["/common/params.py", "/tools/lib/logreader.py"], "/selfdrive/controls/lib/planner.py": ["/common/params.py", "/common/op_params.py"], "/common/basedir.py": ["/common/hardware.py"], "/selfdrive/car/toyota/carstate.py": ["/common/params.py", "/common/travis_checker.py", "/common/op_params.py"], "/laika_repo/tests/test_prns.py": ["/laika/helpers.py"], "/selfdrive/golden/can_bridge.py": ["/common/params.py"]}
|
16,594,525
|
rav4kumar/openpilot
|
refs/heads/DP08
|
/selfdrive/car/volkswagen/values.py
|
# flake8: noqa
from cereal import car
from selfdrive.car import dbc_dict
class CarControllerParams:
HCA_STEP = 2 # HCA message frequency 50Hz on all vehicles
MQB_LDW_STEP = 10 # LDW message frequency 10Hz on MQB
PQ_LDW_STEP = 5 # LDW message frequency 20Hz on PQ35/PQ46/NMS
GRA_ACC_STEP = 3 # GRA_ACC_01 message frequency 33Hz
GRA_VBP_STEP = 100 # Send ACC virtual button presses once a second
GRA_VBP_COUNT = 16 # Send VBP messages for ~0.5s (GRA_ACC_STEP * 16)
# Observed documented MQB limits: 3.00 Nm max, rate of change 5.00 Nm/sec.
# Limiting rate-of-change based on real-world testing and Comma's safety
# requirements for minimum time to lane departure.
STEER_MAX = 300 # Max heading control assist torque 3.00 Nm
STEER_DELTA_UP = 10 # Max HCA reached in 0.60s (STEER_MAX / (50Hz * 0.60))
STEER_DELTA_DOWN = 10 # Min HCA reached in 0.60s (STEER_MAX / (50Hz * 0.60))
STEER_DRIVER_ALLOWANCE = 80
STEER_DRIVER_MULTIPLIER = 3 # weight driver torque heavily
STEER_DRIVER_FACTOR = 1 # from dbc
class CANBUS:
pt = 0
cam = 2
NWL = car.CarParams.NetworkLocation
TRANS = car.CarParams.TransmissionType
GEAR = car.CarState.GearShifter
BUTTON_STATES = {
"accelCruise": False,
"decelCruise": False,
"cancel": False,
"setCruise": False,
"resumeCruise": False,
"gapAdjustCruise": False
}
MQB_LDW_MESSAGES = {
"none": 0, # Nothing to display
"laneAssistUnavailChime": 1, # "Lane Assist currently not available." with chime
"laneAssistUnavailNoSensorChime": 3, # "Lane Assist not available. No sensor view." with chime
"laneAssistTakeOverUrgent": 4, # "Lane Assist: Please Take Over Steering" with urgent beep
"emergencyAssistUrgent": 6, # "Emergency Assist: Please Take Over Steering" with urgent beep
"laneAssistTakeOverChime": 7, # "Lane Assist: Please Take Over Steering" with chime
"laneAssistTakeOverSilent": 8, # "Lane Assist: Please Take Over Steering" silent
"emergencyAssistChangingLanes": 9, # "Emergency Assist: Changing lanes..." with urgent beep
"laneAssistDeactivated": 10, # "Lane Assist deactivated." silent with persistent icon afterward
}
class CAR:
GENERICMQB = "VOLKSWAGEN MQB"
GENERICPQ = "VOLKSWAGEN GOLF"
FINGERPRINTS = {
CAR.GENERICMQB: [
{178: 8, 1600: 8, 1601: 8, 1603: 8, 1605: 8, 695: 8, 1624: 8, 1626: 8, 1629: 8, 1631: 8, 1122: 8, 1123: 8,
1124: 8, 1646: 8, 1648: 8, 1153: 8, 134: 8, 1162: 8, 1175: 8, 159: 8, 795: 8, 679: 8, 681: 8, 173: 8, 1712: 6,
1714: 8, 1716: 8, 1717: 8, 1719: 8, 1720: 8, 1721: 8, 1312: 8, 806: 8, 253: 8, 1792: 8, 257: 8, 260: 8, 262: 8,
897: 8, 264: 8, 779: 8, 780: 8, 783: 8, 278: 8, 279: 8, 792: 8, 283: 8, 285: 8, 286: 8, 901: 8, 288: 8, 289: 8,
290: 8, 804: 8, 294: 8, 807: 8, 808: 8, 809: 8, 299: 8, 302: 8, 1351: 8, 346: 8, 870: 8, 1385: 8, 896: 8, 64: 8,
898: 8, 1413: 8, 917: 8, 919: 8, 927: 8, 1440: 5, 929: 8, 930: 8, 427: 8, 949: 8, 958: 8, 960: 4, 418: 8, 981: 8,
987: 8, 988: 8, 991: 8, 997: 8, 1000: 8, 1514: 8, 1515: 8, 1520: 8, 1019: 8, 385: 8, 668: 8, 1120: 8,
1438: 8, 1461: 8, 391: 8, 1511: 8, 1516: 8, 568: 8, 569: 8, 826: 8, 827: 8, 1156: 8, 1157: 8, 1158: 8, 1471: 8,
1635: 8, 376: 8, 295: 8, 791: 8, 799: 8, 838: 8, 389: 8, 840: 8, 841: 8, 842: 8, 843: 8, 844: 8, 845: 8,
314: 8, 787: 8, 788: 8, 789: 8, 802: 8, 839: 8, 1332: 8, 1872: 8, 1976: 8, 1977: 8, 1985: 8, 2015: 8, 592: 8,
593: 8, 594: 8, 595: 8, 596: 8, 684: 8, 506: 8, 846: 8, 847: 8, 1982: 8
}],
CAR.GENERICPQ: [
# kamold, Edgy, austinc3030, Roy_001
{80: 4, 194: 8, 208: 6, 210: 5, 294: 8, 416: 8, 428: 8, 640: 8, 648: 8, 800: 8, 835: 3, 870: 8, 872: 8, 878: 8,
896: 8, 906: 4, 912: 8, 914: 8, 919: 8, 928: 8, 978: 7, 1056: 8, 1088: 8, 1152: 8, 1175: 8, 1184: 8, 1192: 8,
1312: 8, 1386: 8, 1392: 5, 1394: 1, 1408: 8, 1440: 8, 1463: 8, 1470: 5, 1472: 8, 1488: 8, 1490: 8, 1500: 8,
1550: 2, 1651: 3, 1652: 8, 1654: 2, 1658: 4, 1691: 3, 1736: 2, 1757: 8, 1824: 7, 1845: 7, 2000: 8, 1420: 8},
# cd (powertrain CAN direct)
{16: 7, 17: 7, 80: 4, 174: 8, 194: 8, 208: 6, 416: 8, 428: 8, 640: 8, 648: 8, 672: 8, 800: 8, 896: 8, 906: 4,
912: 8, 914: 8, 915: 8, 919: 8, 928: 8, 946: 8, 976: 6, 978: 7, 1056: 8, 1152: 8, 1160: 8, 1162: 8, 1164: 8,
1175: 8, 1184: 8, 1192: 8, 1306: 8, 1312: 8, 1344: 8, 1360: 8, 1386: 8, 1392: 5, 1394: 1, 1408: 8, 1416: 8,
1420: 8, 1423: 8, 1440: 8, 1463: 8, 1488: 8, 1490: 8, 1494: 2, 1500: 8, 1504: 8, 1523: 8, 1527: 4, 1654: 2,
1658: 2, 1754: 8, 1824: 7, 1827: 7, 2000: 8}],
}
MQB_CARS = [CAR.GENERICMQB]
PQ_CARS = [CAR.GENERICPQ]
DBC = {
CAR.GENERICMQB: dbc_dict('vw_mqb_2010', None),
CAR.GENERICPQ: dbc_dict('vw_golf_mk4', None),
}
|
{"/selfdrive/debug/internal/sounds/test_sounds.py": ["/common/basedir.py"], "/selfdrive/debug/internal/sounds/test_sound_stability.py": ["/common/basedir.py"], "/selfdrive/test/process_replay/model_replay.py": ["/tools/lib/logreader.py"], "/selfdrive/controls/lib/dynamic_follow/__init__.py": ["/common/params.py", "/common/dp_time.py", "/common/dp_common.py", "/selfdrive/controls/lib/dynamic_follow/auto_df.py", "/selfdrive/controls/lib/dynamic_follow/support.py"], "/selfdrive/test/test_cpu_usage.py": ["/common/basedir.py", "/common/params.py"], "/common/i18n.py": ["/common/hardware.py"], "/laika_repo/tests/test_fetch_sat_info.py": ["/laika/__init__.py"], "/common/hardware.py": ["/common/hardware_tici.py", "/common/hardware_base.py"], "/selfdrive/interbridge/interbridged.py": ["/selfdrive/interbridge/unisocket.py"], "/common/dp_common.py": ["/common/params.py", "/common/travis_checker.py"], "/tools/carcontrols/debug_controls.py": ["/common/params.py"], "/common/op_params.py": ["/common/travis_checker.py", "/common/colors.py"], "/laika_repo/laika/astro_dog.py": ["/laika_repo/laika/helpers.py", "/laika_repo/laika/downloader.py"], "/laika_repo/tests/test_positioning.py": ["/laika/__init__.py", "/laika/downloader.py"], "/selfdrive/test/test_openpilot.py": ["/common/params.py"], "/tools/replay/camera.py": ["/common/basedir.py"], "/common/hardware_tici.py": ["/common/hardware_base.py"], "/laika_repo/laika/raw_gnss.py": ["/laika_repo/laika/helpers.py"], "/selfdrive/test/process_replay/update_model.py": ["/tools/lib/logreader.py", "/selfdrive/test/process_replay/inject_model.py"], "/selfdrive/car/volkswagen/carstate.py": ["/selfdrive/car/volkswagen/values.py"], "/selfdrive/controls/lib/dynamic_follow/auto_df.py": ["/common/travis_checker.py"], "/selfdrive/test/process_replay/camera_replay.py": ["/common/hardware.py", "/tools/lib/logreader.py"], "/selfdrive/data_collection/gps_uploader.py": ["/common/params.py", "/common/op_params.py"], "/common/travis_checker.py": ["/common/basedir.py"], "/tools/replay/sensorium.py": ["/tools/replay/lib/ui_helpers.py"], "/tools/replay/unlogger.py": ["/tools/lib/logreader.py", "/tools/lib/route_framereader.py"], "/selfdrive/dragonpilot/appd.py": ["/common/params.py", "/common/dp_conf.py"], "/selfdrive/crash.py": ["/common/params.py", "/common/hardware.py", "/common/op_params.py"], "/laika_repo/tests/test_ephemerides.py": ["/laika/__init__.py"], "/selfdrive/test/testing_closet_client.py": ["/common/params.py"], "/selfdrive/test/model_replay.py": ["/tools/lib/logreader.py", "/selfdrive/test/process_replay/camera_replay.py"], "/tools/webcam/accept_terms.py": ["/common/params.py"], "/laika/astro_dog.py": ["/laika/helpers.py", "/laika/downloader.py", "/laika/__init__.py"], "/selfdrive/mapd/mapd.py": ["/selfdrive/crash.py", "/common/params.py"], "/selfdrive/dragonpilot/systemd.py": ["/common/dp_conf.py", "/common/params.py", "/common/i18n.py", "/common/dp_common.py", "/common/dp_time.py", "/selfdrive/dragonpilot/dashcam.py", "/common/travis_checker.py"], "/op_edit.py": ["/common/op_params.py", "/common/colors.py"], "/selfdrive/test/profiling/profiler.py": ["/common/params.py", "/tools/lib/logreader.py"], "/selfdrive/controls/lib/planner.py": ["/common/params.py", "/common/op_params.py"], "/common/basedir.py": ["/common/hardware.py"], "/selfdrive/car/toyota/carstate.py": ["/common/params.py", "/common/travis_checker.py", "/common/op_params.py"], "/laika_repo/tests/test_prns.py": ["/laika/helpers.py"], "/selfdrive/golden/can_bridge.py": ["/common/params.py"]}
|
16,594,526
|
rav4kumar/openpilot
|
refs/heads/DP08
|
/common/params.py
|
from common.params_pyx import Params, UnknownKeyName, put_nonblocking # pylint: disable=no-name-in-module, import-error
assert Params
assert UnknownKeyName
assert put_nonblocking
|
{"/selfdrive/debug/internal/sounds/test_sounds.py": ["/common/basedir.py"], "/selfdrive/debug/internal/sounds/test_sound_stability.py": ["/common/basedir.py"], "/selfdrive/test/process_replay/model_replay.py": ["/tools/lib/logreader.py"], "/selfdrive/controls/lib/dynamic_follow/__init__.py": ["/common/params.py", "/common/dp_time.py", "/common/dp_common.py", "/selfdrive/controls/lib/dynamic_follow/auto_df.py", "/selfdrive/controls/lib/dynamic_follow/support.py"], "/selfdrive/test/test_cpu_usage.py": ["/common/basedir.py", "/common/params.py"], "/common/i18n.py": ["/common/hardware.py"], "/laika_repo/tests/test_fetch_sat_info.py": ["/laika/__init__.py"], "/common/hardware.py": ["/common/hardware_tici.py", "/common/hardware_base.py"], "/selfdrive/interbridge/interbridged.py": ["/selfdrive/interbridge/unisocket.py"], "/common/dp_common.py": ["/common/params.py", "/common/travis_checker.py"], "/tools/carcontrols/debug_controls.py": ["/common/params.py"], "/common/op_params.py": ["/common/travis_checker.py", "/common/colors.py"], "/laika_repo/laika/astro_dog.py": ["/laika_repo/laika/helpers.py", "/laika_repo/laika/downloader.py"], "/laika_repo/tests/test_positioning.py": ["/laika/__init__.py", "/laika/downloader.py"], "/selfdrive/test/test_openpilot.py": ["/common/params.py"], "/tools/replay/camera.py": ["/common/basedir.py"], "/common/hardware_tici.py": ["/common/hardware_base.py"], "/laika_repo/laika/raw_gnss.py": ["/laika_repo/laika/helpers.py"], "/selfdrive/test/process_replay/update_model.py": ["/tools/lib/logreader.py", "/selfdrive/test/process_replay/inject_model.py"], "/selfdrive/car/volkswagen/carstate.py": ["/selfdrive/car/volkswagen/values.py"], "/selfdrive/controls/lib/dynamic_follow/auto_df.py": ["/common/travis_checker.py"], "/selfdrive/test/process_replay/camera_replay.py": ["/common/hardware.py", "/tools/lib/logreader.py"], "/selfdrive/data_collection/gps_uploader.py": ["/common/params.py", "/common/op_params.py"], "/common/travis_checker.py": ["/common/basedir.py"], "/tools/replay/sensorium.py": ["/tools/replay/lib/ui_helpers.py"], "/tools/replay/unlogger.py": ["/tools/lib/logreader.py", "/tools/lib/route_framereader.py"], "/selfdrive/dragonpilot/appd.py": ["/common/params.py", "/common/dp_conf.py"], "/selfdrive/crash.py": ["/common/params.py", "/common/hardware.py", "/common/op_params.py"], "/laika_repo/tests/test_ephemerides.py": ["/laika/__init__.py"], "/selfdrive/test/testing_closet_client.py": ["/common/params.py"], "/selfdrive/test/model_replay.py": ["/tools/lib/logreader.py", "/selfdrive/test/process_replay/camera_replay.py"], "/tools/webcam/accept_terms.py": ["/common/params.py"], "/laika/astro_dog.py": ["/laika/helpers.py", "/laika/downloader.py", "/laika/__init__.py"], "/selfdrive/mapd/mapd.py": ["/selfdrive/crash.py", "/common/params.py"], "/selfdrive/dragonpilot/systemd.py": ["/common/dp_conf.py", "/common/params.py", "/common/i18n.py", "/common/dp_common.py", "/common/dp_time.py", "/selfdrive/dragonpilot/dashcam.py", "/common/travis_checker.py"], "/op_edit.py": ["/common/op_params.py", "/common/colors.py"], "/selfdrive/test/profiling/profiler.py": ["/common/params.py", "/tools/lib/logreader.py"], "/selfdrive/controls/lib/planner.py": ["/common/params.py", "/common/op_params.py"], "/common/basedir.py": ["/common/hardware.py"], "/selfdrive/car/toyota/carstate.py": ["/common/params.py", "/common/travis_checker.py", "/common/op_params.py"], "/laika_repo/tests/test_prns.py": ["/laika/helpers.py"], "/selfdrive/golden/can_bridge.py": ["/common/params.py"]}
|
16,594,527
|
rav4kumar/openpilot
|
refs/heads/DP08
|
/external/simpleperf/inferno/svg_renderer.py
|
#
# Copyright (C) 2016 The Android Open Source Project
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
import sys
SVG_NODE_HEIGHT = 17
FONT_SIZE = 12
UNZOOM_NODE_ORIGIN_X = 10
UNZOOM_NODE_WIDTH = 80
INFO_NODE_ORIGIN_X = 120
INFO_NODE_WIDTH = 800
PERCENT_NODE_ORIGIN_X = 930
PERCENT_NODE_WIDTH = 250
SEARCH_NODE_ORIGIN_X = 1190
SEARCH_NODE_WIDTH = 80
RECT_TEXT_PADDING = 10
def hash_to_float(string):
return hash(string) / float(sys.maxsize)
def getLegacyColor(method):
r = 175 + int(50 * hash_to_float(reversed(method)))
g = 60 + int(180 * hash_to_float(method))
b = 60 + int(55 * hash_to_float(reversed(method)))
return (r, g, b)
def getDSOColor(method):
r = 170 + int(80 * hash_to_float(reversed(method)))
g = 180 + int(70 * hash_to_float((method)))
b = 170 + int(80 * hash_to_float(reversed(method)))
return (r, g, b)
def getHeatColor(callsite, total_weight):
r = 245 + 10 * (1 - callsite.weight() / total_weight)
g = 110 + 105 * (1 - callsite.weight() / total_weight)
b = 100
return (r, g, b)
def get_proper_scaled_time_string(value):
if value >= 1e9:
return '%.3f s' % (value / 1e9)
if value >= 1e6:
return '%.3f ms' % (value / 1e6)
if value >= 1e3:
return '%.3f us' % (value / 1e3)
return '%.0f ns' % value
def createSVGNode(process, callsite, depth, f, total_weight, height, color_scheme, nav):
x = float(callsite.offset) / total_weight * 100
y = height - (depth + 1) * SVG_NODE_HEIGHT
width = callsite.weight() / total_weight * 100
method = callsite.method.replace(">", ">").replace("<", "<")
if width <= 0:
return
if color_scheme == "dso":
r, g, b = getDSOColor(callsite.dso)
elif color_scheme == "legacy":
r, g, b = getLegacyColor(method)
else:
r, g, b = getHeatColor(callsite, total_weight)
r_border, g_border, b_border = [max(0, color - 50) for color in [r, g, b]]
if process.props['trace_offcpu']:
weight_str = get_proper_scaled_time_string(callsite.weight())
else:
weight_str = "{:,}".format(int(callsite.weight())) + ' events'
f.write(
"""<g id=%d class="n" onclick="zoom(this);" onmouseenter="select(this);" nav="%s">
<title>%s | %s (%s: %3.2f%%)</title>
<rect x="%f%%" y="%f" ox="%f" oy="%f" width="%f%%" owidth="%f" height="15.0"
ofill="rgb(%d,%d,%d)" fill="rgb(%d,%d,%d)" style="stroke:rgb(%d,%d,%d)"/>
<text x="%f%%" y="%f" font-size="%d" font-family="Monospace"></text>
</g>""" %
(callsite.id,
','.join(str(x) for x in nav),
method,
callsite.dso,
weight_str,
callsite.weight() / total_weight * 100,
x,
y,
x,
y,
width,
width,
r,
g,
b,
r,
g,
b,
r_border,
g_border,
b_border,
x,
y + 12,
FONT_SIZE))
def renderSVGNodes(process, flamegraph, depth, f, total_weight, height, color_scheme):
for i, child in enumerate(flamegraph.children):
# Prebuild navigation target for wasd
if i == 0:
left_index = 0
else:
left_index = flamegraph.children[i - 1].id
if i == len(flamegraph.children) - 1:
right_index = 0
else:
right_index = flamegraph.children[i + 1].id
up_index = max(child.children, key=lambda x: x.weight()).id if child.children else 0
# up, left, down, right
nav = [up_index, left_index, flamegraph.id, right_index]
createSVGNode(process, child, depth, f, total_weight, height, color_scheme, nav)
# Recurse down
renderSVGNodes(process, child, depth + 1, f, total_weight, height, color_scheme)
def renderSearchNode(f):
f.write(
"""<rect id="search_rect" style="stroke:rgb(0,0,0);" onclick="search(this);" class="t"
rx="10" ry="10" x="%d" y="10" width="%d" height="30" fill="rgb(255,255,255)""/>
<text id="search_text" class="t" x="%d" y="30" onclick="search(this);">Search</text>
""" % (SEARCH_NODE_ORIGIN_X, SEARCH_NODE_WIDTH, SEARCH_NODE_ORIGIN_X + RECT_TEXT_PADDING))
def renderUnzoomNode(f):
f.write(
"""<rect id="zoom_rect" style="display:none;stroke:rgb(0,0,0);" class="t"
onclick="unzoom(this);" rx="10" ry="10" x="%d" y="10" width="%d" height="30"
fill="rgb(255,255,255)"/>
<text id="zoom_text" style="display:none;" class="t" x="%d" y="30"
onclick="unzoom(this);">Zoom out</text>
""" % (UNZOOM_NODE_ORIGIN_X, UNZOOM_NODE_WIDTH, UNZOOM_NODE_ORIGIN_X + RECT_TEXT_PADDING))
def renderInfoNode(f):
f.write(
"""<clipPath id="info_clip_path"> <rect id="info_rect" style="stroke:rgb(0,0,0);"
rx="10" ry="10" x="%d" y="10" width="%d" height="30" fill="rgb(255,255,255)"/>
</clipPath>
<rect id="info_rect" style="stroke:rgb(0,0,0);"
rx="10" ry="10" x="%d" y="10" width="%d" height="30" fill="rgb(255,255,255)"/>
<text clip-path="url(#info_clip_path)" id="info_text" x="%d" y="30"></text>
""" % (INFO_NODE_ORIGIN_X, INFO_NODE_WIDTH, INFO_NODE_ORIGIN_X, INFO_NODE_WIDTH,
INFO_NODE_ORIGIN_X + RECT_TEXT_PADDING))
def renderPercentNode(f):
f.write(
"""<rect id="percent_rect" style="stroke:rgb(0,0,0);"
rx="10" ry="10" x="%d" y="10" width="%d" height="30" fill="rgb(255,255,255)"/>
<text id="percent_text" text-anchor="end" x="%d" y="30">100.00%%</text>
""" % (PERCENT_NODE_ORIGIN_X, PERCENT_NODE_WIDTH,
PERCENT_NODE_ORIGIN_X + PERCENT_NODE_WIDTH - RECT_TEXT_PADDING))
def renderSVG(process, flamegraph, f, color_scheme):
height = (flamegraph.get_max_depth() + 2) * SVG_NODE_HEIGHT
f.write("""<div class="flamegraph_block" style="width:100%%; height:%dpx;">
""" % height)
f.write("""<svg xmlns="http://www.w3.org/2000/svg"
xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1"
width="100%%" height="100%%" style="border: 1px solid black;"
rootid="%d">
""" % (flamegraph.children[0].id))
f.write("""<defs > <linearGradient id="background_gradiant" y1="0" y2="1" x1="0" x2="0" >
<stop stop-color="#eeeeee" offset="5%" /> <stop stop-color="#efefb1" offset="90%" />
</linearGradient> </defs>""")
f.write("""<rect x="0.0" y="0" width="100%" height="100%" fill="url(#background_gradiant)" />
""")
renderSVGNodes(process, flamegraph, 0, f, flamegraph.weight(), height, color_scheme)
renderSearchNode(f)
renderUnzoomNode(f)
renderInfoNode(f)
renderPercentNode(f)
f.write("</svg></div><br/>\n\n")
|
{"/selfdrive/debug/internal/sounds/test_sounds.py": ["/common/basedir.py"], "/selfdrive/debug/internal/sounds/test_sound_stability.py": ["/common/basedir.py"], "/selfdrive/test/process_replay/model_replay.py": ["/tools/lib/logreader.py"], "/selfdrive/controls/lib/dynamic_follow/__init__.py": ["/common/params.py", "/common/dp_time.py", "/common/dp_common.py", "/selfdrive/controls/lib/dynamic_follow/auto_df.py", "/selfdrive/controls/lib/dynamic_follow/support.py"], "/selfdrive/test/test_cpu_usage.py": ["/common/basedir.py", "/common/params.py"], "/common/i18n.py": ["/common/hardware.py"], "/laika_repo/tests/test_fetch_sat_info.py": ["/laika/__init__.py"], "/common/hardware.py": ["/common/hardware_tici.py", "/common/hardware_base.py"], "/selfdrive/interbridge/interbridged.py": ["/selfdrive/interbridge/unisocket.py"], "/common/dp_common.py": ["/common/params.py", "/common/travis_checker.py"], "/tools/carcontrols/debug_controls.py": ["/common/params.py"], "/common/op_params.py": ["/common/travis_checker.py", "/common/colors.py"], "/laika_repo/laika/astro_dog.py": ["/laika_repo/laika/helpers.py", "/laika_repo/laika/downloader.py"], "/laika_repo/tests/test_positioning.py": ["/laika/__init__.py", "/laika/downloader.py"], "/selfdrive/test/test_openpilot.py": ["/common/params.py"], "/tools/replay/camera.py": ["/common/basedir.py"], "/common/hardware_tici.py": ["/common/hardware_base.py"], "/laika_repo/laika/raw_gnss.py": ["/laika_repo/laika/helpers.py"], "/selfdrive/test/process_replay/update_model.py": ["/tools/lib/logreader.py", "/selfdrive/test/process_replay/inject_model.py"], "/selfdrive/car/volkswagen/carstate.py": ["/selfdrive/car/volkswagen/values.py"], "/selfdrive/controls/lib/dynamic_follow/auto_df.py": ["/common/travis_checker.py"], "/selfdrive/test/process_replay/camera_replay.py": ["/common/hardware.py", "/tools/lib/logreader.py"], "/selfdrive/data_collection/gps_uploader.py": ["/common/params.py", "/common/op_params.py"], "/common/travis_checker.py": ["/common/basedir.py"], "/tools/replay/sensorium.py": ["/tools/replay/lib/ui_helpers.py"], "/tools/replay/unlogger.py": ["/tools/lib/logreader.py", "/tools/lib/route_framereader.py"], "/selfdrive/dragonpilot/appd.py": ["/common/params.py", "/common/dp_conf.py"], "/selfdrive/crash.py": ["/common/params.py", "/common/hardware.py", "/common/op_params.py"], "/laika_repo/tests/test_ephemerides.py": ["/laika/__init__.py"], "/selfdrive/test/testing_closet_client.py": ["/common/params.py"], "/selfdrive/test/model_replay.py": ["/tools/lib/logreader.py", "/selfdrive/test/process_replay/camera_replay.py"], "/tools/webcam/accept_terms.py": ["/common/params.py"], "/laika/astro_dog.py": ["/laika/helpers.py", "/laika/downloader.py", "/laika/__init__.py"], "/selfdrive/mapd/mapd.py": ["/selfdrive/crash.py", "/common/params.py"], "/selfdrive/dragonpilot/systemd.py": ["/common/dp_conf.py", "/common/params.py", "/common/i18n.py", "/common/dp_common.py", "/common/dp_time.py", "/selfdrive/dragonpilot/dashcam.py", "/common/travis_checker.py"], "/op_edit.py": ["/common/op_params.py", "/common/colors.py"], "/selfdrive/test/profiling/profiler.py": ["/common/params.py", "/tools/lib/logreader.py"], "/selfdrive/controls/lib/planner.py": ["/common/params.py", "/common/op_params.py"], "/common/basedir.py": ["/common/hardware.py"], "/selfdrive/car/toyota/carstate.py": ["/common/params.py", "/common/travis_checker.py", "/common/op_params.py"], "/laika_repo/tests/test_prns.py": ["/laika/helpers.py"], "/selfdrive/golden/can_bridge.py": ["/common/params.py"]}
|
16,594,528
|
rav4kumar/openpilot
|
refs/heads/DP08
|
/laika_repo/tests/test_prns.py
|
import unittest
from laika.helpers import get_constellation, get_prn_from_nmea_id, \
get_nmea_id_from_prn, NMEA_ID_RANGES
class TestConstellationPRN(unittest.TestCase):
def test_constellation_from_valid_prn(self):
data = [
['G01', 'GPS'],
['G10', 'GPS'],
['G32', 'GPS'],
['R01', 'GLONASS'],
['R10', 'GLONASS'],
['R23', 'GLONASS'],
['R24', 'GLONASS'],
['R25', 'GLONASS'],
['R32', 'GLONASS'],
['E01', 'GALILEO'],
['E02', 'GALILEO'],
['E36', 'GALILEO'],
['C01', 'BEIDOU'],
['C02', 'BEIDOU'],
['C29', 'BEIDOU'],
['J01', 'QZNSS'],
['J04', 'QZNSS'],
['S01', 'SBAS'],
['I01', 'IRNSS']
]
for prn, expected_constellation in data:
constellation = get_constellation(prn)
self.assertEqual(constellation, expected_constellation)
def test_constellation_from_prn_with_invalid_identifier(self):
prn = '?01'
self.assertWarns(UserWarning, get_constellation, prn)
self.assertIsNone(get_constellation(prn))
def test_constellation_from_prn_outside_range(self):
prn = 'G99'
constellation = get_constellation(prn)
self.assertEqual(constellation, 'GPS')
def test_prn_from_nmea_id_for_main_constellations(self):
data = [
['G01', 1],
['G10', 10],
['G32', 32],
['R01', 65],
['R10', 74],
['R23', 87],
['R24', 88],
['R25', 89],
['R32', 96],
['E01', 301],
['E02', 302],
['E36', 336],
['C01', 201],
['C02', 202],
['C29', 229],
['J01', 193],
['J04', 196]
]
for expected_prn, nmea_id in data:
prn = get_prn_from_nmea_id(nmea_id)
self.assertEqual(prn, expected_prn)
def test_prn_from_nmea_id_for_SBAS(self):
'''Probably numbering SBAS as single constellation doesn't make
a sense, but programatically it works the same as for others
constellations.'''
data = [
['S01', 33],
['S02', 34],
['S10', 42],
['S22', 54],
['S23', 55],
['S32', 64],
['S33', 120],
['S64', 151],
['S65', 152],
['S71', 158]
]
for expected_prn, nmea_id in data:
prn = get_prn_from_nmea_id(nmea_id)
self.assertEqual(prn, expected_prn)
def test_prn_from_invalid_nmea_id(self):
data = [
(-1, "?-1"),
(0, "?0"),
(100, "?100"),
(160, "?160"),
(190, "?190"),
(300, "?300")
]
for nmea_id, expected_prn in data:
self.assertWarns(UserWarning, get_prn_from_nmea_id, nmea_id)
self.assertEqual(get_prn_from_nmea_id(nmea_id), expected_prn)
self.assertRaises(TypeError, get_prn_from_nmea_id, None)
self.assertRaises(TypeError, get_prn_from_nmea_id, '1')
def test_nmea_id_from_prn_for_main_constellations(self):
data = [
['G01', 1],
['G10', 10],
['G32', 32],
['R01', 65],
['R10', 74],
['R23', 87],
['R24', 88],
['R25', 89],
['R32', 96],
['E01', 301],
['E02', 302],
['E36', 336],
['C01', 201],
['C02', 202],
['C29', 229],
['J01', 193],
['J04', 196]
]
for prn, expected_nmea_id in data:
nmea_id = get_nmea_id_from_prn(prn)
self.assertEqual(nmea_id, expected_nmea_id)
def test_nmea_id_from_prn_for_SBAS(self):
'''Probably numbering SBAS as single constellation doesn't make
a sense, but programatically it works the same as for others
constellations.'''
data = [
['S01', 33],
['S02', 34],
['S10', 42],
['S22', 54],
['S23', 55],
['S32', 64],
['S33', 120],
['S64', 151],
['S65', 152],
['S71', 158]
]
for prn, expected_nmea_id in data:
nmea_id = get_nmea_id_from_prn(prn)
self.assertEqual(nmea_id, expected_nmea_id)
def test_nmea_id_from_invalid_prn(self):
# Special nknown constellation - valid number
self.assertEqual(1, get_nmea_id_from_prn('?01'))
self.assertEqual(-1, get_nmea_id_from_prn('?-1'))
# Special nknwon constellation - invalid number
self.assertRaises(ValueError, get_nmea_id_from_prn, '???')
# Constellation with unknwon identifier
self.assertRaises(NotImplementedError, get_nmea_id_from_prn, 'X01')
# Valid constellation - invalid number
self.assertRaises(ValueError, get_nmea_id_from_prn, 'G00')
self.assertRaises(ValueError, get_nmea_id_from_prn, 'GAA')
self.assertRaises(NotImplementedError, get_nmea_id_from_prn, 'G33')
self.assertRaises(NotImplementedError, get_nmea_id_from_prn, 'C99')
self.assertRaises(NotImplementedError, get_nmea_id_from_prn, 'R99')
self.assertRaises(NotImplementedError, get_nmea_id_from_prn, 'J99')
# None
self.assertRaises(TypeError, get_nmea_id_from_prn, None)
def test_nmea_ranges_are_valid(self):
last_end = 0
for entry in NMEA_ID_RANGES:
self.assertIn('range', entry)
self.assertIn('constellation', entry)
range_ = entry['range']
self.assertEqual(len(range_), 2)
start, end = range_
self.assertLessEqual(start, end)
self.assertLess(last_end, start)
last_end = end
|
{"/selfdrive/debug/internal/sounds/test_sounds.py": ["/common/basedir.py"], "/selfdrive/debug/internal/sounds/test_sound_stability.py": ["/common/basedir.py"], "/selfdrive/test/process_replay/model_replay.py": ["/tools/lib/logreader.py"], "/selfdrive/controls/lib/dynamic_follow/__init__.py": ["/common/params.py", "/common/dp_time.py", "/common/dp_common.py", "/selfdrive/controls/lib/dynamic_follow/auto_df.py", "/selfdrive/controls/lib/dynamic_follow/support.py"], "/selfdrive/test/test_cpu_usage.py": ["/common/basedir.py", "/common/params.py"], "/common/i18n.py": ["/common/hardware.py"], "/laika_repo/tests/test_fetch_sat_info.py": ["/laika/__init__.py"], "/common/hardware.py": ["/common/hardware_tici.py", "/common/hardware_base.py"], "/selfdrive/interbridge/interbridged.py": ["/selfdrive/interbridge/unisocket.py"], "/common/dp_common.py": ["/common/params.py", "/common/travis_checker.py"], "/tools/carcontrols/debug_controls.py": ["/common/params.py"], "/common/op_params.py": ["/common/travis_checker.py", "/common/colors.py"], "/laika_repo/laika/astro_dog.py": ["/laika_repo/laika/helpers.py", "/laika_repo/laika/downloader.py"], "/laika_repo/tests/test_positioning.py": ["/laika/__init__.py", "/laika/downloader.py"], "/selfdrive/test/test_openpilot.py": ["/common/params.py"], "/tools/replay/camera.py": ["/common/basedir.py"], "/common/hardware_tici.py": ["/common/hardware_base.py"], "/laika_repo/laika/raw_gnss.py": ["/laika_repo/laika/helpers.py"], "/selfdrive/test/process_replay/update_model.py": ["/tools/lib/logreader.py", "/selfdrive/test/process_replay/inject_model.py"], "/selfdrive/car/volkswagen/carstate.py": ["/selfdrive/car/volkswagen/values.py"], "/selfdrive/controls/lib/dynamic_follow/auto_df.py": ["/common/travis_checker.py"], "/selfdrive/test/process_replay/camera_replay.py": ["/common/hardware.py", "/tools/lib/logreader.py"], "/selfdrive/data_collection/gps_uploader.py": ["/common/params.py", "/common/op_params.py"], "/common/travis_checker.py": ["/common/basedir.py"], "/tools/replay/sensorium.py": ["/tools/replay/lib/ui_helpers.py"], "/tools/replay/unlogger.py": ["/tools/lib/logreader.py", "/tools/lib/route_framereader.py"], "/selfdrive/dragonpilot/appd.py": ["/common/params.py", "/common/dp_conf.py"], "/selfdrive/crash.py": ["/common/params.py", "/common/hardware.py", "/common/op_params.py"], "/laika_repo/tests/test_ephemerides.py": ["/laika/__init__.py"], "/selfdrive/test/testing_closet_client.py": ["/common/params.py"], "/selfdrive/test/model_replay.py": ["/tools/lib/logreader.py", "/selfdrive/test/process_replay/camera_replay.py"], "/tools/webcam/accept_terms.py": ["/common/params.py"], "/laika/astro_dog.py": ["/laika/helpers.py", "/laika/downloader.py", "/laika/__init__.py"], "/selfdrive/mapd/mapd.py": ["/selfdrive/crash.py", "/common/params.py"], "/selfdrive/dragonpilot/systemd.py": ["/common/dp_conf.py", "/common/params.py", "/common/i18n.py", "/common/dp_common.py", "/common/dp_time.py", "/selfdrive/dragonpilot/dashcam.py", "/common/travis_checker.py"], "/op_edit.py": ["/common/op_params.py", "/common/colors.py"], "/selfdrive/test/profiling/profiler.py": ["/common/params.py", "/tools/lib/logreader.py"], "/selfdrive/controls/lib/planner.py": ["/common/params.py", "/common/op_params.py"], "/common/basedir.py": ["/common/hardware.py"], "/selfdrive/car/toyota/carstate.py": ["/common/params.py", "/common/travis_checker.py", "/common/op_params.py"], "/laika_repo/tests/test_prns.py": ["/laika/helpers.py"], "/selfdrive/golden/can_bridge.py": ["/common/params.py"]}
|
16,594,529
|
rav4kumar/openpilot
|
refs/heads/DP08
|
/selfdrive/golden/can_bridge.py
|
#!/usr/bin/env python3
#pylint: skip-file
# flake8: noqa
import os
import time
import math
import atexit
import numpy as np
import threading
import random
import cereal.messaging as messaging
import argparse
from common.params import Params
from common.realtime import Ratekeeper
from selfdrive.golden.can import can_function, sendcan_function
import queue
import subprocess
import sys
import signal
def main():
os.system('echo 1 > /tmp/op_simulation')
os.system('echo 1 > /tmp/force_calibration')
os.system('service call audio 3 i32 3 i32 0 i32 1')
global pm
pm = messaging.PubMaster(['can', 'health'])
gps = messaging.sub_sock('gpsLocation')
live_params = messaging.sub_sock('liveParameters')
#live_calibartion = messaging.sub_sock('liveCalibration')
# can loop
sendcan = messaging.sub_sock('sendcan')
rk = Ratekeeper(100, print_delay_threshold=None)
steer_angle = 0.0
gps_speed = 30.0 / 3.6
cal_status = 0
posenet_speed = 0.0
btn_list = []
while 1:
gps_data = messaging.recv_sock(gps)
params = messaging.recv_sock(live_params)
calibration = None
#calibration = messaging.recv_sock(live_calibartion)
if gps_data:
gps_speed = gps_data.gpsLocation.speed
if params:
posenet_speed = params.liveParameters.posenetSpeed
#print ('posenet_speed=' + str(posenet_speed*3.6) + ' kph')
if calibration:
cal_status = calibration.liveCalibration.calStatus
engage = False
if rk.frame != 0 and rk.frame % 500 == 0:
engage = cal_status == 1
speed = gps_speed
if speed < 0.00001:
speed = posenet_speed
#can_function(pm, speed, steer_angle, rk.frame, rk.frame%500 == 499)
if os.path.exists('/tmp/op_start'):
if len(btn_list) == 0:
for x in range(10):
btn_list.append(3)
os.system('rm /tmp/op_start')
if os.path.exists('/tmp/op_stop'):
if len(btn_list) == 0:
for x in range(10):
btn_list.append(2)
os.system('rm /tmp/op_stop')
btn = 0
if len(btn_list) > 0:
btn = btn_list[0]
btn_list.pop(0)
can_function(pm, speed * 3.6, steer_angle, rk.frame, cruise_button=btn, is_engaged=1)
#if rk.frame%5 == 0:
# throttle, brake, steer = sendcan_function(sendcan)
# steer_angle += steer/10000.0 # torque
# # print(speed * 3.6, steer, throttle, brake)
dat = messaging.new_message('health')
dat.valid = True
dat.health = {
'ignitionLine': True,
'hwType': "blackPanda",
'controlsAllowed': True
}
pm.send('health', dat)
rk.keep_time()
def signal_handler(sig, frame):
print('You pressed Ctrl+C!')
global pm
dat = messaging.new_message('health')
dat.valid = True
dat.health = {
'ignitionLine': False,
'hwType': "greyPanda",
'controlsAllowed': True
}
for seq in range(10):
pm.send('health', dat)
time.sleep(0.1)
print ("exiting")
sys.exit(0)
if __name__ == "__main__":
signal.signal(signal.SIGINT, signal_handler)
main()
|
{"/selfdrive/debug/internal/sounds/test_sounds.py": ["/common/basedir.py"], "/selfdrive/debug/internal/sounds/test_sound_stability.py": ["/common/basedir.py"], "/selfdrive/test/process_replay/model_replay.py": ["/tools/lib/logreader.py"], "/selfdrive/controls/lib/dynamic_follow/__init__.py": ["/common/params.py", "/common/dp_time.py", "/common/dp_common.py", "/selfdrive/controls/lib/dynamic_follow/auto_df.py", "/selfdrive/controls/lib/dynamic_follow/support.py"], "/selfdrive/test/test_cpu_usage.py": ["/common/basedir.py", "/common/params.py"], "/common/i18n.py": ["/common/hardware.py"], "/laika_repo/tests/test_fetch_sat_info.py": ["/laika/__init__.py"], "/common/hardware.py": ["/common/hardware_tici.py", "/common/hardware_base.py"], "/selfdrive/interbridge/interbridged.py": ["/selfdrive/interbridge/unisocket.py"], "/common/dp_common.py": ["/common/params.py", "/common/travis_checker.py"], "/tools/carcontrols/debug_controls.py": ["/common/params.py"], "/common/op_params.py": ["/common/travis_checker.py", "/common/colors.py"], "/laika_repo/laika/astro_dog.py": ["/laika_repo/laika/helpers.py", "/laika_repo/laika/downloader.py"], "/laika_repo/tests/test_positioning.py": ["/laika/__init__.py", "/laika/downloader.py"], "/selfdrive/test/test_openpilot.py": ["/common/params.py"], "/tools/replay/camera.py": ["/common/basedir.py"], "/common/hardware_tici.py": ["/common/hardware_base.py"], "/laika_repo/laika/raw_gnss.py": ["/laika_repo/laika/helpers.py"], "/selfdrive/test/process_replay/update_model.py": ["/tools/lib/logreader.py", "/selfdrive/test/process_replay/inject_model.py"], "/selfdrive/car/volkswagen/carstate.py": ["/selfdrive/car/volkswagen/values.py"], "/selfdrive/controls/lib/dynamic_follow/auto_df.py": ["/common/travis_checker.py"], "/selfdrive/test/process_replay/camera_replay.py": ["/common/hardware.py", "/tools/lib/logreader.py"], "/selfdrive/data_collection/gps_uploader.py": ["/common/params.py", "/common/op_params.py"], "/common/travis_checker.py": ["/common/basedir.py"], "/tools/replay/sensorium.py": ["/tools/replay/lib/ui_helpers.py"], "/tools/replay/unlogger.py": ["/tools/lib/logreader.py", "/tools/lib/route_framereader.py"], "/selfdrive/dragonpilot/appd.py": ["/common/params.py", "/common/dp_conf.py"], "/selfdrive/crash.py": ["/common/params.py", "/common/hardware.py", "/common/op_params.py"], "/laika_repo/tests/test_ephemerides.py": ["/laika/__init__.py"], "/selfdrive/test/testing_closet_client.py": ["/common/params.py"], "/selfdrive/test/model_replay.py": ["/tools/lib/logreader.py", "/selfdrive/test/process_replay/camera_replay.py"], "/tools/webcam/accept_terms.py": ["/common/params.py"], "/laika/astro_dog.py": ["/laika/helpers.py", "/laika/downloader.py", "/laika/__init__.py"], "/selfdrive/mapd/mapd.py": ["/selfdrive/crash.py", "/common/params.py"], "/selfdrive/dragonpilot/systemd.py": ["/common/dp_conf.py", "/common/params.py", "/common/i18n.py", "/common/dp_common.py", "/common/dp_time.py", "/selfdrive/dragonpilot/dashcam.py", "/common/travis_checker.py"], "/op_edit.py": ["/common/op_params.py", "/common/colors.py"], "/selfdrive/test/profiling/profiler.py": ["/common/params.py", "/tools/lib/logreader.py"], "/selfdrive/controls/lib/planner.py": ["/common/params.py", "/common/op_params.py"], "/common/basedir.py": ["/common/hardware.py"], "/selfdrive/car/toyota/carstate.py": ["/common/params.py", "/common/travis_checker.py", "/common/op_params.py"], "/laika_repo/tests/test_prns.py": ["/laika/helpers.py"], "/selfdrive/golden/can_bridge.py": ["/common/params.py"]}
|
16,655,513
|
BorjaG90/ibm-auto-manager
|
refs/heads/develop
|
/ibm_auto_manager/scout/market_page.py
|
# -*- coding: utf-8 -*-
__author__ = 'Borja Gete'
__email__ = 'borjagete90@outlook.es'
from bs4 import BeautifulSoup
from datetime import datetime
from ibm_auto_manager.common import text
from ibm_auto_manager.common.util import cls, show
from ibm_auto_manager.connection.login_page import login
from ibm_auto_manager.scout import player_page, auction
def enter_market(auth, db):
""" Recorremos las páginas de mercado
Keyword arguments:
auth -- Cadena de autenticacion a la web.
db -- Objeto de conexion a la BD.
"""
db.auctions.delete_many({})
print(show("market") + " > Mercado previo eliminado")
params = {
"juvenil": 0,
"tiempos": 0,
"posiciones": -1,
"calidad": 14,
"edad": -1,
"cdirecta": 0
}
print(show("market") + " > Analizando Mercado Seniors")
for p_time in range(2, 5):
params["tiempos"] = p_time
for p_avg in range(11, 17):
params["calidad"] = p_avg
analyze_market_page(auth, params, db)
print(show("market") + " > Analizando Mercado Juniors")
params["juvenil"] = 1
params["edad"] = 0 # 14 años
for p_time in range(2, 5):
params["tiempos"] = p_time
for p_avg in range(4, 6):
params["calidad"] = p_avg
analyze_market_page(auth, params, db)
def analyze_market_page(auth, params, db):
""" Accede a la página del mercado obtenida de los parametros
Keyword arguments:
auth -- Cadena de autenticacion a la web.
params -- Parametros para construir la url del mercado.
db -- Objeto de conexion a la BD.
"""
session = login(auth)
market_url = "http://es.ibasketmanager.com/mercado.php"
market_url = market_url + "?juvenil=" + str(params["juvenil"])
market_url = market_url + "&tiempos=" + str(params["tiempos"])
market_url = market_url + "&posiciones=" + str(params["posiciones"])
market_url = market_url + "&calidad=" + str(params["calidad"])
market_url = market_url + "&edad" + str(params["edad"])
market_url = market_url + "&cdirecta=" + str(params["cdirecta"])
print(show("market") + ">{ " + market_url + " }")
r = session.get(market_url)
load_status = 0
while load_status != 200:
load_status = r.status_code
auctions = get_auctions(r.content)
for v_auction in auctions:
# print("\t{}".format(auction))
# Realizamos un analisis profundo de cada jugador
id_player = str(int(str(v_auction.player)))
player = player_page.get_player_data(id_player, auth, session)
# Esto es una tupla
similars = player_page.get_similar_data(id_player, auth, None, session)
# print(similars)
# Insertamos la subasta
# print(v_auction.date_auction)
db.auctions.insert_one(v_auction.to_db_collection())
db.auctions_history.replace_one(
{'_id': v_auction._id}, v_auction.to_db_collection(), True
)
player_page.insert_player(player, id_player, db)
player_page.insert_similars(similars, db)
player_page.updateAuctions(id_player, v_auction._id, db)
def get_auctions(html_content):
""" Analizamos los datos de la página del mercado y devolvemos las subastas
Keyword arguments:
html_content -- Texto completo de la página del mercado
en formato String.
"""
soup = BeautifulSoup(html_content, "html.parser")
auctions = []
final = soup.find("div", {"class": "texto final"})
if(final is None): # If there is auctions with that filter
players_str = soup.find_all(
"table", {"id": "pagetabla"})[0].find_all("tr")
players_str.pop(0)
# print(players_str)
for player_str in players_str:
player_soup = BeautifulSoup(str(player_str), "html.parser")
data_player = player_soup.find_all("td")
url = str(data_player[1].find("a")["href"]).split("id_jugador=")[1]
pos = str(data_player[2].text)[3:5:1]
avg = str(data_player[3].text)
age = str(data_player[4].text)
date_auction = text.date_market_translation(
str(data_player[6].text[10:50:1]))
offer = str(data_player[8].text).replace(
'€', '').replace('.', '').strip()
auctions.append(
auction.Auction(url, pos, avg, age, date_auction, offer))
else:
print('\t' + final.contents[0])
return auctions
|
{"/ibm_auto_manager/trainer/team_page.py": ["/ibm_auto_manager/common/util.py", "/ibm_auto_manager/connection/login_page.py", "/ibm_auto_manager/common/__init__.py"], "/ibm_auto_manager/app.py": ["/ibm_auto_manager/common/util.py"], "/ibm_auto_manager/general/dashboard_page.py": ["/ibm_auto_manager/common/util.py", "/ibm_auto_manager/connection/login_page.py"], "/ibm_auto_manager/scout/market_page.py": ["/ibm_auto_manager/common/__init__.py", "/ibm_auto_manager/common/util.py", "/ibm_auto_manager/connection/login_page.py"], "/ibm_auto_manager/scout/auction.py": ["/ibm_auto_manager/common/__init__.py"], "/ibm_auto_manager/scout/player_page.py": ["/ibm_auto_manager/common/__init__.py", "/ibm_auto_manager/common/util.py", "/ibm_auto_manager/connection/login_page.py"], "/ibm_auto_manager/scout/league_page.py": ["/ibm_auto_manager/common/util.py", "/ibm_auto_manager/connection/login_page.py", "/ibm_auto_manager/general/dashboard_page.py", "/ibm_auto_manager/trainer/team_page.py"], "/ibm_auto_manager/dt/automation.py": ["/ibm_auto_manager/connection/login_page.py", "/ibm_auto_manager/common/util.py"], "/ibm_auto_manager/scout/roster_page.py": ["/ibm_auto_manager/connection/login_page.py"], "/ibm_auto_manager/scout/transaction.py": ["/ibm_auto_manager/common/__init__.py"], "/ibm_auto_manager/scout/player.py": ["/ibm_auto_manager/common/__init__.py"]}
|
16,655,514
|
BorjaG90/ibm-auto-manager
|
refs/heads/develop
|
/ibm_auto_manager/scout/auction.py
|
# -*- coding: utf-8 -*-
__author__ = 'Borja Gete'
__email__ = 'borjagete90@outlook.es'
from datetime import datetime
from bson import ObjectId
from ibm_auto_manager.common import text
class Auction:
"""Representa una línea de mercado, una subasta de un jugador."""
def __init__(self,
id_player,
pos,
avg,
age,
date_auction,
offer
):
self._id = ObjectId((id_player + text.get_date_str(date_auction)).zfill(24))
self.player = ObjectId(id_player.zfill(24))
self.position = pos
self.average = int(avg)
self.age = int(age)
self.date_auction = date_auction
self.offer = int(offer.replace('.', ''))
def __str__(self):
return "Id: {}, {} de {} años y {} de media,\
hasta el {} por {}€".format(
self._id,
self.position,
self.age,
self.average,
self.date_auction,
self.offer
)
def to_db_collection(self):
"""Devuelve el dato de la subasta en un formato legible de MongoDB."""
return {
"_id": self._id,
"position": text.pos_treatment(self.position),
"age": self.age,
"average": self.average,
"date_auction": self.date_auction,
"offer": self.offer,
"_date": datetime.now(),
"player": self.player
}
|
{"/ibm_auto_manager/trainer/team_page.py": ["/ibm_auto_manager/common/util.py", "/ibm_auto_manager/connection/login_page.py", "/ibm_auto_manager/common/__init__.py"], "/ibm_auto_manager/app.py": ["/ibm_auto_manager/common/util.py"], "/ibm_auto_manager/general/dashboard_page.py": ["/ibm_auto_manager/common/util.py", "/ibm_auto_manager/connection/login_page.py"], "/ibm_auto_manager/scout/market_page.py": ["/ibm_auto_manager/common/__init__.py", "/ibm_auto_manager/common/util.py", "/ibm_auto_manager/connection/login_page.py"], "/ibm_auto_manager/scout/auction.py": ["/ibm_auto_manager/common/__init__.py"], "/ibm_auto_manager/scout/player_page.py": ["/ibm_auto_manager/common/__init__.py", "/ibm_auto_manager/common/util.py", "/ibm_auto_manager/connection/login_page.py"], "/ibm_auto_manager/scout/league_page.py": ["/ibm_auto_manager/common/util.py", "/ibm_auto_manager/connection/login_page.py", "/ibm_auto_manager/general/dashboard_page.py", "/ibm_auto_manager/trainer/team_page.py"], "/ibm_auto_manager/dt/automation.py": ["/ibm_auto_manager/connection/login_page.py", "/ibm_auto_manager/common/util.py"], "/ibm_auto_manager/scout/roster_page.py": ["/ibm_auto_manager/connection/login_page.py"], "/ibm_auto_manager/scout/transaction.py": ["/ibm_auto_manager/common/__init__.py"], "/ibm_auto_manager/scout/player.py": ["/ibm_auto_manager/common/__init__.py"]}
|
16,655,515
|
BorjaG90/ibm-auto-manager
|
refs/heads/develop
|
/ibm_auto_manager/__main__.py
|
# -*- coding: utf-8 -*-
__author__ = 'Borja Gete'
__email__ = 'borjagete90@outlook.es'
import sys
from ibm_auto_manager import app
if __name__ == '__main__':
app.run(sys.argv[1]) if len(sys.argv)>1 else app.run()
|
{"/ibm_auto_manager/trainer/team_page.py": ["/ibm_auto_manager/common/util.py", "/ibm_auto_manager/connection/login_page.py", "/ibm_auto_manager/common/__init__.py"], "/ibm_auto_manager/app.py": ["/ibm_auto_manager/common/util.py"], "/ibm_auto_manager/general/dashboard_page.py": ["/ibm_auto_manager/common/util.py", "/ibm_auto_manager/connection/login_page.py"], "/ibm_auto_manager/scout/market_page.py": ["/ibm_auto_manager/common/__init__.py", "/ibm_auto_manager/common/util.py", "/ibm_auto_manager/connection/login_page.py"], "/ibm_auto_manager/scout/auction.py": ["/ibm_auto_manager/common/__init__.py"], "/ibm_auto_manager/scout/player_page.py": ["/ibm_auto_manager/common/__init__.py", "/ibm_auto_manager/common/util.py", "/ibm_auto_manager/connection/login_page.py"], "/ibm_auto_manager/scout/league_page.py": ["/ibm_auto_manager/common/util.py", "/ibm_auto_manager/connection/login_page.py", "/ibm_auto_manager/general/dashboard_page.py", "/ibm_auto_manager/trainer/team_page.py"], "/ibm_auto_manager/dt/automation.py": ["/ibm_auto_manager/connection/login_page.py", "/ibm_auto_manager/common/util.py"], "/ibm_auto_manager/scout/roster_page.py": ["/ibm_auto_manager/connection/login_page.py"], "/ibm_auto_manager/scout/transaction.py": ["/ibm_auto_manager/common/__init__.py"], "/ibm_auto_manager/scout/player.py": ["/ibm_auto_manager/common/__init__.py"]}
|
16,655,516
|
BorjaG90/ibm-auto-manager
|
refs/heads/develop
|
/ibm_auto_manager/scout/player_page.py
|
# -*- coding: utf-8 -*-
__author__ = 'Borja Gete'
__email__ = 'borjagete90@outlook.es'
import re
import time
from bs4 import BeautifulSoup, Comment
from bson import ObjectId
from ibm_auto_manager.common import text
from ibm_auto_manager.common.util import show
from ibm_auto_manager.connection.login_page import login
from ibm_auto_manager.scout import player, transaction
def get_player_data(id_player, auth, session = None):
""" Obtenemos los datos del jugador pasado por parametros
Keyword arguments:
id_player -- Id del jugador con el que cargamos su página
auth -- Cadena de autenticacion a la web.
"""
if session is None:
print("[Relogging]")
session = login(auth)
# http://es.ibasketmanager.com/jugador.php?id_jugador=7192302
# http://es.ibasketmanager.com/jugador.php?id_jugador=7856412
# id_player = 7856412
player_url = "http://es.ibasketmanager.com/" + \
"jugador.php?id_jugador=" + str(id_player)
# print(show("player") + " >{ " + player_url + " }")
r = session.get(player_url)
load_status = 0
while load_status != 200:
load_status = r.status_code
v_player = analyze_player_page(id_player, r.content)
return v_player
def analyze_player_page(id_player, html_content):
""" Analizamos la página del jugador
y devolvemos una tupla con sus datos y atributos
Keyword arguments:
id_player -- Id del jugador con el que cargamos su página
html_content -- Texto completo de la página del mercado
en formato String.
"""
soup = BeautifulSoup(html_content, 'html.parser')
# Datos
barra = soup.find("div", {"class": "barrajugador"})
if barra is not None: # El jugador está en medio de un partido
estado = barra.findChildren("div" , recursive=False)[0]
name = barra.text.strip()
name = str(re.search(r'[A-ZÁÉÍÓÚ][\w\W]+', name).group(0))
if name.find('(Juvenil)') > 0:
juvenil = True
name = name.replace('(Juvenil)', '')
else:
juvenil = False
# print(estado)
if(estado.find('img') is not None):
# print(name + " Ascendido")
juvenil = True
name = name.strip()
caja50 = soup.find_all("div", {"class": "caja50"})
data0 = caja50[0].find_all("td")
data1 = caja50[1].find_all("td")
position = data0[1].text
age = str(re.search(r'[\d]+', data0[3].text).group(0)).strip()
# age = data0[3].text.replace('años','').replace('año','').replace(
# 'años','').replace('año','').strip()
heigth = str(re.search(r'[\d]+', data0[5].text.replace(
'.', '').replace(',', '')).group(0)).strip()
weight = str(re.search(r'[\d]+', data0[7].text.replace(
'.', '').replace(',', '')).group(0)).strip()
canon = str(re.search(r'[\d]+', data0[9].text.replace(
'.', '').replace(',', '')).group(0)).strip()
team_id = data1[1].find_all(
'a')[0]['href'][data1[1].find_all('a')[0]['href'].find('=')+1:]
salary = data1[3].text.replace('€', '').replace('.', '').strip()
clause = data1[5].text.replace('€', '').replace('.', '').strip()
years = str(re.search(r'[\d]+', data1[7].text).group(0)).strip()
country = data1[9].text.strip()
# Atributos
bars = soup.find_all("div", {"class": "jugbarranum"})
# print("---Atributos---")
power = bars[0].text
ambition = bars[1].text
leadership = bars[2].text
exp = bars[3].text
speed = bars[4].text
jump = bars[5].text
endurance = bars[6].text
level = bars[7].text[0:bars[7].text.find('(')].replace(',', '').strip()
marking = bars[11].text
rebound = bars[12].text
block = bars[13].text
recover = bars[14].text
two = bars[15].text
three = bars[16].text
free = bars[17].text
assist = bars[18].text
dribbling = bars[19].text
dunk = bars[20].text
fight = bars[21].text
# for t in bars:
# print(str(t.text))
# print("--Medias--")
caja5b = soup.find("div", {"class": "caja5b"})
mrx = caja5b.find("div", {"class": "mrx"}).find_all(
"td", {"class": "rojo"})
mental = mrx[0].text.replace('.', '').strip()
physic = mrx[1].text.replace('.', '').strip()
defense = mrx[2].text.replace('.', '').strip()
offense = mrx[3].text.replace('.', '').strip()
total = mrx[4].text.replace('.', '').strip()
# for t in mrx:
# print(t.text)
# Lealtad
ml = soup.find_all("div", {"class": "ml"})
for comments in ml[2].findAll(text=lambda text:isinstance(text, Comment)):
comment = comments[comments.find('jugbarranum">')+13:]
loyalty = comment[:comment.find('</div')]
# print(loyalty)
return [player.Player(id_player, team_id, name, position, age, heigth,
weight, canon, salary, clause, years, juvenil,
country),
player.PlayerAtributes(id_player, power, ambition, leadership,
exp, speed, jump, endurance, level,
marking, rebound, block, recover, two,
three, free, assist, dribbling, dunk,
fight, mental, physic, defense, offense,
total, loyalty)]
else:
return None
def insert_player(player, player_id, db):
""" Introduce el jugador en la BD
Keyword arguments:
player -- tupla que representa los datos y los atributos del jugador
player_id -- id del jugador
db -- Objeto de conexion a la BD.
"""
if player is not None:
# Comprobamos si el jugador ya existe y en consecuencia
# lo insertamos/actualizamos
# print(str(player_id) + ' - '+ str(player[0].id_player))
# print(db.players.find_one({"id_player": player_id}))
if (db.players.find_one({"_id": ObjectId(player_id.zfill(24))}) is not None):
# print(show("player") + " Actualizar P: " + str(player[0]))
db.players.update_one(
{"_id": ObjectId(player_id.zfill(24))},
{'$set': player[0].to_db_collection()}
)
else:
# print(show("player") + " Insertar P: " + str(player[0]))
db.players.insert_one(player[0].to_db_collection())
if (db.players.find_one({"_id": ObjectId(player_id.zfill(24))}) is not None):
# print(show("player") + " Actualizar PA: " + str(player[1]))
db.players.update_one(
{"_id": ObjectId(player_id.zfill(24))},
{'$set': player[1].to_db_collection()}
)
else:
# print(show("player") + " Insertar PA: " + str(player[1]))
db.players.insert_one(player[1].to_db_collection())
def get_similar_data(id_player, auth, register_date = None, session = None):
""" Obtenemos los datos de transacciones del jugador pasado por parametro
Keyword arguments:
id_player -- Id del jugador con el que cargamos su página
auth -- Cadena de autenticacion a la web.
"""
if session is None:
print("[Relogging]")
session = login(auth)
# http://es.ibasketmanager.com/jugador.php?id_jugador=7192302
# http://es.ibasketmanager.com/jugador.php?id_jugador=7856412
# id_player = 7856412
player_url = "http://es.ibasketmanager.com/jugador_compras_similares.php?" + \
"id_jugador=" + str(id_player)
# print(show("player") + " >{ " + player_url + " }")
r = session.get(player_url)
load_status = 0
while load_status != 200:
load_status = r.status_code
transactions = analyze_similar_page(id_player, r.content)
return transactions
def analyze_similar_page(id_player, html_content):
""" Analizamos la página de transacciones similares del jugador
y devolvemos una tupla con sus datos y atributos
Keyword arguments:
id_player -- Id del jugador con el que cargamos su página
html_content -- Texto completo de la página del mercado
en formato String.
"""
soup = BeautifulSoup(html_content, 'html.parser')
# Datos
transactions = []
final = soup.find("div", {'class': 'texto final'})
# print(final)
mensaje = soup.find("div", {"id": "menserror"}) # Playing a game
# print(mensaje)
if(final is None and mensaje is None):
# If there is auctions with that filter
players_str = soup.find_all(
'table', {"id": "pagetabla"})[0].find_all('tr')
players_str.pop(0) # Deleted THs elements
for player_str in players_str:
player_soup = BeautifulSoup(str(player_str), 'html.parser')
data_player = player_soup.find_all("td")
name = str(data_player[0].find('a').text)
id_date_buy = data_player[1].find("div").text
date_buy = text.date_translation(
data_player[1].text.replace(id_date_buy, '').strip())
age = data_player[2].text
avg = data_player[3].text
pos = data_player[4].text
salary = data_player[5].text.replace(
'.', '').replace('€', '').strip()
price = data_player[6].text.replace(
'.', '').replace('€', '').strip()
type_buy = data_player[7].text
# print('\nId: '+ str(id_player) + ' Jugador: ' + name+ ' \
# ' + pos + ' de ' + age + ' años, con ' + avg + ' de media')
# print('Vendido en ' + type_buy + ' por ' + price + '€, cobrando \
# ' + salary + '€ en la fecha '+ date_buy +'\n')
transactions.append(
transaction.Transaction(
id_player,
id_date_buy,
age,
avg,
pos,
price,
type_buy,
salary,
date_buy
)
)
return transactions
def insert_similars(similars, db):
""" Introduce las compras similares en la BD
Keyword arguments:
similars -- Array que representa las transacciones similares al jugador
db -- Objeto de conexion a la BD.
"""
for similar in similars:
id_player = str(int(str(similar.player_id)))
id_similar = str(int(str(similar.date_buy_id)))
if(db.transactions.find(
{"id_player": ObjectId(id_player.zfill(24))},
{"date_buy_id": ObjectId(id_similar.zfill(24))}
).count() == 0):
db.transactions.insert_one(similar.to_db_collection())
else:
pass
# print("\t-Ya existe-")
# db.transactions.replace_one(
# {"$and": [{"id_player": ObjectId(id_player.zfill(24))},
# {"date_buy_id": ObjectId(id_similar.zfill(24))}]},
# similar.to_db_collection())
def updateProgressions(player_id, progression_id, db):
""" Actualiza/añade una progresion al jugador
Keyword arguments:
player_id -- Id del jugador con el que cargamos su página
progression_id -- Id de la progresion
db -- Objeto de conexion a la BD.
"""
if(db.players.find_one({"progressions": ObjectId(progression_id)}) is None):
# print("Inserta prog")
db.players.update_one(
{"_id": ObjectId(player_id.zfill(24))},
{'$push': {"progressions": ObjectId(progression_id)}}
)
# else:
# print("Insertado")
def updateAuctions(player_id, auction_id, db):
""" Actualiza/añade una subasta al jugador
Keyword arguments:
player_id -- Id del jugador con el que cargamos su página
auction_id -- Id de Subasta
db -- Objeto de conexion a la BD.
"""
if(db.players.find_one({"auctions": ObjectId(auction_id)}) is None):
db.players.update_one(
{"_id": ObjectId(player_id.zfill(24))},
{'$push': {"auctions": ObjectId(auction_id)}}
)
# else:
# print("Insertado")
|
{"/ibm_auto_manager/trainer/team_page.py": ["/ibm_auto_manager/common/util.py", "/ibm_auto_manager/connection/login_page.py", "/ibm_auto_manager/common/__init__.py"], "/ibm_auto_manager/app.py": ["/ibm_auto_manager/common/util.py"], "/ibm_auto_manager/general/dashboard_page.py": ["/ibm_auto_manager/common/util.py", "/ibm_auto_manager/connection/login_page.py"], "/ibm_auto_manager/scout/market_page.py": ["/ibm_auto_manager/common/__init__.py", "/ibm_auto_manager/common/util.py", "/ibm_auto_manager/connection/login_page.py"], "/ibm_auto_manager/scout/auction.py": ["/ibm_auto_manager/common/__init__.py"], "/ibm_auto_manager/scout/player_page.py": ["/ibm_auto_manager/common/__init__.py", "/ibm_auto_manager/common/util.py", "/ibm_auto_manager/connection/login_page.py"], "/ibm_auto_manager/scout/league_page.py": ["/ibm_auto_manager/common/util.py", "/ibm_auto_manager/connection/login_page.py", "/ibm_auto_manager/general/dashboard_page.py", "/ibm_auto_manager/trainer/team_page.py"], "/ibm_auto_manager/dt/automation.py": ["/ibm_auto_manager/connection/login_page.py", "/ibm_auto_manager/common/util.py"], "/ibm_auto_manager/scout/roster_page.py": ["/ibm_auto_manager/connection/login_page.py"], "/ibm_auto_manager/scout/transaction.py": ["/ibm_auto_manager/common/__init__.py"], "/ibm_auto_manager/scout/player.py": ["/ibm_auto_manager/common/__init__.py"]}
|
16,655,517
|
BorjaG90/ibm-auto-manager
|
refs/heads/develop
|
/ibm_auto_manager/general/dashboard_page.py
|
# -*- coding: utf-8 -*-
__author__ = 'Borja Gete'
__email__ = 'borjagete90@outlook.es'
from bs4 import BeautifulSoup
from bson import ObjectId
from ibm_auto_manager.common.util import show
from ibm_auto_manager.connection.login_page import login
from ibm_auto_manager.general import profile
def get_profile_data(auth, db):
""" Obtenemos los datos del perfil del usuario actual
Devolvemos el id del equipo
Keyword arguments:
auth -- Cadena de autenticacion a la web.
db -- Objeto de conexion a la BD.
"""
id_team, user, team, money, color_prim, color_sec = analyze_init(auth, db)
id_user, seats, fans, ranking, streak = analyze_team_page(auth, db, id_team)
v_profile = profile.Profile(
id_user, user, id_team, team, money, color_prim,
color_sec, seats, fans, ranking, streak
)
if (db.profiles.find_one({"team_id": ObjectId(id_team.zfill(24))}) is not None):
db.profiles.replace_one(
{"team_id": ObjectId(id_team.zfill(24))}, v_profile.to_db_collection())
else:
db.profiles.insert_one(v_profile.to_db_collection())
print(show("profile") + " > Perfil actualizado")
return id_team
def analyze_init(auth, db):
""" Analizamos la pagina de inicio
Keyword arguments:
auth -- Cadena de autenticacion a la web.
db -- Objeto de conexion a la BD.
"""
session = login(auth)
url = "http://es.ibasketmanager.com/inicio.php"
r = session.get(url)
load_status = 0
while load_status != 200:
load_status = r.status_code
print(show("profile") + " > Analizando perfil inicial")
soup = BeautifulSoup(r.content, "html.parser")
a = soup.find_all("a", {"class": "color_skin"})
camisetas = soup.find_all("div", {"class": "camiseta"}, style=True)
color_prim = camisetas[0]["style"].split(":")[1].strip()
color_sec = camisetas[1]["style"].split(":")[1].strip()
# print(a)
username = a[0].text
id_team = a[2]["href"].split("=")[1].strip()
team_name = a[2].text.strip()
money = a[3].text.replace('€','').replace('.','').strip()
return [id_team, username, team_name, money, color_prim, color_sec]
def analyze_team_page(auth, db, id_team):
""" Analizamos la pagina del equipo
Keyword arguments:
auth -- Cadena de autenticacion a la web.
db -- Objeto de conexion a la BD.
"""
session = login(auth)
url = "http://es.ibasketmanager.com/equipo.php?id=" + id_team
r = session.get(url)
load_status = 0
while load_status != 200:
load_status = r.status_code
print(show("profile") + " > Analizando perfil del equipo")
soup = BeautifulSoup(r.content, "html.parser")
trs2 = soup.find_all("tr", {"class": "tipo2"})
id_user = trs2[0].find("a")["href"].split("=")[1]
streak = trs2[2].find_all("td")[1].text
club_seats = trs2[3].find_all("td")[1].text.replace(".","").strip()
ranking = trs2[4].find_all("td")[1].text.replace("Ranking","").strip()
trs1 = soup.find_all("tr", {"class": "tipo1"})
fans = trs1[3].find_all("td")[1].text.replace(".","").strip()
return [id_user, club_seats, fans, ranking, streak]
def get_season(auth):
""" Obtenemos la temporada actual en juego
Keyword arguments:
auth -- Cadena de autenticacion a la web.
"""
session = login(auth)
# Obtenemos id de la liga actual
url = "http://es.ibasketmanager.com/inicio.php"
r = session.get(url)
load_status = 0
while load_status != 200:
load_status = r.status_code
soup = BeautifulSoup(r.content, "html.parser")
menu = soup.find("div", {"id": "menu1"})
id_league = menu.find_all("div")[2].find("a")["href"].split("=")[1].strip()
# Obtenemos la temporada
url = "http://es.ibasketmanager.com/liga.php?id_liga=" + str(id_league)
r = session.get(url)
load_status = 0
while load_status != 200:
load_status = r.status_code
soup = BeautifulSoup(r.content, "html.parser")
menu = soup.find_all("div", {"class": "caja2 final"})[0]
season = menu.find_all("div", {"class": "selector"})[2].find("span").text
return season
|
{"/ibm_auto_manager/trainer/team_page.py": ["/ibm_auto_manager/common/util.py", "/ibm_auto_manager/connection/login_page.py", "/ibm_auto_manager/common/__init__.py"], "/ibm_auto_manager/app.py": ["/ibm_auto_manager/common/util.py"], "/ibm_auto_manager/general/dashboard_page.py": ["/ibm_auto_manager/common/util.py", "/ibm_auto_manager/connection/login_page.py"], "/ibm_auto_manager/scout/market_page.py": ["/ibm_auto_manager/common/__init__.py", "/ibm_auto_manager/common/util.py", "/ibm_auto_manager/connection/login_page.py"], "/ibm_auto_manager/scout/auction.py": ["/ibm_auto_manager/common/__init__.py"], "/ibm_auto_manager/scout/player_page.py": ["/ibm_auto_manager/common/__init__.py", "/ibm_auto_manager/common/util.py", "/ibm_auto_manager/connection/login_page.py"], "/ibm_auto_manager/scout/league_page.py": ["/ibm_auto_manager/common/util.py", "/ibm_auto_manager/connection/login_page.py", "/ibm_auto_manager/general/dashboard_page.py", "/ibm_auto_manager/trainer/team_page.py"], "/ibm_auto_manager/dt/automation.py": ["/ibm_auto_manager/connection/login_page.py", "/ibm_auto_manager/common/util.py"], "/ibm_auto_manager/scout/roster_page.py": ["/ibm_auto_manager/connection/login_page.py"], "/ibm_auto_manager/scout/transaction.py": ["/ibm_auto_manager/common/__init__.py"], "/ibm_auto_manager/scout/player.py": ["/ibm_auto_manager/common/__init__.py"]}
|
16,655,518
|
BorjaG90/ibm-auto-manager
|
refs/heads/develop
|
/ibm_auto_manager/app.py
|
######################
# IBM-Auto-Manager #
######################
# -*- coding: utf-8 -*-
__author__ = 'Borja Gete'
__email__ = 'borjagete90@outlook.es'
import os
import json
import getpass
from bs4 import BeautifulSoup
from pymongo import MongoClient
from ibm_auto_manager.common.util import cls, show
from ibm_auto_manager.general import dashboard_page
from ibm_auto_manager.scout import market_page, league_page
from ibm_auto_manager.trainer import team_page
from ibm_auto_manager.dt import automation
# ----- Functions -----
def config():
""" Obtenemos la configuración de la app desde el fichero solicitado.
En caso de que no exista, solictamos los datos necesarios y lo creamos."""
settings = {}
if os.path.isfile("./ibm_auto_manager/config/settings.json"):
print(show("config") + "Encontrado fichero configuración")
with open("./ibm_auto_manager/config/settings.json", 'r') as settings_file:
settings = json.load(settings_file)
settings_file.close
print(show("config") + "Configuración cargada con éxito")
else :
print(show("config") + "! No se encuentra fichero de configuración")
print(show("config") + "! Se va a proceder a generar el fichero")
print(show("config") + "! Se realizaran múltiples preguntas")
print("\n" + show("config") + "Configuración de conexión")
settings["mongodb"] = ""
while settings["mongodb"] == "":
settings["mongodb"] = input(" Introduce la cadena de conexión a la BD: ")
settings["proxy"] = input(" Introduce la cadena del proxy (opcional): ")
print("\n" + show("config") + "Configuración de usuario")
settings["user"] = {}
settings["user"]["alias"] = ""
while settings["user"]["alias"] == "":
settings["user"]["alias"] = input(" Introduce tu Alias del juego: ")
settings["user"]["password"] = ""
while settings["user"]["password"] == "":
settings["user"]["password"] = getpass.getpass(" Introduce tu Password: ")
print("\n" + show("config") + "Configuración de automatización (Tienda)")
settings["shop"] = {}
settings["shop"]["llaveros"] = input(" Introduce cantidad de Llaveros (6400): ") or "6400"
settings["shop"]["banderolas"] = input(" Introduce cantidad de Banderolas (6400): ") or "6400"
settings["shop"]["balones"] = input(" Introduce cantidad de Balones (6400): ") or "6400"
settings["shop"]["camisetas"] = input(" Introduce cantidad de Camisetas (6400): ") or "6400"
settings["shop"]["zapatillas"] = input(" Introduce cantidad de Zapatillas (6400): ") or "6400"
print("\n" + show("config") + "Configuración de automatización (Catering)")
settings["catering"] = {}
settings["catering"]["refrescos"] = input(" Introduce cantidad de Refrescos (2000): ") or "2000"
settings["catering"]["frankfurts"] = input(" Introduce cantidad de Frankfurts (1000): ") or "1000"
settings["catering"]["pipas"] = input(" Introduce cantidad de Pipas (1000): ") or "1000"
settings["catering"]["bocadillo"] = input(" Introduce cantidad de Bocadillos (1000): ") or "1000"
settings["catering"]["cerveza"] = input(" Introduce cantidad de Cerveza (1250): ") or "1250"
settings["catering"]["patatas"] = input(" Introduce cantidad de Bolsa de Patatas (1000): ") or "1000"
settings["catering"]["berberechos"] = input(" Introduce cantidad de Berberechos (1000): ") or "1000"
settings["catering"]["canapes"] = input(" Introduce cantidad de Canapés (1250): ") or "1250"
settings["catering"]["arroz"] = input(" Introduce cantidad de Arroz Frito (1000): ") or "1000"
settings["catering"]["vino"] = input(" Introduce cantidad de Vino (2000): ") or "2000"
settings["catering"]["spaguetti"] = input(" Introduce cantidad de Spaguetti (1250): ") or "120"
settings["catering"]["ensalada"] = input(" Introduce cantidad de Ensalada (1000): ") or "1000"
settings["catering"]["cava"] = input(" Introduce cantidad de Cava (1000): ") or "1000"
settings["catering"]["gnocchi"] = input(" Introduce cantidad de Gnocci (1250): ") or "1250"
settings["catering"]["sushi"] = input(" Introduce cantidad de Sushi (1000): ") or "1000"
settings["catering"]["bistec"] = input(" Introduce cantidad de Bistec (1250): ") or "1250"
settings["catering"]["risotto"] = input(" Introduce cantidad de Risotto (1250): ") or "1250"
settings["catering"]["rodaballo"] = input(" Introduce cantidad de Rodaballo (1750): ") or "1750"
settings["catering"]["solomillo"] = input(" Introduce cantidad de Solomillo (1000): ") or "1000"
settings["catering"]["caviar"] = input(" Introduce cantidad de Caviar (1000): ") or "1000"
# Creamos el fichero de configuración
print(show("config") + "Fichero de configuración creado con éxito")
with open("./ibm_auto_manager/config/settings.json", "w") as settings_file:
json.dump(settings, settings_file, indent=4, ensure_ascii=False)
settings_file.close
print(show("config") + "Configuración cargada con éxito")
# Aplicamos la configuración
if settings["proxy"] != "":
os.environ["http_proxy"] = settings["proxy"]
os.environ["HTTP_PROXY"] = settings["proxy"]
os.environ["https_proxy"] = settings["proxy"]
os.environ["HTTPS_PROXY"] = settings["proxy"]
print(show("config") + "Configuración aplicada con éxito")
return settings
def connect():
""" Realizamos las configuraciones y conexiones necesarias para el
funcionamiento de la aplicación y las devolvemos en un diccionario"""
cls()
# Obtenemos la configuración
settings = config()
cls()
# Login
auth = {
"alias": settings["user"]["alias"],
"pass": settings["user"]["password"],
"dest": None
}
# Database
mongoClient = MongoClient(settings["mongodb"])
db = mongoClient['ibm-auto-manager']
connection = {"settings": settings, "auth": auth, "db": db }
return connection
# =====================
# -- Start --
# =====================
def run(arg=""):
connection = connect()
if arg == "--market" or arg == "-m" or arg == "market":
""" Ejecución exclusiva del análisis de mercado """
print("********IBM Auto Manager**********")
print("\nAnalizando mercado")
market_page.enter_market(connection["auth"], connection["db"])
elif arg == "--profile" or arg == "-p" or arg == "profile":
""" Ejecución exclusiva del análisis del perfil """
print("********IBM Auto Manager**********")
print("\nAnalizando perfil")
id_team = dashboard_page.get_profile_data(
connection["auth"], connection["db"])
team_page.enter_team(connection["auth"], connection["db"], id_team)
elif arg == "--teams" or arg == "-t" or arg == "teams":
""" Ejecución de analisis de equipos de la parte alta de la competición """
print("********IBM Auto Manager**********")
print("\nAnalizando competición")
league_page.enter_competition(connection["auth"], connection["db"], "m")
elif arg == "--teams-elite" or arg == "-te" or arg == "teams-elite":
""" Ejecución de analisis de equipos de elite de la competición """
print("********IBM Auto Manager**********")
print("\nAnalizando competición")
league_page.enter_competition(connection["auth"], connection["db"], "e")
elif arg == "--teams-full" or arg == "-tf" or arg == "teams-full":
""" Ejecución de analisis de todos los equipos de la competición"""
print("********IBM Auto Manager**********")
print("\nAnalizando competición")
league_page.enter_competition(connection["auth"], connection["db"], "f")
elif arg == "--teams-mid" or arg == "-tm" or arg == "teams-mid":
""" Ejecución de analisis delos equipos de 3 y 4 de la competición"""
print("********IBM Auto Manager**********")
print("\nAnalizando competición")
league_page.enter_competition(connection["auth"], connection["db"], "2")
elif arg == "--teams-low" or arg == "-tl" or arg == "teams-low":
""" Ejecución de analisis delos equipos de 3 y 4 de la competición"""
print("********IBM Auto Manager**********")
print("\nAnalizando competición")
league_page.enter_competition(connection["auth"], connection["db"], "3")
elif arg == "--auto-bid" or arg == "-b" or arg == "auto-bid":
""" Ejecución de auto_apuesta en la subasta de un jugador"""
print("********IBM Auto Manager**********")
print("\nAnalizando subasta")
automation.auto_bid(connection["auth"])
elif arg == "--auto-offer" or arg == "-o" or arg == "auto-offer":
""" Ejecución de auto_oferta en la renovación de un jugador"""
print("********IBM Auto Manager**********")
print("\nAnalizando contrato")
automation.auto_offer(connection["auth"])
elif arg == "":
""" Ejecución normal """
# Menu
while True:
cls()
print("********IBM Auto Manager**********")
print("\n[m] Analizar mercado")
print("\n[p] Analizar perfil") # Provisional
print("\n[t] Analizar competicion")
print("\n[b] Realizar apuesta en subasta")
print("\n[o] Realizar oferta de renovación")
print("\n[0] Salir del programa\n")
opcion = input("Introduce una opción: > ")
if opcion == "b":
automation.auto_bid(connection["auth"])
if opcion == "o":
automation.auto_offer(connection["auth"])
if opcion == "m":
market_page.enter_market(connection["auth"], connection["db"])
if opcion == "p":
id_team = int(dashboard_page.get_profile_data(
connection["auth"], connection["db"]))
team_page.enter_team(connection["auth"], connection["db"], id_team)
if opcion == "m":
while True:
cls()
print("********IBM Auto Manager**********")
print("****Análisis de Competición******")
print("\n[e] Elite / 2 divisiones")
print("\n[m] Parte alta / 4 divisiones")
print("\n[f] Toda la competicion")
print("\n[0] Salir de la opcion\n")
opcion = input("Introduce las divisiones a analizar: > ")
if opcion == "m":
league_page.enter_competition(
connection["auth"], connection["db"], "m")
elif opcion == "e":
league_page.enter_competition(
connection["auth"], connection["db"], "e")
elif opcion == "f":
league_page.enter_competition(
connection["auth"], connection["db"], "f")
elif opcion == "0":
cls()
break
else:
print("Opción incorrecta")
elif opcion == "0":
print("Cerrando programa!")
cls()
break
else:
print("Opción incorrecta")
input("\nPulse para continuar...")
else:
print("No se reconoce este comando")
input("Pulse para salir...")
cls()
|
{"/ibm_auto_manager/trainer/team_page.py": ["/ibm_auto_manager/common/util.py", "/ibm_auto_manager/connection/login_page.py", "/ibm_auto_manager/common/__init__.py"], "/ibm_auto_manager/app.py": ["/ibm_auto_manager/common/util.py"], "/ibm_auto_manager/general/dashboard_page.py": ["/ibm_auto_manager/common/util.py", "/ibm_auto_manager/connection/login_page.py"], "/ibm_auto_manager/scout/market_page.py": ["/ibm_auto_manager/common/__init__.py", "/ibm_auto_manager/common/util.py", "/ibm_auto_manager/connection/login_page.py"], "/ibm_auto_manager/scout/auction.py": ["/ibm_auto_manager/common/__init__.py"], "/ibm_auto_manager/scout/player_page.py": ["/ibm_auto_manager/common/__init__.py", "/ibm_auto_manager/common/util.py", "/ibm_auto_manager/connection/login_page.py"], "/ibm_auto_manager/scout/league_page.py": ["/ibm_auto_manager/common/util.py", "/ibm_auto_manager/connection/login_page.py", "/ibm_auto_manager/general/dashboard_page.py", "/ibm_auto_manager/trainer/team_page.py"], "/ibm_auto_manager/dt/automation.py": ["/ibm_auto_manager/connection/login_page.py", "/ibm_auto_manager/common/util.py"], "/ibm_auto_manager/scout/roster_page.py": ["/ibm_auto_manager/connection/login_page.py"], "/ibm_auto_manager/scout/transaction.py": ["/ibm_auto_manager/common/__init__.py"], "/ibm_auto_manager/scout/player.py": ["/ibm_auto_manager/common/__init__.py"]}
|
16,655,519
|
BorjaG90/ibm-auto-manager
|
refs/heads/develop
|
/ibm_auto_manager/scout/league_page.py
|
# -*- coding: utf-8 -*-
__author__ = 'Borja Gete'
__email__ = 'borjagete90@outlook.es'
from bs4 import BeautifulSoup
from ibm_auto_manager.common.util import show
from ibm_auto_manager.connection.login_page import login
from ibm_auto_manager.general.dashboard_page import get_season
from ibm_auto_manager.trainer.team_page import enter_team
def enter_competition(auth, db, option):
""" Recorremos las páginas de divisiones y ligas
Keyword arguments:
auth -- Cadena de autenticacion a la web.
db -- Objeto de conexion a la BD.
option -- opción de divisiones a analizar
"""
season = get_season(auth)
p_division = 1
p_group = 1
if (option != "2" and option != "3"):
# División 1
print(show("division") + " > Analizando división " + str(p_division))
league_url = 'http://es.ibasketmanager.com/liga.php?temporada=' + \
str(season) + '&division=' + str(p_division) + '&grupo=' + str(p_group)
teams_ids = analyze_standings(league_url, auth)
for team_id in teams_ids:
enter_team(auth, db, team_id, False)
# División 2
p_division = 2
print(show("division") + " > Analizando división " + str(p_division))
for p_group in range(1, 5):
print(show("division") + " > Analizando división " + str(p_division) + \
" Grupo: " + str(p_group))
league_url = 'http://es.ibasketmanager.com/liga.php?temporada=' + \
str(season) + '&division=' + str(p_division) + '&grupo=' + str(p_group)
teams_ids = analyze_standings(league_url, auth)
for team_id in teams_ids:
enter_team(auth, db, team_id, False)
if (option == "m" or option == "f" or option == "2"):
# División 3
p_division = 3
print(show("division") + " > Analizando división " + str(p_division))
for p_group in range(1, 17):
print(show("division") + " > Analizando división " + str(p_division) + \
" Grupo: " + str(p_group))
league_url = 'http://es.ibasketmanager.com/liga.php?temporada=' + \
str(season) + '&division=' + str(p_division) + '&grupo=' + str(p_group)
teams_ids = analyze_standings(league_url, auth)
for team_id in teams_ids:
enter_team(auth, db, team_id, False)
# División 4
p_division = 4
print(show("division") + " > Analizando división " + str(p_division))
for p_group in range(1, 65):
print(show("division") + " > Analizando división " + str(p_division) + \
" Grupo: " + str(p_group))
league_url = 'http://es.ibasketmanager.com/liga.php?temporada=' + \
str(season) + '&division=' + str(p_division) + '&grupo=' + str(p_group)
teams_ids = analyze_standings(league_url, auth)
for team_id in teams_ids:
enter_team(auth, db, team_id, False)
if (option == "f" or option == "3"):
# División 5
p_division = 5
print(show("division") + " > Analizando división " + str(p_division))
for p_group in range(1, 51): # Es posible que no haya más equipos
print(show("division") + " > Analizando división " + str(p_division) + \
" Grupo: " + str(p_group))
league_url = 'http://es.ibasketmanager.com/liga.php?temporada=' + \
str(season) + '&division=' + str(p_division) + '&grupo=' + str(p_group)
teams_ids = analyze_standings(league_url, auth)
for team_id in teams_ids:
enter_team(auth, db, team_id, False)
def analyze_standings(league_url, auth):
""" Analizamos los equipos de la liga pasada por parametro.
Devolvemos los ids de los equipos inscritos a esa liga
Keyword arguments:
league_url -- URL de la liga
auth -- Cadena de autenticacion a la web.
"""
session = login(auth)
# print(league_url)
r = session.get(league_url)
load_status = 0
while load_status != 200:
load_status = r.status_code
soup = BeautifulSoup(r.content, 'html.parser')
teams_str_a = soup.find_all('table')[0].find_all('a')
teams_str_b = soup.find_all('table')[1].find_all('a')
# Obtenemos los ids de los equipos que conforman esa liga
teams_ids = []
for team_str in teams_str_a + teams_str_b:
# print(team_str['href'][team_str['href'].find('=')+1:])
teams_ids.append(team_str['href'][team_str['href'].find('=')+1:])
return teams_ids
|
{"/ibm_auto_manager/trainer/team_page.py": ["/ibm_auto_manager/common/util.py", "/ibm_auto_manager/connection/login_page.py", "/ibm_auto_manager/common/__init__.py"], "/ibm_auto_manager/app.py": ["/ibm_auto_manager/common/util.py"], "/ibm_auto_manager/general/dashboard_page.py": ["/ibm_auto_manager/common/util.py", "/ibm_auto_manager/connection/login_page.py"], "/ibm_auto_manager/scout/market_page.py": ["/ibm_auto_manager/common/__init__.py", "/ibm_auto_manager/common/util.py", "/ibm_auto_manager/connection/login_page.py"], "/ibm_auto_manager/scout/auction.py": ["/ibm_auto_manager/common/__init__.py"], "/ibm_auto_manager/scout/player_page.py": ["/ibm_auto_manager/common/__init__.py", "/ibm_auto_manager/common/util.py", "/ibm_auto_manager/connection/login_page.py"], "/ibm_auto_manager/scout/league_page.py": ["/ibm_auto_manager/common/util.py", "/ibm_auto_manager/connection/login_page.py", "/ibm_auto_manager/general/dashboard_page.py", "/ibm_auto_manager/trainer/team_page.py"], "/ibm_auto_manager/dt/automation.py": ["/ibm_auto_manager/connection/login_page.py", "/ibm_auto_manager/common/util.py"], "/ibm_auto_manager/scout/roster_page.py": ["/ibm_auto_manager/connection/login_page.py"], "/ibm_auto_manager/scout/transaction.py": ["/ibm_auto_manager/common/__init__.py"], "/ibm_auto_manager/scout/player.py": ["/ibm_auto_manager/common/__init__.py"]}
|
16,655,520
|
BorjaG90/ibm-auto-manager
|
refs/heads/develop
|
/ibm_auto_manager/general/profile.py
|
# -*- coding: utf-8 -*-
__author__ = 'Borja Gete'
__email__ = 'borjagete90@outlook.es'
from bson import ObjectId
from datetime import datetime
class Profile:
def __init__(self,
id_user,
username,
id_team,
team_name,
money,
color_prim,
color_sec,
club_seats, # socios
fans, # aficionados
ranking_team,
streak # racha de partidos
):
self._id = ObjectId(id_user.zfill(24))
self.username = str(username)
self.team_id = ObjectId(id_team.zfill(24))
self.team_name = str(team_name)
self.money = int(money)
self.color_prim = str(color_prim)
self.color_sec = str(color_sec)
self.club_seats = int(club_seats)
self.fans = int(fans)
self.ranking_team = int(ranking_team)
self.streak = int(streak)
def to_db_collection(self):
"""Devuelve los datos del perfil en un formato legible de MongoDB."""
return {
"_id": self._id,
"username": self.username,
"team_id": self.team_id,
"team_name": self.team_name,
"money": self.money,
"color_prim": self.color_prim,
"color_sec": self.color_sec,
"club_seats": self.club_seats,
"fans": self.fans,
"ranking_team": self.ranking_team,
"streak": self.streak,
"_date": datetime.now()
}
|
{"/ibm_auto_manager/trainer/team_page.py": ["/ibm_auto_manager/common/util.py", "/ibm_auto_manager/connection/login_page.py", "/ibm_auto_manager/common/__init__.py"], "/ibm_auto_manager/app.py": ["/ibm_auto_manager/common/util.py"], "/ibm_auto_manager/general/dashboard_page.py": ["/ibm_auto_manager/common/util.py", "/ibm_auto_manager/connection/login_page.py"], "/ibm_auto_manager/scout/market_page.py": ["/ibm_auto_manager/common/__init__.py", "/ibm_auto_manager/common/util.py", "/ibm_auto_manager/connection/login_page.py"], "/ibm_auto_manager/scout/auction.py": ["/ibm_auto_manager/common/__init__.py"], "/ibm_auto_manager/scout/player_page.py": ["/ibm_auto_manager/common/__init__.py", "/ibm_auto_manager/common/util.py", "/ibm_auto_manager/connection/login_page.py"], "/ibm_auto_manager/scout/league_page.py": ["/ibm_auto_manager/common/util.py", "/ibm_auto_manager/connection/login_page.py", "/ibm_auto_manager/general/dashboard_page.py", "/ibm_auto_manager/trainer/team_page.py"], "/ibm_auto_manager/dt/automation.py": ["/ibm_auto_manager/connection/login_page.py", "/ibm_auto_manager/common/util.py"], "/ibm_auto_manager/scout/roster_page.py": ["/ibm_auto_manager/connection/login_page.py"], "/ibm_auto_manager/scout/transaction.py": ["/ibm_auto_manager/common/__init__.py"], "/ibm_auto_manager/scout/player.py": ["/ibm_auto_manager/common/__init__.py"]}
|
16,655,521
|
BorjaG90/ibm-auto-manager
|
refs/heads/develop
|
/ibm_auto_manager/trainer/team.py
|
# -*- coding: utf-8 -*-
__author__ = 'Borja Gete'
__email__ = 'borjagete90@outlook.es'
from bson import ObjectId
from datetime import datetime
class Team:
""" Representa un equipo """
def __init__(self,
id_team,
name,
id_user,
user,
arena,
division,
group,
clasification,
streak # racha de partidos
):
self._id = ObjectId(id_team.zfill(24))
self.id_user = ObjectId(id_user.zfill(24))
self.name = name
self.user = user
self.arena = arena
self.division = int(division)
self.group = int(group)
self.clasification = int(clasification)
self.streak = int(streak)
def to_db_collection(self):
"""Devuelve los datos del perfil en un formato legible de MongoDB."""
return {
"_id": self._id,
"name": self.name,
"id_user": self.id_user,
"user": self.user,
"arena": self.arena,
"division": self.division,
"group": self.group,
"clasification": self.clasification,
"streak": self.streak,
"_date": datetime.now()
}
|
{"/ibm_auto_manager/trainer/team_page.py": ["/ibm_auto_manager/common/util.py", "/ibm_auto_manager/connection/login_page.py", "/ibm_auto_manager/common/__init__.py"], "/ibm_auto_manager/app.py": ["/ibm_auto_manager/common/util.py"], "/ibm_auto_manager/general/dashboard_page.py": ["/ibm_auto_manager/common/util.py", "/ibm_auto_manager/connection/login_page.py"], "/ibm_auto_manager/scout/market_page.py": ["/ibm_auto_manager/common/__init__.py", "/ibm_auto_manager/common/util.py", "/ibm_auto_manager/connection/login_page.py"], "/ibm_auto_manager/scout/auction.py": ["/ibm_auto_manager/common/__init__.py"], "/ibm_auto_manager/scout/player_page.py": ["/ibm_auto_manager/common/__init__.py", "/ibm_auto_manager/common/util.py", "/ibm_auto_manager/connection/login_page.py"], "/ibm_auto_manager/scout/league_page.py": ["/ibm_auto_manager/common/util.py", "/ibm_auto_manager/connection/login_page.py", "/ibm_auto_manager/general/dashboard_page.py", "/ibm_auto_manager/trainer/team_page.py"], "/ibm_auto_manager/dt/automation.py": ["/ibm_auto_manager/connection/login_page.py", "/ibm_auto_manager/common/util.py"], "/ibm_auto_manager/scout/roster_page.py": ["/ibm_auto_manager/connection/login_page.py"], "/ibm_auto_manager/scout/transaction.py": ["/ibm_auto_manager/common/__init__.py"], "/ibm_auto_manager/scout/player.py": ["/ibm_auto_manager/common/__init__.py"]}
|
16,655,522
|
BorjaG90/ibm-auto-manager
|
refs/heads/develop
|
/ibm_auto_manager/trainer/team_page.py
|
# -*- coding: utf-8 -*-
__author__ = 'Borja Gete'
__email__ = 'borjagete90@outlook.es'
import datetime
import time
import re
from bs4 import BeautifulSoup
from bson import ObjectId
from ibm_auto_manager.common.util import show
from ibm_auto_manager.common import text
from ibm_auto_manager.connection.login_page import login
from ibm_auto_manager.scout import roster_page, player_page
from ibm_auto_manager.trainer import team
def enter_team(auth, db, team_id, get_prog = True):
""" Recorremos las páginas de plantilla y cantera del equipo
y registra los atributos de los jugadores para
la posterior comprobación de la progresión
Keyword arguments:
auth -- Cadena de autenticacion a la web.
db -- Objeto de conexion a la BD.
team_id -- Id del equipo
get_prog --
"""
session = login(auth)
# http://es.ibasketmanager.com/equipo.php?id=1643
team_url = "http://es.ibasketmanager.com/" + \
"equipo.php?id=" + str(team_id)
r = session.get(team_url)
load_status = 0
while load_status != 200:
load_status = r.status_code
# Analizo el progreso del equipo
print(show("team_info") + " > Analizando Equipo: " + str(team_id))
team_info = analyze_team(team_id, r.content)
print(show("team") + " -> Equipo: " + str(team_id))
insert_team_data(team_info, db)
# Seniors
print(show("roster") + " -> Plantilla: " + str(team_id))
players_ids = roster_page.enter_senior_roster(team_id, auth, session)
insert_players_data(auth, db, players_ids, get_prog, session)
update_players(players_ids, team_id, db, "S")
# Juniors
print(show("juniors") + " -> Cantera: " + str(team_id))
juniors_ids = roster_page.enter_junior_roster(team_id, auth, session)
insert_players_data(auth, db, juniors_ids, get_prog, session)
update_players(juniors_ids, team_id, db, "J")
def analyze_team(team_id, html_content):
""" Obtenemos los datos relativos al equipo"""
soup = BeautifulSoup(html_content, 'html.parser')
caja50 = soup.find_all("div", {"class": "caja50"})
th = caja50[0].find("table").find("th")
data = caja50[0].find("table").find_all("td")
name = th.text
# print("Name: " + name)
user = data[1].text
# print("User: " + user)
if user != 'System bot':
id_user = data[1].find_all('a')[0]['href'][
data[1].find_all('a')[0]['href'].find('=')+1:]
# print("IdUser: " + id_user)
else:
id_user = str(0)
arena = data[3].find_all('a')[0].text
# print("Arena: " + arena)
division = re.search("([\d])+", data[5].text.split('/')[0])[0]
group = re.search("([\d])+", data[5].text.split('/')[1])[0]
# print("League: " + division + "/" + group )
clasification = data[7].text
# print("Clasification: " + clasification)
streak = data[9].text
# print("Racha: " + streak)
return team.Team(team_id, name, id_user, user, arena, division, group, \
clasification, streak)
def insert_players_data(auth, db, players_ids, get_prog = True, session = None):
""" Realizamos el bucle de inserción de los ids
Keyword arguments:
auth -- Cadena de autenticacion a la web.
db -- Objeto de conexion a la BD.
players_ids -- Array de Ids de los jugadores
"""
for player_id in players_ids:
player = player_page.get_player_data(player_id, auth, session)
player_page.insert_player(player, player_id, db)
# Si recibimos la orden de guardar la progresión de los jugadores
if(get_prog):
future_id = ObjectId((str(int(str(player_id))) + text.get_date_str(datetime.datetime.now(), False)).zfill(24))
# print(future_id)
if(db.progressions.find_one({"_id": future_id}) is None):
prog_id = db.progressions.insert_one(
player[1].to_db_collection_prog()).inserted_id
# print(show("progression") + ": " + str(prog_id))
player_page.updateProgressions(player_id, future_id, db)
def insert_team_data(team, db):
""" Introduce el equipo en la BD
Keyword arguments:
team -- objeto que representa los datos del equipo
db -- Objeto de conexion a la BD.
"""
if team is not None:
# Comprobamos si el equipo ya existe y en consecuencia
# lo insertamos/actualizamos
# print(str(player_id) + ' - '+ str(player[0].id_player))
# print(db.players.find_one({"id_player": player_id}))
if (db.teams.find_one({"_id": team._id}) is not None):
# print(show("player") + " Actualizar P: " + str(player[0]))
db.teams.update_one(
{"_id": team._id},
{'$set': team.to_db_collection()}
)
else:
# print(show("player") + " Insertar P: " + str(player[0]))
db.teams.insert_one(team.to_db_collection())
def update_players(ids, team_id, db, option):
""" Actualiza/añade los jugadores del equipo
Keyword arguments:
ids -- Ids de los jugadores
team_id -- Id del equipo
db -- Objeto de conexion a la BD.
option -- Plantilla senior o junior
"""
if option == "S":
db.teams.update_one(
{"_id": ObjectId(team_id.zfill(24))},
{"$set": {"seniors": []}}
)
for id in ids:
# print(team_id)
db.teams.update_one(
{"_id": ObjectId(team_id.zfill(24))},
{"$push": {"seniors": ObjectId(id.zfill(24))}}
)
else:
db.teams.update_one(
{"_id": ObjectId(team_id.zfill(24))},
{'$set': {"juniors": []}}
)
for id in ids:
# print(id)
db.teams.update_one(
{"_id": ObjectId(team_id.zfill(24))},
{'$push': {"juniors": ObjectId(id.zfill(24))}}
)
|
{"/ibm_auto_manager/trainer/team_page.py": ["/ibm_auto_manager/common/util.py", "/ibm_auto_manager/connection/login_page.py", "/ibm_auto_manager/common/__init__.py"], "/ibm_auto_manager/app.py": ["/ibm_auto_manager/common/util.py"], "/ibm_auto_manager/general/dashboard_page.py": ["/ibm_auto_manager/common/util.py", "/ibm_auto_manager/connection/login_page.py"], "/ibm_auto_manager/scout/market_page.py": ["/ibm_auto_manager/common/__init__.py", "/ibm_auto_manager/common/util.py", "/ibm_auto_manager/connection/login_page.py"], "/ibm_auto_manager/scout/auction.py": ["/ibm_auto_manager/common/__init__.py"], "/ibm_auto_manager/scout/player_page.py": ["/ibm_auto_manager/common/__init__.py", "/ibm_auto_manager/common/util.py", "/ibm_auto_manager/connection/login_page.py"], "/ibm_auto_manager/scout/league_page.py": ["/ibm_auto_manager/common/util.py", "/ibm_auto_manager/connection/login_page.py", "/ibm_auto_manager/general/dashboard_page.py", "/ibm_auto_manager/trainer/team_page.py"], "/ibm_auto_manager/dt/automation.py": ["/ibm_auto_manager/connection/login_page.py", "/ibm_auto_manager/common/util.py"], "/ibm_auto_manager/scout/roster_page.py": ["/ibm_auto_manager/connection/login_page.py"], "/ibm_auto_manager/scout/transaction.py": ["/ibm_auto_manager/common/__init__.py"], "/ibm_auto_manager/scout/player.py": ["/ibm_auto_manager/common/__init__.py"]}
|
16,655,523
|
BorjaG90/ibm-auto-manager
|
refs/heads/develop
|
/ibm_auto_manager/dt/automation.py
|
# -*- coding: utf-8 -*-
__author__ = 'Borja Gete'
__email__ = 'borjagete90@outlook.es'
from bs4 import BeautifulSoup
from ibm_auto_manager.connection.login_page import login
from ibm_auto_manager.common.util import cls, show
def auto_bid(auth, play_aut_id = None):
""" Auto-apuesta en una subasta por un jugador
Keyword arguments:
auth -- Cadena de autenticacion a la web.
play_aut_id -- id del jugador por el que pujar
"""
#Login
session = login(auth)
print("\n\n")
cls()
if not play_aut_id:
play_aut_id = input("Introduce el id del jugador: ")
bid_url = 'http://es.ibasketmanager.com/ofertapuja.php?' \
+ 'acc=nuevo&id_jugador=' + str(play_aut_id)
#http://es.ibasketmanager.com/ofertapuja.php?acc=nuevo&id_jugador=6345048
print(show("auto-bid") + ' >{ ' + bid_url + ' }')
r = session.get(bid_url)
load_status=0
while load_status!=200:
load_status = r.status_code
#make_bid(r.content,play_aut_id,auth)
###########################################################
soup = BeautifulSoup(r.content, 'html.parser')
final = soup.find("span",{"id":"claus"})
# print(final)
if(final!=None): #I can bid
puja = final.find(text=True, recursive=False)
puja_max = soup.find("span",{"id":"clausmax"}).find(text=True, recursive=False)
fich = soup.find_all("div",{"class":"selector2"})[2].attrs['valor']
ano = soup.find("span",{"id":"ano"}).find(text=True, recursive=False)
print("\t\tPuja: " + str(puja))
print("\t\tPujaMax: " + str(puja_max))
print("\t\tFicha: " + str(fich))
print("\t\tAños: " + str(ano))
max_team = input(" Introduzca Puja máxima para el Equipo: ")
min_player = input(" Introduzca Ficha minima para el Jugador: ")
max_player = input(" Introduzca Ficha máxima para el Jugador: ")
years = input(" Introduzca Años de Contrato: ")
par = {
"acc":"ofrecer",
"tipo":"1",
"id_jugador":str(play_aut_id),
"clausula":str(puja),
"clausulamax":str(max_team),
"ficha":str(max_player),
"anos":str(years)
}
session = login(auth)
bid_up = 5000
if(int(max_player)-int(min_player) < 5000):
print(show("auto-bid") + " >>Apuestas a 100")
bid_up = 100
elif(int(max_player)-int(min_player) < 25000):
print(show("auto-bid") + " >>Apuestas a 1000")
bid_up = 1000
for i in range(int(min_player),int(max_player)+1,bid_up):
print(show("auto-bid") + " Bid: [" + str(i) + "€]")
x_url = "http://es.ibasketmanager.com/ofertapuja.php?acc=" + par['acc']
x_url = x_url + "&tipo=" + par['tipo'] + "&id_jugador=" + par['id_jugador']
x_url = x_url + "&clausula=" + par['clausula'] + "&clausulamax=" + par['clausulamax']
x_url = x_url + "&ficha=" + str(i) + "&anos=" + par['anos']
# print(x_url)
r = session.post(x_url)
load_status=0
while load_status!=200:
load_status = r.status_code
soup=BeautifulSoup(r.content, 'html.parser')
# print('#########')
# print(str(soup))
# print('#########')
final = soup.find("td",{"class":"formerror"})
#
if(final==None):
print(show("auto-bid") + " }La apuesta es buena")
#print(final.find(text=True, recursive=False))
i=int(max_player)+2
break
elif(final=="El jugador pide más años de contrato."):
break
else:
print(final.find(text=True, recursive=False))
print(show("auto-bid") + " Fin de bucle")
else:
print(show("auto-bid") + " [No puedes pujar por este jugador]")
def auto_offer(auth, play_aut_id=None):
""" Auto-oferta de renovacion por un jugador
Keyword arguments:
auth -- Cadena de autenticacion a la web.
play_aut_id -- id del jugador por el que pujar
"""
#Login
session = login(auth)
print("\n\n")
cls()
if not play_aut_id:
play_aut_id = input("Introduce el id del jugador: ")
bid_url = 'http://es.ibasketmanager.com/ofertarenovar.php?' \
+ 'acc=nuevo&tipo=4&id_jugador=' + str(play_aut_id)
#http://es.ibasketmanager.com/ofertarenovar.php?acc=nuevo&tipo=4&id_jugador=7895726
print(show("auto-offer") + ' >{ ' + bid_url + ' }')
r = session.get(bid_url)
load_status=0
while load_status!=200:
load_status = r.status_code
#make_bid(r.content,play_aut_id,auth)
###########################################################
soup = BeautifulSoup(r.content, 'html.parser')
#print(soup)
final = soup.find_all("div",{"class":"selector2"})[0].attrs['valor']
print(final)
if(final!=None): #I can bid
fich = soup.find_all("div",{"class":"selector2"})[0].attrs['valor']
ano = soup.find("span",{"id":"ano"}).find(text=True, recursive=False)
print("\t\tFicha: " + str(fich))
print("\t\tAños: " + str(ano))
min_player = input("Introduzca Ficha minima para el Jugador: ")
max_player = input("Introduzca Ficha máxima para el Jugador: ")
years = input("Introduzca Años de Contrato: ")
par = {
"acc":"ofrecer",
"tipo":"4",
"id_jugador":str(play_aut_id),
"clausula":str(0),
"clausulamax":str(0),
"ficha":str(max_player),
"anos":str(years)
}
session = login(auth)
bid_up = 5000
if(int(max_player)-int(min_player) < 5000):
print(show("auto-offer") + " >>Ofertas a 100")
bid_up = 100
elif(int(max_player)-int(min_player) < 25000):
print(show("auto-offer") + " >>Ofertas a 1000")
bid_up = 1000
for i in range(int(min_player),int(max_player)+1,bid_up):
print(show("auto-offer") + " Offer: [" + str(i) + "€]")
x_url = "http://es.ibasketmanager.com/ofertarenovar.php?acc=" + par['acc']
x_url = x_url + "&tipo=" + par['tipo'] + "&id_jugador=" + par['id_jugador']
x_url = x_url + "&clausula=" + par['clausula'] + "&clausulamax=" + par['clausulamax']
x_url = x_url + "&ficha=" + str(i) + "&anos=" + par['anos']
#print(x_url)
r = session.post(x_url)
load_status=0
while load_status!=200:
load_status = r.status_code
soup=BeautifulSoup(r.content, 'html.parser')
# print('#########')
# print(str(soup))
# print('#########')
final = soup.find("td",{"class":"formerror"})
print(final.find(text=True, recursive=False))
if(final==None):
print(show("auto-offer") + " La apuesta es buena")
#print(final.find(text=True, recursive=False))
i=int(max_player+2)
break
elif(final=="El jugador pide más años de contrato."):
break
print(show("auto-offer") + " Fin de bucle")
else:
print(show("auto-offer") + " [No puedes renovar este jugador]")
|
{"/ibm_auto_manager/trainer/team_page.py": ["/ibm_auto_manager/common/util.py", "/ibm_auto_manager/connection/login_page.py", "/ibm_auto_manager/common/__init__.py"], "/ibm_auto_manager/app.py": ["/ibm_auto_manager/common/util.py"], "/ibm_auto_manager/general/dashboard_page.py": ["/ibm_auto_manager/common/util.py", "/ibm_auto_manager/connection/login_page.py"], "/ibm_auto_manager/scout/market_page.py": ["/ibm_auto_manager/common/__init__.py", "/ibm_auto_manager/common/util.py", "/ibm_auto_manager/connection/login_page.py"], "/ibm_auto_manager/scout/auction.py": ["/ibm_auto_manager/common/__init__.py"], "/ibm_auto_manager/scout/player_page.py": ["/ibm_auto_manager/common/__init__.py", "/ibm_auto_manager/common/util.py", "/ibm_auto_manager/connection/login_page.py"], "/ibm_auto_manager/scout/league_page.py": ["/ibm_auto_manager/common/util.py", "/ibm_auto_manager/connection/login_page.py", "/ibm_auto_manager/general/dashboard_page.py", "/ibm_auto_manager/trainer/team_page.py"], "/ibm_auto_manager/dt/automation.py": ["/ibm_auto_manager/connection/login_page.py", "/ibm_auto_manager/common/util.py"], "/ibm_auto_manager/scout/roster_page.py": ["/ibm_auto_manager/connection/login_page.py"], "/ibm_auto_manager/scout/transaction.py": ["/ibm_auto_manager/common/__init__.py"], "/ibm_auto_manager/scout/player.py": ["/ibm_auto_manager/common/__init__.py"]}
|
16,655,524
|
BorjaG90/ibm-auto-manager
|
refs/heads/develop
|
/ibm_auto_manager/common/__init__.py
|
# -*- coding: utf-8 -*-
__author__ = 'Borja Gete'
__email__ = 'borjagete90@outlook.es'
__all__ = ["util", "text"]
|
{"/ibm_auto_manager/trainer/team_page.py": ["/ibm_auto_manager/common/util.py", "/ibm_auto_manager/connection/login_page.py", "/ibm_auto_manager/common/__init__.py"], "/ibm_auto_manager/app.py": ["/ibm_auto_manager/common/util.py"], "/ibm_auto_manager/general/dashboard_page.py": ["/ibm_auto_manager/common/util.py", "/ibm_auto_manager/connection/login_page.py"], "/ibm_auto_manager/scout/market_page.py": ["/ibm_auto_manager/common/__init__.py", "/ibm_auto_manager/common/util.py", "/ibm_auto_manager/connection/login_page.py"], "/ibm_auto_manager/scout/auction.py": ["/ibm_auto_manager/common/__init__.py"], "/ibm_auto_manager/scout/player_page.py": ["/ibm_auto_manager/common/__init__.py", "/ibm_auto_manager/common/util.py", "/ibm_auto_manager/connection/login_page.py"], "/ibm_auto_manager/scout/league_page.py": ["/ibm_auto_manager/common/util.py", "/ibm_auto_manager/connection/login_page.py", "/ibm_auto_manager/general/dashboard_page.py", "/ibm_auto_manager/trainer/team_page.py"], "/ibm_auto_manager/dt/automation.py": ["/ibm_auto_manager/connection/login_page.py", "/ibm_auto_manager/common/util.py"], "/ibm_auto_manager/scout/roster_page.py": ["/ibm_auto_manager/connection/login_page.py"], "/ibm_auto_manager/scout/transaction.py": ["/ibm_auto_manager/common/__init__.py"], "/ibm_auto_manager/scout/player.py": ["/ibm_auto_manager/common/__init__.py"]}
|
16,655,525
|
BorjaG90/ibm-auto-manager
|
refs/heads/develop
|
/ibm_auto_manager/common/util.py
|
# -*- coding: utf-8 -*-
__author__ = 'Borja Gete'
__email__ = 'borjagete90@outlook.es'
import os
import time
def cls():
""" Limpia la terminal según el sistema operativo """
print("\n\n")
os.system('cls' if os.name=='nt' else 'clear')
def show(title):
""" Devuelve la fecha con el objeto entre corchetes """
return str("[" + title + "](" + time.strftime("%H:%M:%S") + ") ")
|
{"/ibm_auto_manager/trainer/team_page.py": ["/ibm_auto_manager/common/util.py", "/ibm_auto_manager/connection/login_page.py", "/ibm_auto_manager/common/__init__.py"], "/ibm_auto_manager/app.py": ["/ibm_auto_manager/common/util.py"], "/ibm_auto_manager/general/dashboard_page.py": ["/ibm_auto_manager/common/util.py", "/ibm_auto_manager/connection/login_page.py"], "/ibm_auto_manager/scout/market_page.py": ["/ibm_auto_manager/common/__init__.py", "/ibm_auto_manager/common/util.py", "/ibm_auto_manager/connection/login_page.py"], "/ibm_auto_manager/scout/auction.py": ["/ibm_auto_manager/common/__init__.py"], "/ibm_auto_manager/scout/player_page.py": ["/ibm_auto_manager/common/__init__.py", "/ibm_auto_manager/common/util.py", "/ibm_auto_manager/connection/login_page.py"], "/ibm_auto_manager/scout/league_page.py": ["/ibm_auto_manager/common/util.py", "/ibm_auto_manager/connection/login_page.py", "/ibm_auto_manager/general/dashboard_page.py", "/ibm_auto_manager/trainer/team_page.py"], "/ibm_auto_manager/dt/automation.py": ["/ibm_auto_manager/connection/login_page.py", "/ibm_auto_manager/common/util.py"], "/ibm_auto_manager/scout/roster_page.py": ["/ibm_auto_manager/connection/login_page.py"], "/ibm_auto_manager/scout/transaction.py": ["/ibm_auto_manager/common/__init__.py"], "/ibm_auto_manager/scout/player.py": ["/ibm_auto_manager/common/__init__.py"]}
|
16,655,526
|
BorjaG90/ibm-auto-manager
|
refs/heads/develop
|
/ibm_auto_manager/common/text.py
|
# -*- coding: utf-8 -*-
__author__ = 'Borja Gete'
__email__ = 'borjagete90@outlook.es'
import datetime
import re
from bs4 import BeautifulSoup
reg_date_full = r'(?:(?:31(\/|-|\.)(?:0?[13578]|1[02]|\
(?:Jan|Mar|May|Jul|Aug|Oct|Dec)))\1|(?:(?:29|30)(\/|-|\.)(?:0?[1,3-9]|1[0-2]|\
(?:Jan|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec))\2))\
(?:(?:1[6-9]|[2-9]\d)?\d{2})$|^(?:29(\/|-|\.)\
(?:0?2|(?:Feb))\3(?:(?:(?:1[6-9]|[2-9]\d)?(?:0[48]|[2468][048]|[13579][26])|\
(?:(?:16|[2468][048]|[3579][26])00))))$|^(?:0?[1-9]|1\d|2[0-8])(\/|-|\.)(?:\
(?:0?[1-9]|(?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep))|(?:1[0-2]|\
(?:Oct|Nov|Dec)))\4(?:(?:1[6-9]|[2-9]\d)?\d{2})'
reg_month = r'(Ene|Feb|Mar|Abr|May|Jun|Jul|Ago|Sep|Oct|Nov|Dic)'
reg_day = r'(Lunes|Martes|Miércoles|Jueves|Viernes|Sábado|Domingo)'
reg_hour = r'(([01]\d|2[0-3]):([0-5]\d)|24:00)'
def pos_treatment(position):
""" Tratamiento de las posiciones de los jugadores """
return position.replace("SF", "A").replace("PF", "AP").replace(
"C", "P").replace("PG", "B").replace("SG", "E").replace(
"Base", "B").replace("Escolta", "E").replace(
"Alero", "A").replace("Ala-pivot", "AP").replace("Pivot", "P")
def date_translation(html_content):
"""Transform short date format to standard date format.
Keyword arguments:
html_content -- String who represents a date in diverse formats.
"""
# Remove the hour
html_content = html_content.replace(re.search(
r'\s\d{1,2}:\d{1,2}', html_content).group(0), '')
if re.search("Hoy", html_content) is not None:
# print("Hoy")
return '{}/{}/{}'.format(str(datetime.datetime.now().day).zfill(2), \
str(datetime.datetime.now().month).zfill(2), datetime.datetime.now().year)
elif re.search("Ayer", html_content) is not None:
# print("Ayer")
return '{}/{}/{}'.format(str(datetime.datetime.now().day -1).zfill(2), \
str(datetime.datetime.now().month).zfill(2), datetime.datetime.now().year)
elif re.search(reg_month, html_content) is not None:
day = re.search(r'\d{1,2}', html_content).group(0).replace(' ', '')
month_str = re.search(reg_month, html_content).group(0)
if(month_str == 'Ene'):
month = 1
elif(month_str == 'Feb'):
month = 2
elif(month_str == 'Mar'):
month = 3
elif(month_str == 'Abr'):
month = 4
elif(month_str == 'May'):
month = 5
elif(month_str == 'Jun'):
month = 6
elif(month_str == 'Jul'):
month = 7
elif(month_str == 'Ago'):
month = 8
elif(month_str == 'Sep'):
month = 9
elif(month_str == 'Oct'):
month = 10
elif(month_str == 'Nov'):
month = 11
elif(month_str == 'Dic'):
month = 12
if(month < datetime.datetime.now().month):
year = datetime.datetime.now().year - 1
else:
year = datetime.datetime.now().year
return '{}/{}/{}'.format(str(day).zfill(2), str(month).zfill(2), year)
elif re.search(reg_day, html_content) is not None:
day = re.search(r'\d{1,2}', html_content).group(0).replace(' ', '')
if(int(day) < datetime.datetime.now().day):
if(datetime.datetime.now().month == 1):
month = 12
else:
month = datetime.datetime.now().month - 1
else:
month = datetime.datetime.now().month
if(month < datetime.datetime.now().month):
year = datetime.datetime.now().year - 1
else:
year = datetime.datetime.now().year
return '{}/{}/{}'.format(str(day).zfill(2), str(month).zfill(2), year)
else:
pass
# print(html_content)
return html_content
def date_market_translation(html_content):
"""Transform short date format to standard date format.
Keyword arguments:
html_content -- String who represents a date in diverse formats.
"""
soup = BeautifulSoup(html_content, 'html.parser')
html_content = str(soup).replace(' ', ' ').replace(
'á', 'á').replace('é', 'é').replace(
'í', 'í').replace('ó', 'ó').replace('ú', 'ú')
hr = re.search(reg_hour, html_content).group(0)
# print(html_content)
hour = int(hr.split(':')[0])
minutes = int(hr.split(':')[1])
# print('{}:{}'.format(hour,minutes))
today = datetime.datetime.today()
if(re.search(reg_day, html_content) is not None):
h = str(html_content).split('\xa0')
while(int(today.strftime("%d")) != int(h[1])):
today = today + datetime.timedelta(days=1)
elif(re.search('Mañana', html_content) is not None or re.search(
'Mañana', html_content) is not None):
today = today + datetime.timedelta(days=1)
elif(re.search('Hoy', html_content) is not None):
pass
else:
print('\t[Market-COMPROBAR]:' + html_content)
today = today.replace(
hour=hour,
minute=minutes
)
return today
def get_date_str(p_date, seconds = True):
""" Devuelve la cadena de una fecha """
if(seconds):
res = str(str(p_date.year) + str(p_date.month) + str(p_date.day) + str(p_date.hour) + str(p_date.minute))
else:
res = str(str(p_date.year) + str(p_date.month) + str(p_date.day))
return res
|
{"/ibm_auto_manager/trainer/team_page.py": ["/ibm_auto_manager/common/util.py", "/ibm_auto_manager/connection/login_page.py", "/ibm_auto_manager/common/__init__.py"], "/ibm_auto_manager/app.py": ["/ibm_auto_manager/common/util.py"], "/ibm_auto_manager/general/dashboard_page.py": ["/ibm_auto_manager/common/util.py", "/ibm_auto_manager/connection/login_page.py"], "/ibm_auto_manager/scout/market_page.py": ["/ibm_auto_manager/common/__init__.py", "/ibm_auto_manager/common/util.py", "/ibm_auto_manager/connection/login_page.py"], "/ibm_auto_manager/scout/auction.py": ["/ibm_auto_manager/common/__init__.py"], "/ibm_auto_manager/scout/player_page.py": ["/ibm_auto_manager/common/__init__.py", "/ibm_auto_manager/common/util.py", "/ibm_auto_manager/connection/login_page.py"], "/ibm_auto_manager/scout/league_page.py": ["/ibm_auto_manager/common/util.py", "/ibm_auto_manager/connection/login_page.py", "/ibm_auto_manager/general/dashboard_page.py", "/ibm_auto_manager/trainer/team_page.py"], "/ibm_auto_manager/dt/automation.py": ["/ibm_auto_manager/connection/login_page.py", "/ibm_auto_manager/common/util.py"], "/ibm_auto_manager/scout/roster_page.py": ["/ibm_auto_manager/connection/login_page.py"], "/ibm_auto_manager/scout/transaction.py": ["/ibm_auto_manager/common/__init__.py"], "/ibm_auto_manager/scout/player.py": ["/ibm_auto_manager/common/__init__.py"]}
|
16,655,527
|
BorjaG90/ibm-auto-manager
|
refs/heads/develop
|
/ibm_auto_manager/scout/roster_page.py
|
# -*- coding: utf-8 -*-
__author__ = 'Borja Gete'
__email__ = 'borjagete90@outlook.es'
from bs4 import BeautifulSoup
from ibm_auto_manager.connection.login_page import login
def enter_senior_roster(id_team, auth, session = None):
""" Recorremos las páginas de plantillas
Devolvemos un array con los ids de los jugadores
que conforman la plantilla
Keyword arguments:
id_team -- Id del equipo al que se va a acceder a su plantilla
auth -- Cadena de autenticacion a la web.
db -- Objeto de conexion a la BD.
"""
if session is None:
session = login(auth)
senior_roster_url = "http://es.ibasketmanager.com/plantilla.php?id_equipo="\
+ str(id_team)
r = session.get(senior_roster_url)
load_status = 0
while load_status != 200:
load_status = r.status_code
seniors = []
soup = BeautifulSoup(r.content, 'html.parser')
seniors_str = soup.find_all('table', {"id": "pagetabla"})
seniors_str = BeautifulSoup(
str(seniors_str), 'html.parser').find_all("td", {"class": "jugador"})
if seniors_str is not None:
for senior_str in seniors_str:
# print(senior_str.find('a')['href'][senior_str.find(
# 'a')['href'].find('=')+1:])
seniors.append(
senior_str.find("a")["href"][senior_str.find("a")["href"].find("=")+1:]
)
return seniors
def enter_junior_roster(id_team, auth, session = None):
""" Recorremos las páginas de canteras
Devolvemos un array con los ids de los jugadores que
conforman la cantera
Keyword arguments:
id_team -- Id del equipo al que se va a acceder a su cantera
auth -- Cadena de autenticacion a la web.
db -- Objeto de conexion a la BD.
"""
if session is None:
session = login(auth)
jr_url = "http://es.ibasketmanager.com/plantilla.php?" + \
"juveniles=1&id_equipo=" + str(id_team)
r = session.get(jr_url)
load_status = 0
while load_status != 200:
load_status = r.status_code
juniors = []
soup = BeautifulSoup(r.content, "html.parser")
juniors_str = soup.find_all("table", {"id": "pagetabla"})
juniors_str = BeautifulSoup(str(juniors_str), "html.parser").find_all(
"td", {"class": "jugador"})
if juniors_str is not None:
# print(juniors_str)
for junior_str in juniors_str:
# print(junior_str.find('a')['href'][junior_str.find(
# 'a')['href'].find('=')+1:])
# Sustituir por split()[1]
juniors.append(
junior_str.find("a")["href"][junior_str.find("a")["href"].find("=")+1:]
)
return juniors
|
{"/ibm_auto_manager/trainer/team_page.py": ["/ibm_auto_manager/common/util.py", "/ibm_auto_manager/connection/login_page.py", "/ibm_auto_manager/common/__init__.py"], "/ibm_auto_manager/app.py": ["/ibm_auto_manager/common/util.py"], "/ibm_auto_manager/general/dashboard_page.py": ["/ibm_auto_manager/common/util.py", "/ibm_auto_manager/connection/login_page.py"], "/ibm_auto_manager/scout/market_page.py": ["/ibm_auto_manager/common/__init__.py", "/ibm_auto_manager/common/util.py", "/ibm_auto_manager/connection/login_page.py"], "/ibm_auto_manager/scout/auction.py": ["/ibm_auto_manager/common/__init__.py"], "/ibm_auto_manager/scout/player_page.py": ["/ibm_auto_manager/common/__init__.py", "/ibm_auto_manager/common/util.py", "/ibm_auto_manager/connection/login_page.py"], "/ibm_auto_manager/scout/league_page.py": ["/ibm_auto_manager/common/util.py", "/ibm_auto_manager/connection/login_page.py", "/ibm_auto_manager/general/dashboard_page.py", "/ibm_auto_manager/trainer/team_page.py"], "/ibm_auto_manager/dt/automation.py": ["/ibm_auto_manager/connection/login_page.py", "/ibm_auto_manager/common/util.py"], "/ibm_auto_manager/scout/roster_page.py": ["/ibm_auto_manager/connection/login_page.py"], "/ibm_auto_manager/scout/transaction.py": ["/ibm_auto_manager/common/__init__.py"], "/ibm_auto_manager/scout/player.py": ["/ibm_auto_manager/common/__init__.py"]}
|
16,655,528
|
BorjaG90/ibm-auto-manager
|
refs/heads/develop
|
/ibm_auto_manager/connection/login_page.py
|
# -*- coding: utf-8 -*-
__author__ = 'Borja Gete'
__email__ = 'borjagete90@outlook.es'
import requests
def login(payload):
""" Devuelve una sesión logueada en la web de IBM
con la cual hacer peticiones.
Se usara tambien para renovar la llamada cada vez que sea
susceptible de caducarse la sesión """
session = requests.session()
login_url = 'http://es.ibasketmanager.com/loginweb.php'
r = session.post(login_url, data=payload)
load_status = 0
while load_status != 200:
load_status = r.status_code
# print('\n[' + time.strftime("%H:%M:%S") + '] \
# [LogIn realizado con exito]\n')
return session
|
{"/ibm_auto_manager/trainer/team_page.py": ["/ibm_auto_manager/common/util.py", "/ibm_auto_manager/connection/login_page.py", "/ibm_auto_manager/common/__init__.py"], "/ibm_auto_manager/app.py": ["/ibm_auto_manager/common/util.py"], "/ibm_auto_manager/general/dashboard_page.py": ["/ibm_auto_manager/common/util.py", "/ibm_auto_manager/connection/login_page.py"], "/ibm_auto_manager/scout/market_page.py": ["/ibm_auto_manager/common/__init__.py", "/ibm_auto_manager/common/util.py", "/ibm_auto_manager/connection/login_page.py"], "/ibm_auto_manager/scout/auction.py": ["/ibm_auto_manager/common/__init__.py"], "/ibm_auto_manager/scout/player_page.py": ["/ibm_auto_manager/common/__init__.py", "/ibm_auto_manager/common/util.py", "/ibm_auto_manager/connection/login_page.py"], "/ibm_auto_manager/scout/league_page.py": ["/ibm_auto_manager/common/util.py", "/ibm_auto_manager/connection/login_page.py", "/ibm_auto_manager/general/dashboard_page.py", "/ibm_auto_manager/trainer/team_page.py"], "/ibm_auto_manager/dt/automation.py": ["/ibm_auto_manager/connection/login_page.py", "/ibm_auto_manager/common/util.py"], "/ibm_auto_manager/scout/roster_page.py": ["/ibm_auto_manager/connection/login_page.py"], "/ibm_auto_manager/scout/transaction.py": ["/ibm_auto_manager/common/__init__.py"], "/ibm_auto_manager/scout/player.py": ["/ibm_auto_manager/common/__init__.py"]}
|
16,655,529
|
BorjaG90/ibm-auto-manager
|
refs/heads/develop
|
/ibm_auto_manager/scout/transaction.py
|
# -*- coding: utf-8 -*-
__author__ = 'Borja Gete'
__email__ = 'borjagete90@outlook.es'
from datetime import datetime
from bson import ObjectId
from ibm_auto_manager.common import text
class Transaction:
"""Representa una transacción de un jugador de un equipo a otro
en una fecha especifica.
Keyword arguments:
id_player -- id of the player.
id_date_buy -- date of transaction in numeric format.
age -- age of the player at the moment of the transaction.
avg -- average points at the moment of the transaction.
pos -- position of the player.
price -- cost of the player.
salary -- salary of the player.
type_buy -- [Subasta/Compra directa/Traspaso pactado/Clausulazo]
date_buy -- date of transaction in date format.
"""
def __init__(self,
id_player,
id_date_buy,
age,
avg,
pos,
price,
type_buy,
salary=None,
date_buy=None
):
self.player_id = ObjectId(id_player.zfill(24))
self.date_buy_id = ObjectId(id_date_buy.zfill(24))
self.age = int(age)
self.average = int(avg)
self.position = pos
self.price = int(price.replace('.', ''))
self.salary = int(salary.replace('.', ''))
self.type_buy = type_buy
self.date_buy = date_buy
def __str__(self):
return 'Id: {} {} de {} años, con {} de media\n\tVendido en {} por {}€\
, cobrando {}€ en la fecha {},{}'.format(
self.player_id,
self.position,
self.age,
self.average,
self.type_buy,
self.price,
self.salary,
self.date_buy,
self.date_buy_id
)
def to_db_collection(self):
"""Devuelve los datos del jugador en un formato legible de MongoDB."""
return {
"date_buy_id": self.date_buy_id,
"player_id": self.player_id,
"age": self.age,
"average": self.average,
"position": text.pos_treatment(self.position),
"price": self.price,
"salary": self.salary,
"type_buy": self.type_buy,
"date_buy": self.date_buy,
"_date": datetime.now(),
"player": self.player_id
}
|
{"/ibm_auto_manager/trainer/team_page.py": ["/ibm_auto_manager/common/util.py", "/ibm_auto_manager/connection/login_page.py", "/ibm_auto_manager/common/__init__.py"], "/ibm_auto_manager/app.py": ["/ibm_auto_manager/common/util.py"], "/ibm_auto_manager/general/dashboard_page.py": ["/ibm_auto_manager/common/util.py", "/ibm_auto_manager/connection/login_page.py"], "/ibm_auto_manager/scout/market_page.py": ["/ibm_auto_manager/common/__init__.py", "/ibm_auto_manager/common/util.py", "/ibm_auto_manager/connection/login_page.py"], "/ibm_auto_manager/scout/auction.py": ["/ibm_auto_manager/common/__init__.py"], "/ibm_auto_manager/scout/player_page.py": ["/ibm_auto_manager/common/__init__.py", "/ibm_auto_manager/common/util.py", "/ibm_auto_manager/connection/login_page.py"], "/ibm_auto_manager/scout/league_page.py": ["/ibm_auto_manager/common/util.py", "/ibm_auto_manager/connection/login_page.py", "/ibm_auto_manager/general/dashboard_page.py", "/ibm_auto_manager/trainer/team_page.py"], "/ibm_auto_manager/dt/automation.py": ["/ibm_auto_manager/connection/login_page.py", "/ibm_auto_manager/common/util.py"], "/ibm_auto_manager/scout/roster_page.py": ["/ibm_auto_manager/connection/login_page.py"], "/ibm_auto_manager/scout/transaction.py": ["/ibm_auto_manager/common/__init__.py"], "/ibm_auto_manager/scout/player.py": ["/ibm_auto_manager/common/__init__.py"]}
|
16,655,530
|
BorjaG90/ibm-auto-manager
|
refs/heads/develop
|
/ibm_auto_manager/scout/player.py
|
# -*- coding: utf-8 -*-
__author__ = 'Borja Gete'
__email__ = 'borjagete90@outlook.es'
from datetime import datetime
from bson import ObjectId
from ibm_auto_manager.common import text
class Player:
"""Representa un jugador."""
def __init__(self,
id_player,
team_id,
name,
position,
age,
heigth,
weight,
canon,
salary,
clause,
years,
juvenil,
country
):
self._id = ObjectId(id_player.zfill(24))
self.team_id = ObjectId(team_id.zfill(24))
self.name = name
self.position = position
self.age = int(age)
self.heigth = int(heigth)
self.weight = int(weight)
self.canon = int(canon)
self.salary = int(salary)
self.clause = int(clause)
self.years = int(years)
self.juvenil = juvenil
self.country = country
def __str__(self):
return "{} con Id: {}, {} de {} años de {}".format(
self.name,
self._id,
self.position,
self.age,
self.country
)
def to_db_collection(self):
"""Devuelve los datos del jugador en un formato legible de MongoDB."""
return {
"_id": self._id,
"team_id": self.team_id,
"name": self.name,
"position": text.pos_treatment(self.position),
"age": self.age,
"heigth": self.heigth,
"weight": self.weight,
"canon": self.canon,
"salary": self.salary,
"clause": self.clause,
"years": self.years,
"juvenil": self.juvenil,
"country": self.country,
"_date": datetime.now()
}
class PlayerAtributes:
"""Representa los atributos de un jugador."""
def __init__(self,
id_player,
power,
ambition,
leadership,
exp,
speed,
jump,
endurance,
level,
marking,
rebound,
block,
recover,
two,
three,
free,
assist,
dribbling,
dunk,
fight,
mental,
physic,
defense,
offense,
total,
loyalty
):
self.player_id = ObjectId(id_player.zfill(24))
self.power = int(power)
self.ambition = int(ambition)
self.leadership = int(leadership)
self.exp = int(exp)
self.speed = int(speed)
self.jump = int(jump)
self.endurance = int(endurance)
self.level = int(level)
self.marking = int(marking)
self.rebound = int(rebound)
self.block = int(block)
self.recover = int(recover)
self.two = int(two)
self.three = int(three)
self.free = int(free)
self.assist = int(assist)
self.dribbling = int(dribbling)
self.dunk = int(dunk)
self.fight = int(fight)
self.mental = int(mental)
self.physic = int(physic)
self.defense = int(defense)
self.offense = int(offense)
self.total = int(total)
self.loyalty = int(loyalty)
def __str__(self):
return "Id: {}, medias -> Tot: {}, Off: {}, Def: {}, \
Mnt: {}, Fis: {}".format(
self.player_id,
self.total / 100,
self.offense / 100,
self.defense / 100,
self.mental / 100,
self.physic / 100
)
def to_db_collection(self):
"""Devuelve los atributos del jugador en un formato legible de MongoDB."""
return{
"_id": self.player_id,
"power": self.power,
"ambition": self.ambition,
"leadership": self.leadership,
"loyalty": self.loyalty,
"exp": self.exp,
"speed": self.speed,
"jump": self.jump,
"endurance": self.endurance,
"level": self.level,
"marking": self.marking,
"rebound": self.rebound,
"block": self.block,
"recover": self.recover,
"two": self.two,
"three": self.three,
"free": self.free,
"assist": self.assist,
"dribbling": self.dribbling,
"dunk": self.dunk,
"fight": self.fight,
"mental": self.mental,
"physic": self.physic,
"defense": self.defense,
"offense": self.offense,
"total": self.total,
"_date": datetime.now()
}
def to_db_collection_prog(self):
"""Devuelve la progresión del jugador en un formato legible de MongoDB."""
return{
"_id": ObjectId((str(int(str(self.player_id))) + text.get_date_str(datetime.now(), False)).zfill(24)),
"player_id": self.player_id,
"power": self.power,
"ambition": self.ambition,
"leadership": self.leadership,
"loyalty": self.loyalty,
"exp": self.exp,
"speed": self.speed,
"jump": self.jump,
"endurance": self.endurance,
"level": self.level,
"marking": self.marking,
"rebound": self.rebound,
"block": self.block,
"recover": self.recover,
"two": self.two,
"three": self.three,
"free": self.free,
"assist": self.assist,
"dribbling": self.dribbling,
"dunk": self.dunk,
"fight": self.fight,
"mental": self.mental,
"physic": self.physic,
"defense": self.defense,
"offense": self.offense,
"total": self.total,
"_date": datetime.now()
}
|
{"/ibm_auto_manager/trainer/team_page.py": ["/ibm_auto_manager/common/util.py", "/ibm_auto_manager/connection/login_page.py", "/ibm_auto_manager/common/__init__.py"], "/ibm_auto_manager/app.py": ["/ibm_auto_manager/common/util.py"], "/ibm_auto_manager/general/dashboard_page.py": ["/ibm_auto_manager/common/util.py", "/ibm_auto_manager/connection/login_page.py"], "/ibm_auto_manager/scout/market_page.py": ["/ibm_auto_manager/common/__init__.py", "/ibm_auto_manager/common/util.py", "/ibm_auto_manager/connection/login_page.py"], "/ibm_auto_manager/scout/auction.py": ["/ibm_auto_manager/common/__init__.py"], "/ibm_auto_manager/scout/player_page.py": ["/ibm_auto_manager/common/__init__.py", "/ibm_auto_manager/common/util.py", "/ibm_auto_manager/connection/login_page.py"], "/ibm_auto_manager/scout/league_page.py": ["/ibm_auto_manager/common/util.py", "/ibm_auto_manager/connection/login_page.py", "/ibm_auto_manager/general/dashboard_page.py", "/ibm_auto_manager/trainer/team_page.py"], "/ibm_auto_manager/dt/automation.py": ["/ibm_auto_manager/connection/login_page.py", "/ibm_auto_manager/common/util.py"], "/ibm_auto_manager/scout/roster_page.py": ["/ibm_auto_manager/connection/login_page.py"], "/ibm_auto_manager/scout/transaction.py": ["/ibm_auto_manager/common/__init__.py"], "/ibm_auto_manager/scout/player.py": ["/ibm_auto_manager/common/__init__.py"]}
|
16,664,774
|
ptrthegr8/news_app
|
refs/heads/main
|
/news/forms.py
|
from django import forms
from news.models import Author
"""
create an article
title = models.CharField(max_length=50)
body = models.TextField()
post_created = models.DateTimeField(default=timezone.now)
author = models.ForeignKey(Author, on_delete=models.CASCADE)
create an author
name = models.CharField(max_length=50)
byline = models.CharField(max_length=50, null=True, blank=True)
"""
class AddArticleForm(forms.Form):
title = forms.CharField(max_length=50)
body = forms.CharField(widget=forms.Textarea)
author = forms.ModelChoiceField(queryset=Author.objects.all())
class AddAuthorForm(forms.ModelForm):
class Meta:
model = Author
fields = ["name", "byline"]
|
{"/news/views.py": ["/news/forms.py"]}
|
16,664,775
|
ptrthegr8/news_app
|
refs/heads/main
|
/news/views.py
|
from django.shortcuts import render, HttpResponseRedirect, reverse
from news.models import Article, Author
from news.forms import AddArticleForm, AddAuthorForm
# Create your views here.
def index_view(request):
articles = Article.objects.all()
return render(request, "index.html", {"articles": articles})
def article_detail(request, id):
article = Article.objects.get(id=id)
return render(request, "article_detail.html", {"article": article})
def author_detail(request, id):
author = Author.objects.get(id=id)
articles = Article.objects.filter(author=author)
return render(
request, "author_detail.html", {"author": author, "articles": articles}
)
def add_article(request):
if request.method == "POST":
form = AddArticleForm(request.POST)
if form.is_valid():
data = form.cleaned_data
article = Article.objects.create(
title=data["title"], body=data["body"], author=data["author"]
)
return HttpResponseRedirect(reverse("home"))
form = AddArticleForm()
return render(request, "generic_form.html", {"form": form})
def add_author(request):
if request.method == "POST":
form = AddAuthorForm(request.POST)
form.save()
return HttpResponseRedirect(reverse("home"))
form = AddAuthorForm()
return render(request, "generic_form.html", {"form": form})
|
{"/news/views.py": ["/news/forms.py"]}
|
16,674,401
|
pj0620/collatz
|
refs/heads/main
|
/gen_a_sets.py
|
max_alpha = 16
# def h_p(x):
# if x == 0: return 0
# res = 0
# while x%2 == 0:
# res += 1
# x = x >> 1
# return res
#
# def h(x):
# if x < 0:
# x = abs(x)
# if x-int(x) == 0:
# return h_p(int(x))
#
# def c(x):
# return int(x/u(x))
#
# def u(x):
# return 2**h(x)
#
# def get_num_steps(x):
# cur = x
# steps = 0
# while cur != 1:
# cur = c(3*c(cur) + 1)
# steps += 1
# return steps
def getNextA(A, max_val):
i = 0
while A[i] >= max_val:
A[i] = 1
i += 1
A[i] += 1
for n in range(1, 100):
f = open(f"collatz-{n}.csv", "w")
f.write("depth, xn, alpha values\n")
A = [1]*n
while A[n-1] < max_alpha:
a = 2**sum(A)
b = 0
for k in range(n):
bp = 0
if k > 0:
for t in range(1,k+1):
bp += A[n-t]
b += (3**(n-1-k))*(2**bp)
xn, r = divmod(a-b, 3**n)
if r == 0:
f.write(f"{n}, {xn}, {','.join(str(x) for x in A)} \n")
getNextA(A, max_alpha)
f.close()
|
{"/level_1_sum_approx.py": ["/common_funcs.py"], "/sum_u.py": ["/common_funcs.py"], "/level_2_sum_approx.py": ["/common_funcs.py"], "/main.py": ["/levels_func.py", "/common_funcs.py"]}
|
16,757,278
|
priyankush-siloria/django_api_task
|
refs/heads/master
|
/api/views.py
|
from django.shortcuts import render
from rest_framework.views import APIView
from .models import Student
from .serializers import StudentSerializer
from rest_framework.response import Response
from .utils import randoem_name
from django.views import View
from django.http import StreamingHttpResponse
import csv
import io
from django.http import HttpResponseRedirect
from django.urls import reverse
from rest_framework import status
class HomeView(View):
"""
View for download button page
"""
template = 'api/index.html'
def get(self, request, lot=None):
return render(request, self.template, locals())
class DummyPage(View):
"""
View for dummy page
"""
template = 'api/dummy.html'
def get(self, request, lot=None):
return HttpResponseRedirect(reverse("api:home"))
class CreateListStudent(APIView):
"""
APi view for create and list student
"""
def get(self, request):
student = Student.objects.all()
serializer = StudentSerializer(student, many=True)
return Response(serializer.data)
def post(self, request):
data = []
context = {}
for i in range(1000):
student_dtls = {}
student_dtls['first_name'] = randoem_name()
student_dtls['last_name'] = randoem_name()
data.append(student_dtls)
serializer = StudentSerializer(data=data, many=True)
if serializer.is_valid():
serializer.save()
context['data'] = serializer.data
context['status'] = True
status_code = status.HTTP_201_CREATED
context['message'] = "All Student data created"
return Response(context, status=status_code)
class UpdateDeleteStudent(APIView):
"""
Api view for update and delete student
"""
def get_object(self, pk):
try:
student = Student.objects.get(id=pk)
return student
except Exception as e:
return False
def put(self, request, pk=None):
context = {}
try:
student = self.get_object(pk)
if student:
serializer = StudentSerializer(student ,data=request.data, partial=True)
if serializer.is_valid():
serializer.save()
context['data'] = serializer.data
context['status'] = True
status_code = 200
context['message'] = "Student data Updated"
return Response(context, status=status_code)
return Response(serializer.errors, status=400)
else:
return Response({'mesg': "NO student found"},
status=404)
except Exception as e:
context['data'] = []
context['status'] = False
status_code = status.HTTP_400_BAD_REQUEST
context['message'] = str(e)
return Response(context, status=status_code)
def delete(self, request, pk=None):
context = {}
try:
student = self.get_object(pk)
if student:
student.delete()
context['data'] = []
context['status'] = True
status_code = 200
context['message'] = "Student data delete"
return Response(context, status=status_code)
else:
return Response({'mesg': "NO student found"},
status=404)
except Exception as e:
context['data'] = []
context['status'] = False
status_code = status.HTTP_400_BAD_REQUEST
context['message'] = str(e)
return Response(context, status=status_code)
class Download(APIView):
"""
View for download student details as a streaming
"""
def get(self, request):
rows = Student.objects.all()
header = ['id','first name', 'last name']
def stream():
buffer_ = io.StringIO()
writer = csv.writer(buffer_)
writer.writerow(header)
for row in rows:
data_list = [row.id, row.first_name, row.last_name]
writer.writerow(data_list)
buffer_.seek(0)
data = buffer_.read()
buffer_.seek(0)
buffer_.truncate()
yield data
response = StreamingHttpResponse(
stream(), content_type='text/csv'
)
disposition = "attachment; filename=file.csv"
response['Content-Disposition'] = disposition
return response
|
{"/api/views.py": ["/api/models.py", "/api/serializers.py", "/api/utils.py"], "/api/urls.py": ["/api/views.py"], "/api/serializers.py": ["/api/models.py"]}
|
16,757,279
|
priyankush-siloria/django_api_task
|
refs/heads/master
|
/api/models.py
|
from django.db import models
# Create your models here.
class Student(models.Model):
first_name = models.CharField(max_length=55)
last_name = models.CharField(max_length=55, null=True, blank=True)
created_at = models.DateTimeField(auto_now_add=True)
def __str__(self) -> str:
return f"{self.id}-{self.first_name}"
|
{"/api/views.py": ["/api/models.py", "/api/serializers.py", "/api/utils.py"], "/api/urls.py": ["/api/views.py"], "/api/serializers.py": ["/api/models.py"]}
|
16,757,280
|
priyankush-siloria/django_api_task
|
refs/heads/master
|
/api/urls.py
|
from django.urls import path
from .views import CreateListStudent, UpdateDeleteStudent, HomeView, Download, DummyPage
from .apps import ApiConfig
app_name = ApiConfig.name
urlpatterns = [
path("student", CreateListStudent.as_view(), name="student"),
path("student/<int:pk>", UpdateDeleteStudent.as_view()),
path('',HomeView.as_view(), name="home"),
path('download',Download.as_view()),
path('dummy', DummyPage.as_view())
]
|
{"/api/views.py": ["/api/models.py", "/api/serializers.py", "/api/utils.py"], "/api/urls.py": ["/api/views.py"], "/api/serializers.py": ["/api/models.py"]}
|
16,757,281
|
priyankush-siloria/django_api_task
|
refs/heads/master
|
/api/utils.py
|
import string
import random
def randoem_name():
letters = string.ascii_lowercase
return ''.join(random.choice(letters) for i in range(10))
|
{"/api/views.py": ["/api/models.py", "/api/serializers.py", "/api/utils.py"], "/api/urls.py": ["/api/views.py"], "/api/serializers.py": ["/api/models.py"]}
|
16,757,282
|
priyankush-siloria/django_api_task
|
refs/heads/master
|
/api/serializers.py
|
from .models import Student
from rest_framework import serializers
class StudentSerializer(serializers.ModelSerializer):
class Meta:
model = Student
fields = ['id', 'first_name', 'last_name', 'created_at']
|
{"/api/views.py": ["/api/models.py", "/api/serializers.py", "/api/utils.py"], "/api/urls.py": ["/api/views.py"], "/api/serializers.py": ["/api/models.py"]}
|
16,867,593
|
imeteora/SmartCam
|
refs/heads/main
|
/SmartCam.py
|
import cv2
import imutils
import shutil
import time
import glob
import numpy as np
import os, sys
from PIL import Image
import face_recognition
from adafruit_servokit import ServoKit
import datetime
import threading
import concurrent.futures
import smtplib
import argparse
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart
import MegaNZ
#display width and height
WIDTH = 1920
HEIGHT = 1080
DISPLAY_WIDTH = 1920
DISPLAY_HEIGHT = 1080
FOV = 40 # Servo FOV to change frame
#camera settings
camSet='nvarguscamerasrc ! video/x-raw(memory:NVMM), width=4032, height=3040, format=NV12, framerate=21/1 ! nvvidconv ! video/x-raw, width='+str(WIDTH)+', height='+str(HEIGHT)+', format=BGRx ! videoconvert ! video/x-raw, format=BGR ! appsink'
cam= cv2.VideoCapture(camSet)
#If workinng mod = 1 , dont show video after initialize, else show video
#Parameters to mouse click event
goFlag = 0
x1 = 0
x2 = 0
y1 = 0
y2 = 0
#define servo channels
kit=ServoKit(channels=16)
def parser():
parser = argparse.ArgumentParser(description="Smart Camera detection and classification")
parser.add_argument("--weights", default="./cfg/Tinyyolov4_personDetection.weights",
help="yolo weights path")
parser.add_argument("--cfg", default="./cfg/Tinyyolov4_personDetection.cfg",
help="yolo cfg path, defult: ./cfg/Tinyyolov4_personDetection.cfg")
parser.add_argument("--backup_dir", default="/home/rami/Desktop/SmartCam/Pictures/backup",
help="backup image directory")
parser.add_argument("--unknown_dir", default="/home/rami/Desktop/SmartCam/Pictures/unknown",
help="unknown image directory")
parser.add_argument("--known_dir", default="/home/rami/Desktop/SmartCam/Pictures/known",
help="known image directory")
parser.add_argument("--model", default="hog",
help="model for the classifier , cnn or hog, defullt: hog")
parser.add_argument("--frames", type=int ,default=2,
help="number of frames to init, defult: 2")
parser.add_argument("--mode", type=int ,default=1,
help="to show video processing insert 0 , defult: 1")
parser.add_argument("--thresh", type=int, default=5,
help="false classification with confidence below this value (percentage), defult : 5")
return parser.parse_args()
def check_arguments_errors(args):
assert 0 < args.thresh < 100, "Threshold should be an int between zero and 100"
assert 0 < args.frames < 4, "Frames should be an int between 1 - 3 "
assert args.mode == 0 or args.mode == 1, "mode should be zero or one "
if not os.path.exists(args.cfg):
raise(ValueError("Invalid config path {}".format(os.path.abspath(args.cfg))))
if not os.path.exists(args.weights):
raise(ValueError("Invalid weight path {}".format(os.path.abspath(args.weights))))
if not os.path.exists(args.backup_dir):
raise(ValueError("Invalid backup image path {}".format(os.path.abspath(args.backup_dir))))
if not os.path.exists(args.unknown_dir):
raise(ValueError("Invalid unknown image path {}".format(os.path.abspath(args.unknown_dir))))
if not os.path.exists(args.known_dir):
raise(ValueError("Invalid known image path {}".format(os.path.abspath(args.known_dir))))
#draw ROI - Region Of Interest
def mouse_click(event,x,y,flags,params):
global x1,y1,x2,y2
global goFlag
if event == cv2.EVENT_LBUTTONDOWN:
x1 = x
y1 = y
goFlag = 0
if event == cv2.EVENT_LBUTTONUP:
x2 = x
y2 = y
goFlag = 1
if event == cv2.EVENT_MOUSEWHEEL:
goFlag = 0
x1 = x2 = y1 = y2 = 0
def nothing(x):
pass
#Create Pan Tilt trackbars for first initialization
def create_panTilt_trackbars():
cv2.namedWindow('Trackbars')
cv2.createTrackbar('Pan', 'Trackbars',90,180,nothing)
cv2.createTrackbar('Tilt', 'Trackbars',90,180,nothing)
cv2.moveWindow('Trackbars',1320,0)
class Point:
def __init__(self, x, y):
self.x = x * (WIDTH/DISPLAY_WIDTH)
self.y = y * (HEIGHT/DISPLAY_HEIGHT)
#Class camera for change position
class imxCamera:
def __init__(self, pan , tilt):
self.pan = pan
self.tilt = tilt
def changePosition(pan ,tilt):
if pan > 180 or tilt > 180 or pan<0 or tilt<0:
print("pan or tilt cannot be more than 180")
return 1
kit.servo[0].angle = pan
kit.servo[1].angle = tilt
#Class camera for each frame of the session
class FrameView:
def __init__(self):
self.frame_pan = 90
self.frame_tilt = 90
self.roi = np.zeros(4)
def __str__(self):
return'Roi: {self.roi} pan {self.frame_pan} tilt: {self.frame_tilt}'.format(self = self)
#Set the roi from the user
def setRoi(self):
ret, frame = cam.read()
frame = cv2.resize(frame,(640 , 480))
cv2.imshow('nanoCam',frame)
cv2.moveWindow('nanoCam',0,0)
cv2.setMouseCallback('nanoCam', mouse_click)
if goFlag == 1:
frame=cv2.rectangle(frame,(x1,y1),(x2,y2),(255,0,0),3)
region_of_interest = cv2.rectangle(frame,(x1,y1),(x2,y2),(255,0,0), 3)
cv2.imshow('nanoCam', region_of_interest)
#get the roi to the frame roi
def getRoi(self):
self.roi[0] = x1*WIDTH/DISPLAY_WIDTH
self.roi[1] = x2*WIDTH/DISPLAY_WIDTH
self.roi[2] = y1*HEIGHT/DISPLAY_HEIGHT
self.roi[3] = y2*HEIGHT/DISPLAY_HEIGHT
#show the roi
def showRoi(self,frame, mode):
frame=cv2.rectangle(frame,(int(self.roi[0]),int(self.roi[2])),(int(self.roi[1]),int(self.roi[3])),(255,0,0),3)
region_of_interest = cv2.rectangle(frame,(int(self.roi[0]),int(self.roi[2])),(int(self.roi[1]),int(self.roi[3])),(255,0,0), 3)
if mode == 0:
frame = cv2.resize(frame,(640 , 480))
cv2.imshow('nanoCam', region_of_interest)
#init the first frame
def initFrame1(self):
while True:
self.frame_pan = cv2.getTrackbarPos('Pan','Trackbars')
self.frame_tilt = cv2.getTrackbarPos('Tilt', 'Trackbars')
if (imxCamera.changePosition(self.frame_pan, self.frame_tilt)) == 1:
print("Failed to initialize frame:")
print("Frame cannot be over 180 degrees or less than 0")
return False
FrameView.setRoi(self)
if cv2.waitKey(1)==ord('1'):
FrameView.getRoi(self)
return True
if cv2.waitKey(1)==ord('q'):
return False
#init any other frame with frame_frame_idx
def initRightFrame(self, frame_frame_idx, pan, tilt):
self.frame_tilt = tilt
self.frame_pan = pan
self.frame_pan = self.frame_pan - FOV*(frame_frame_idx-1)
if (imxCamera.changePosition(self.frame_pan, self.frame_tilt)) == 1:
print("Failed to initialize frame:")
print("Frame cannot be over 180 degrees or less than 0")
return False
while True:
FrameView.setRoi(self)
if cv2.waitKey(1)==ord(str(frame_frame_idx)):
FrameView.getRoi(self)
return True
if cv2.waitKey(1)==ord('q'):
return False
#show the frame includes the roi
def showFrame(self, frame, mode):
imxCamera.changePosition(self.frame_pan, self.frame_tilt)
FrameView.showRoi(self, frame, mode)
def personDetector(frame, frame_idx, numberOfFrames, FRAME_CHANGED_FLAG, NO_PERSON_FLAG, class_names, net, CONFIDENCE_THRESHOLD, NMS_THRESHOLD, COLORS):
model = cv2.dnn_DetectionModel(net)
model.setInputParams(size=(416, 416), scale=1/255, swapRB=True)
classes, scores, boxes = model.detect(frame, CONFIDENCE_THRESHOLD, NMS_THRESHOLD)
boundingBox = np.zeros(4)
for (classid, score, boundingBox) in zip(classes, scores, boxes):
color = COLORS[int(classid) % len(COLORS)]
label = "%s : %f" % (class_names[classid[0]], score)
(startX, startY, w, h) = boundingBox.astype("int")
endX = startX + w
endY = startY + h
cv2.rectangle(frame, boundingBox, color, 2)
cv2.putText(frame, label, (boundingBox[0], boundingBox[1] - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, color, 2)
#Dealing with latency between servo and frame
if FRAME_CHANGED_FLAG>0:
print("Frame changed flag: " , FRAME_CHANGED_FLAG)
FRAME_CHANGED_FLAG = FRAME_CHANGED_FLAG+1
if FRAME_CHANGED_FLAG > 3:
FRAME_CHANGED_FLAG = 0
return frame, frame_idx, FRAME_CHANGED_FLAG, NO_PERSON_FLAG, boundingBox
#Checking what direction subject goes
frame_idx, FRAME_CHANGED_FLAG = checkDirection(startX,endX,frame_idx,FRAME_CHANGED_FLAG, numberOfFrames)
return frame, frame_idx, FRAME_CHANGED_FLAG, NO_PERSON_FLAG, boundingBox
#IF NO PERSON IN THE PIC FOR MORE THAN 10 FRAMES BACK TO BEGINNING
NO_PERSON_FLAG = NO_PERSON_FLAG + 1
if NO_PERSON_FLAG > 0:
if NO_PERSON_FLAG > 50:
frame_idx = 0
NO_PERSON_FLAG = 0
return frame, frame_idx, FRAME_CHANGED_FLAG, NO_PERSON_FLAG, boundingBox
def checkDirection(startX, endX, frame_idx, FRAME_CHANGED_FLAG, numberOfFrames):
if endX>WIDTH-50:
if frame_idx == numberOfFrames:
print("frame index cannot be more then number of frames")
return frame_idx, FRAME_CHANGED_FLAG
frame_idx = frame_idx + 1
print("Frame idx end" , frame_idx, "EndX ", endX)
FRAME_CHANGED_FLAG = 1
if startX<50:
if frame_idx == 0:
print("frame index cannot be less then number of frames")
return frame_idx, FRAME_CHANGED_FLAG
frame_idx = frame_idx - 1
FRAME_CHANGED_FLAG = 1
print("Begin" , frame_idx , "StartX : " , startX)
return frame_idx, FRAME_CHANGED_FLAG
def isInRoi(boundingBox, frame_right, frame_idx):
(startX, startY, w, h) = boundingBox.astype("int")
print("Frame IDX: " ,frame_idx)
RoiBoxLeftUp = Point(frame_right[frame_idx].roi[0],frame_right[frame_idx].roi[2])
RoiBoxLeftDown = Point(frame_right[frame_idx].roi[0],frame_right[frame_idx].roi[3])
RoiBoxRightUp = Point(frame_right[frame_idx].roi[1],frame_right[frame_idx].roi[2])
RoiBoxRightDown = Point(frame_right[frame_idx].roi[1],frame_right[frame_idx].roi[3])
BoundingBoxLeftUp = Point(startX, startY)
BoundingBoxLeftDown = Point(startX, startY + h)
BoundingBoxRightUp = Point(startX + w, startY)
BoundingBoxRightDown = Point(startX + w, startY + h)
if(doOverlap(BoundingBoxLeftUp, BoundingBoxLeftDown, BoundingBoxRightUp, BoundingBoxRightDown,
RoiBoxLeftUp, RoiBoxLeftDown, RoiBoxRightUp, RoiBoxRightDown)==True):
return True
else:
return False
def doOverlap(BoundingBoxLeftUp, BoundingBoxLeftDown, BoundingBoxRightUp, BoundingBoxRightDown,
RoiBoxLeftUp, RoiBoxLeftDown, RoiBoxRightUp, RoiBoxRightDown):
#Check if one of the bounding box points in the roi rectangle
if (BoundingBoxLeftUp.x > RoiBoxLeftDown.x and BoundingBoxLeftUp.x < RoiBoxRightDown.x) and (BoundingBoxLeftUp.y > RoiBoxLeftUp.y and BoundingBoxLeftUp.y < RoiBoxLeftDown.y):
return True
if (BoundingBoxRightUp.x > RoiBoxLeftDown.x and BoundingBoxRightUp.x < RoiBoxRightDown.x) and (BoundingBoxRightUp.y > RoiBoxLeftUp.y and BoundingBoxRightUp.y < RoiBoxLeftDown.y):
return True
if (BoundingBoxRightDown.x > RoiBoxLeftDown.x and BoundingBoxRightDown.x < RoiBoxRightDown.x) and (BoundingBoxRightDown.y > RoiBoxLeftUp.y and BoundingBoxRightDown.y < RoiBoxLeftDown.y):
return True
if (BoundingBoxLeftDown.x > RoiBoxLeftDown.x and BoundingBoxLeftDown.x < RoiBoxRightDown.x) and (BoundingBoxLeftDown.y > RoiBoxLeftUp.y and BoundingBoxLeftDown.y < RoiBoxLeftDown.y):
return True
#Check if one of the roi box points in the bounding box rectangle
if (RoiBoxLeftUp.x > BoundingBoxLeftDown.x and RoiBoxLeftUp.x < BoundingBoxRightDown.x) and (RoiBoxLeftUp.y > BoundingBoxLeftUp.y and RoiBoxLeftUp.y < BoundingBoxLeftDown.y):
return True
if (RoiBoxRightUp.x > BoundingBoxLeftDown.x and RoiBoxRightUp.x < BoundingBoxRightDown.x) and (RoiBoxRightUp.y > BoundingBoxLeftUp.y and RoiBoxRightUp.y < BoundingBoxLeftDown.y):
return True
if (RoiBoxRightDown.x > BoundingBoxLeftDown.x and RoiBoxRightDown.x < BoundingBoxRightDown.x) and (RoiBoxRightDown.y > BoundingBoxLeftUp.y and RoiBoxRightDown.y < BoundingBoxLeftDown.y):
return True
if (RoiBoxLeftDown.x > BoundingBoxLeftDown.x and RoiBoxLeftDown.x < BoundingBoxRightDown.x) and (RoiBoxLeftDown.y > BoundingBoxLeftUp.y and RoiBoxLeftDown.y < BoundingBoxLeftDown.y):
return True
return False
Encodings=[]
Names=[]
def classifyAndBackup(known_image_dir, unknown_image_dir, backup, frame_right, SuspectThreshhold, frame_idx, model):
score = isSuspect(known_image_dir, unknown_image_dir, model)
print(score)
shutil.move(unknown_image_dir, backup)
dateTime = str(datetime.datetime.now())
newBackupPath = '/home/rami/Desktop/SmartCam/Pictures/backup/'+dateTime+''
os.rename('/home/rami/Desktop/SmartCam/Pictures/backup/unknown' , newBackupPath)
os.mkdir(unknown_image_dir)
pathToExamplePic = newBackupPath+'/0_unknown.png'
if score > SuspectThreshhold:
frame_idx = 0
shutil.rmtree(newBackupPath)
else:
SendMail(pathToExamplePic)
ResizeAllPicturesInFOlder(newBackupPath)
MegaNZ.CreateUploadDeleteOld(newBackupPath, dateTime, newBackupPath)
WriteFrameToFile(frame_idx)
return score
def isSuspect(known_image_dir, unknown_image_dir, model):
scan_known_images(known_image_dir)
return scan_unknow_images(unknown_image_dir, model)
def scan_known_images(known_image_dir):
for root, dirs, files in os.walk(known_image_dir):
print(files)
for file in files:
path=os.path.join(root,file)
print(path)
name=os.path.splitext(file)[0]
print(name)
person=face_recognition.load_image_file(path)
encoding=face_recognition.face_encodings(person)[0]
Encodings.append(encoding)
Names.append(name)
print(Names)
font=cv2.FONT_HERSHEY_SIMPLEX
def scan_unknow_images(unknown_image_dir, model_net):
vec = []
for root,dirs, files in os.walk(unknown_image_dir):
for file in files:
print(root)
print(file)
testImagePath=os.path.join(root,file)
testImage=face_recognition.load_image_file(testImagePath)
facePositions=face_recognition.face_locations(testImage, model=model_net)
allEncodings=face_recognition.face_encodings(testImage,facePositions)
testImage=cv2.cvtColor(testImage,cv2.COLOR_RGB2BGR)
for (top,right,bottom,left),face_encoding in zip(facePositions,allEncodings):
name='Known'
matches=face_recognition.compare_faces(Encodings,face_encoding)
if True in matches:
first_match_index=matches.index(True)
name=Names[first_match_index]
print("True match")
vec.append(1)
vec.append(0)
print(vec)
confidence = calculate_statistic(vec)
print("Scan Unknown Images" , confidence)
return confidence
if cv2.waitKey(0)==ord('q'):
cv2.destroyAllWindows()
def calculate_statistic(vec):
len_vec = len(vec) # 0 - number of pictures 1 - true result
true_results = countOccurrences(vec,len_vec,1)
number_of_pictures = countOccurrences(vec,len_vec,0)
confidence = true_results/number_of_pictures
confidence = confidence * 100 #For Pecentage
print("calculate_statistic" , confidence)
return confidence
def countOccurrences(arr, n, x):
res = 0
for i in range(n):
if x == arr[i]:
res += 1
return res
def SendMail(ImgFileName):
port = 587 # For starttls
smtp_server = "smtp.gmail.com"
img_data = open(ImgFileName, 'rb').read()
msg = MIMEMultipart()
msg['Subject'] = 'Suspect in the house: '
msg['From'] = 'razmichaelhit@gmail.com'
msg['To'] = 'razmichaelhit@gmail.com'
password = "Hit123456!"
username = "razmichaelhit@gmail.com"
sender_mail = username
reciever_mail = "razmichaelhit@gmail.com"
text = MIMEText("Suspect has been found in the garden")
msg.attach(text)
image = MIMEImage(img_data, name=os.path.basename(ImgFileName))
msg.attach(image)
server = smtplib.SMTP(smtp_server, port)
server.ehlo()
server.starttls()
server.ehlo()
server.login(username, password)
server.sendmail(sender_mail, reciever_mail, msg.as_string())
server.quit()
def WriteFrameToFile(frame_idx):
f = open("./cfg/frame_idx.txt", "w")
f.write(str(frame_idx))
f.close()
def ResizeAllPicturesInFOlder(path):
lst_imgs = [i for i in glob.glob(path+"/*.png")]
print(lst_imgs)
for i in lst_imgs:
img = Image.open(i)
img = img.resize((500, 500), Image.ANTIALIAS)
img.save(i[:-4] +".png")
print("Done")
def deleteAllFilesInFolder(path):
for filename in os.listdir(path):
file_path = os.path.join(path, filename)
try:
if os.path.isfile(file_path) or os.path.islink(file_path):
os.unlink(file_path)
elif os.path.isdir(file_path):
shutil.rmtree(file_path)
except Exception as e:
print('Failed to delete %s. Reason: %s' % (file_path, e))
def setDNNParams():
#configuring yolo model
net = cv2.dnn.readNet("./cfg/Tinyyolov4_personDetection.weights", "./cfg/Tinyyolov4_personDetection.cfg")
net.setPreferableBackend(cv2.dnn.DNN_BACKEND_CUDA)
net.setPreferableTarget(cv2.dnn.DNN_TARGET_CUDA)
return net
def setClassNames():
#open class txt file (Person)
class_names = []
with open("./cfg/classes.txt", "r") as f:
class_names = [cname.strip() for cname in f.readlines()]
return class_names
def checkThreadResults(frame_idx, lock_thread):
f = open("./cfg/frame_idx.txt", "r")
frame_idx_text = f.read()
frame_idx_text = int(frame_idx_text)
if frame_idx_text == 0:
frame_idx = 0
f = open("./cfg/frame_idx.txt", "w")
f.write("NULL")
lock_thread = 0
if frame_idx_text > 0 and frame_idx_text < 10:
f = open("./cfg/frame_idx.txt", "w")
f.write("NULL")
lock_thread = 0
return frame_idx, lock_thread
def init_number_of_frames(frame_right, number_of_frames_to_init):
#init first frame
frame_right.append(FrameView())
if (frame_right[0].initFrame1()) == False:
cam.release()
cv2.destroyAllWindows()
return frame_right, False
print(frame_right[0])
if number_of_frames_to_init >1:
i = 1
while i < number_of_frames_to_init:
frame_right.append(FrameView())
if (frame_right[i].initRightFrame(i+1, frame_right[0].frame_pan, frame_right[0].frame_tilt)) == False:
cam.release()
cv2.destroyAllWindows()
return frame_right, False
print(frame_right[i])
i = i + 1
return frame_right, True
#main func
def main():
args = parser()
check_arguments_errors(args)
#If show video , reduce resources use by changing classification model to hog model. less accuracy
if args.mode == 0:
args.model = "hog"
create_panTilt_trackbars()
#transverse array of frames
frame_right = []
number_of_frames_to_init = 2
#initialize frames
frame_right, status = init_number_of_frames(frame_right, args.frames)
if status == False:
return False
cv2.destroyAllWindows()
#FRAME_CHANGED_FLAG - if frame has been changed , stop tracking the object for number of loops, keep from latency bugsglobal FRAME_CHANGED_FLAG
FRAME_CHANGED_FLAG = 1
CONFIDENCE_THRESHOLD = 0.4
NMS_THRESHOLD = 0.4
COLORS = [(0, 255, 255), (255, 255, 0), (0, 255, 0), (255, 0, 0)]
#Clean unknown image dir
deleteAllFilesInFolder(args.unknown_dir)
#Set person class
class_names = setClassNames()
#Threshhold of how many pictures true of all pictures, in percentage
SuspectThreshhold = 20
#configuring yolo model
net = setDNNParams()
frame_idx = 0
i = 0
#Flag to know how many pictures to process
PROCESSING_FLAG = 0
#If there is no person any more in the picture back to beginning
NO_PERSON_FLAG = 0
#timer to starting classify tread
timer = 0
#lock thread flag
lock_thread = 0
while True:
ret, frame2 = cam.read()
ret, frame = cam.read()
#frame = cv2.resize(frame,(640 , 480))
frame_right[frame_idx].showFrame(frame, args.mode)
if PROCESSING_FLAG==2 or PROCESSING_FLAG == 3:
frame, frame_idx, FRAME_CHANGED_FLAG, NO_PERSON_FLAG, boundingBox = personDetector(frame, frame_idx, number_of_frames_to_init, FRAME_CHANGED_FLAG, NO_PERSON_FLAG, class_names, net, CONFIDENCE_THRESHOLD, NMS_THRESHOLD, COLORS)
if args.mode == 0:
frame = cv2.resize(frame,(640 , 480))
cv2.imshow("nanoCam", frame)
PROCESSING_FLAG = PROCESSING_FLAG + 1
try:
numberOfPicturesInFolder = len([name for name in os.listdir(args.unknown_dir) if os.path.isfile(os.path.join(args.unknown_dir, name))])
except:
continue
#If bounding box inside the ROI then start take pictures
if isInRoi(boundingBox, frame_right, frame_idx):
if numberOfPicturesInFolder < 5 and i <5:
cv2.imwrite(args.unknown_dir+'/'+str(i)+'_unknown.png',frame2)
i = i + 1
#If there are 30 pics in the folder start classify thread
if i == 5 and lock_thread == 0:
classify_thread = threading.Thread(target = classifyAndBackup, args=(args.known_dir, args.unknown_dir, args.backup_dir, frame_right, SuspectThreshhold, frame_idx, args.model))
classify_thread.start()
lock_thread = 1
i = 0
#if timer over 100 frames and there is no processing thread on start classify thread
if timer > 100 and lock_thread == 0:
classify_thread = threading.Thread(target = classifyAndBackup, args=(args.known_dir, args.unknown_dir, args.backup_dir, frame_right, SuspectThreshhold, frame_idx, args.model))
classify_thread.start()
lock_thread = 1
timer = 0
#Start timer if there are any pics left in the unknown folder
if numberOfPicturesInFolder > 0:
timer = timer + 1
print("timer: " ,timer)
if numberOfPicturesInFolder == 0:
timer = 0
print("lock_thread: ",lock_thread)
#if no suspect return to frame 1
try:
frame_idx, lock_thread = checkThreadResults(frame_idx, lock_thread)
except:
nothing(1)
if PROCESSING_FLAG==4:
PROCESSING_FLAG = 0
else:
if args.mode == 0:
frame = cv2.resize(frame,(640 , 480))
cv2.imshow("nanoCam", frame)
# if the `q` key was pressed, break from the loop
PROCESSING_FLAG = PROCESSING_FLAG + 1
if cv2.waitKey(1) == ord("q"):
break
cam.release()
cv2.destroyAllWindows()
if __name__ == '__main__':
main()
|
{"/SmartCam.py": ["/MegaNZ.py"]}
|
16,867,594
|
imeteora/SmartCam
|
refs/heads/main
|
/MegaNZ.py
|
from mega import Mega
import os
import shutil
def connectToMega():
email = 'razmichaelhit@gmail.com'
password = 'Hit123456!'
mega = Mega()
m = mega.login(email,password)
return m
def createFolderInMega(m , name):
m.create_folder(name)
def uploadFolderToMega(m, src, dst):
for filename in os.listdir(src):
filePath = src+'/'+filename
folder_destination = m.find(dst)
m.upload(filePath, folder_destination[0])
def CreateUploadDeleteOld(sourceFolder, megaFolder, folderToDelete):
connection = connectToMega()
createFolderInMega(connection, megaFolder)
uploadFolderToMega(connection, sourceFolder, megaFolder)
shutil.rmtree(folderToDelete)
|
{"/SmartCam.py": ["/MegaNZ.py"]}
|
16,867,595
|
imeteora/SmartCam
|
refs/heads/main
|
/Test.py
|
import numpy as np
import cv2
from adafruit_servokit import ServoKit
print(cv2.__version__)
dispW=1920
dispH=1080
#Uncomment These next Two Line for Pi Camera
camSet='nvarguscamerasrc ! video/x-raw(memory:NVMM), width=3264, height=2464, format=NV12, framerate=21/1 ! nvvidconv ! video/x-raw, width='+str(dispW)+', height='+str(dispH)+', format=BGRx ! videoconvert ! video/x-raw, format=BGR ! appsink'
name= 'Raz'
#camSet='nvarguscamerasrc sensor-id=-0 ! video/x-raw(memory:NVMM), width=3264, height=2464, framerate=21/1, format=NV12 ! nvvidconv flip-method=2 ! video/x-raw, width=800, height=600, format=BGRx ! videoconvert ! video/x-raw, format=BGR ! appsink'
cam= cv2.VideoCapture(camSet)
#Or, if you have a WEB cam, uncomment the next line
#(If it does not work, try setting to '1' instead of '0')
#cam=cv2.VideoCaptur%e(0)
i=1
kit=ServoKit(channels=16)
def nothing(x):
pass
def create_panTilt_trackbars():
cv2.namedWindow('Trackbars')
cv2.createTrackbar('Pan', 'Trackbars',90,180,nothing)
cv2.createTrackbar('Tilt', 'Trackbars',90,180,nothing)
cv2.moveWindow('Trackbars',1320,0)
create_panTilt_trackbars()
#Class camera for change position
class imxCamera:
def __init__(self, pan , tilt):
self.pan = pan
self.tilt = tilt
def changePosition(pan ,tilt):
if pan > 180 or tilt > 180 or pan<0 or tilt<0:
print("pan or tilt cannot be more than 180")
return 1
kit.servo[0].angle = pan
kit.servo[1].angle = tilt
while True:
pan = cv2.getTrackbarPos('Pan','Trackbars')
tilt = cv2.getTrackbarPos('Tilt', 'Trackbars')
ret, frame = cam.read()
imxCamera.changePosition(pan,tilt)
cv2.imshow('nanoCam',frame)
if cv2.waitKey(1)==ord('p'):
cv2.imwrite('/home/rami/Desktop/SmartCam/Pictures/known/'+str(i)+name+'.png',frame)
i = i + 1
if cv2.waitKey(1)==ord('q'):
break
cam.release()
cv2.destroyAllWindows()
|
{"/SmartCam.py": ["/MegaNZ.py"]}
|
16,893,117
|
rittwickBhabak/Task-manager
|
refs/heads/main
|
/test2.py
|
from app import db, Tasks, Reps
tasks = Tasks.query.all()
for t in tasks:
print(t.name, t.id)
|
{"/app.py": ["/myproject/models.py", "/myproject/forms.py", "/repDates.py"], "/repDates.py": ["/dateComparator.py", "/getDatesInSpecificInterval.py", "/getNextOrPreviousDay.py"], "/getDatesInSpecificInterval.py": ["/getNextOrPreviousDay.py"], "/test.py": ["/app.py"], "/test2.py": ["/app.py"]}
|
16,893,118
|
rittwickBhabak/Task-manager
|
refs/heads/main
|
/test.py
|
from app import db, Reps, Tasks
import datetime
# # db.create_all()
# task1 = Tasks('Task1', 'asldkfjasf')
# task2 = Tasks('Task2', 'asdklfjasdf')
# task3 = Tasks('Task3', '8usdafjffasfjd')
# db.session.add_all([task1, task2, task3])
# db.session.commit()
# for i in range(1, 4):
# rep1 = Reps(datetime.date(2020,10, 25), i, 0)
# rep2 = Reps(datetime.date(2020,10, 25), i, 0)
# db.session.add_all([rep1, rep2])
# db.session.commit()
# rep = Reps(datetime.date(2020,10, 26), 1, 0)
# db.session.add(rep)
# db.session.commit()
# rep1 = Reps(datetime.date(2020, 12, 10), 1, 0)
# rep2 = Reps(datetime.date(2020, 12, 1), 1, 0)
# db.session.add(rep1)
# db.session.commit()
# db.session.add(rep2)
# db.session.commit()
# a = None
# b = None
reps = Reps.query.all()
for rep in reps:
print(rep.date)
print(type(rep.date))
# if a is None:
# a = rep.date.date()
# b = rep.date.date()
# else:
# b = rep.date.date()
# print(a<b)
# import datetime
# s = '2020-02-2'
# print(date)
|
{"/app.py": ["/myproject/models.py", "/myproject/forms.py", "/repDates.py"], "/repDates.py": ["/dateComparator.py", "/getDatesInSpecificInterval.py", "/getNextOrPreviousDay.py"], "/getDatesInSpecificInterval.py": ["/getNextOrPreviousDay.py"], "/test.py": ["/app.py"], "/test2.py": ["/app.py"]}
|
16,893,119
|
rittwickBhabak/Task-manager
|
refs/heads/main
|
/app.py
|
from flask import Flask, url_for, redirect, request, render_template, flash, current_app
import os
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
import time
import datetime
basedir = os.path.abspath(os.path.dirname(__file__))
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + os.path.join(basedir, 'data.sqlite')
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
app.secret_key = 'super secret key'
db = SQLAlchemy(app)
Migrate(app, db)
class Tasks(db.Model):
__tablename__ = 'tasks'
id = db.Column(db.Integer, primary_key=True)
desc = db.Column(db.String)
name = db.Column(db.String, unique=True)
reps = db.relationship('Reps', cascade="all,delete", backref='tasks', lazy='dynamic')
def __init__(self, name, desc):
self.name = name
self.desc = desc
class Reps(db.Model):
__tablename__ = 'reps'
id = db.Column(db.Integer, primary_key=True)
date = db.Column(db.DateTime)
status = db.Column(db.Integer)
task = db.Column(db.Integer, db.ForeignKey('tasks.id'))
def __init__(self, date, task, status):
self.task = task
self.date = date
self.status = status
@app.route('/')
def index():
today = datetime.datetime.now().date()
# today = datetime.date(2020,10,29)
# today is in the form yyyy-mm-dd
reps = Reps.query.all()
list_of_reps = []
for r in reps:
print(r.date)
y, m, d = str(r.date).split()[0].split('-')
y = int(y)
m = int(m)
d = int(d)
date = datetime.date(y,m,d)
if date==today:
task = Tasks.query.get(r.task)
rep = { 'name': task.name, 'id': r.id, 'status': r.status, 'task': task.id }
list_of_reps.append(rep)
params = {
'reps': list_of_reps,
'today': today.strftime('%d, %b %Y')
}
return render_template('index.html', params=params)
@app.route('/new', methods=['GET', 'POST'])
def newtask():
if request.method=='POST':
name = request.form['name']
desc = request.form['desc']
dates = request.form['dates'].split(',')
print(name, desc, dates)
# flash('success', 'success')
# return redirect(url_for('newtask'))
task = Tasks(name, desc)
try:
db.session.add(task)
db.session.commit()
task = Tasks.query.filter_by(name=name)[0]
id = task.id
for date in dates:
date = datetime.date(*list(map(lambda x: int(x), date.split('-'))))
rep = Reps(date, id, 0)
db.session.add(rep)
db.session.commit()
flash('Task added successful.', 'success')
return redirect(url_for('task', id=id))
except Exception as e:
msg = "Either the task name already exists or some internal error occoured."
# msg = str(e)
flash(msg, 'danger')
params = {
'task': task,
'desc': desc,
'dates': ','.join(dates)
}
return render_template('newtask.html', params=None)
else:
return render_template('newtask.html', params=None)
@app.route('/task/<int:id>')
def task(id):
task = Tasks.query.get(id)
reps = Reps.query.filter_by(task=task.id).order_by(Reps.date)
params = {
'task': task,
'reps': reps
}
return render_template('task.html', params=params)
@app.route('/update/<int:id>', methods=['GET', 'POST'])
def update(id):
task = Tasks.query.get(id)
reps = Reps.query.filter_by(task=task.id)
dates = []
for r in reps:
dates.append(str(r.date).split()[0])
dates = ','.join(dates)
if request.method == 'GET':
params = {
'task': task,
'reps': reps,
'dates': dates
}
return render_template('newtask.html', params=params)
else:
new_name = request.form['name']
new_desc = request.form['desc']
new_dates = request.form['dates'].split(',')
task.name = new_name
task.desc = new_desc
db.session.add(task)
db.session.commit()
reps = Reps.query.filter_by(task=id)
for rep in reps:
db.session.delete(rep)
db.session.commit()
for date in list(set(new_dates)):
date = datetime.date(*list(map(lambda x: int(x), date.split('-'))))
rep = Reps(date, id, 0)
db.session.add(rep)
db.session.commit()
flash('Task updated successful', 'success')
return redirect(url_for('task', id=id))
@app.route('/delete/<int:id>', methods=['GET', 'POST'])
def delete(id):
task = Tasks.query.get(id)
if request.method == 'POST':
db.session.delete(task)
db.session.commit()
flash('Task successfully deleted', 'success')
return redirect(url_for('index'))
@app.route('/alltask')
def alltask():
tasks = Tasks.query.all()
params = {
'tasks': tasks
}
return render_template('tasklist.html', params=params)
@app.route('/finishrep/<int:id>', methods=['GET', 'POST'])
def finishrep(id):
rep = Reps.query.get(id)
task = Tasks.query.get(rep.task)
if request.method == 'POST':
rep.status = 1
db.session.add(rep)
db.session.commit()
flash('1 Task completed', 'success')
return redirect(url_for('index'))
@app.route('/undonerep/<int:id>', methods=['GET', 'POST'])
def undonerep(id):
rep = Reps.query.get(id)
task = Tasks.query.get(rep.task)
if request.method == 'POST':
rep.status = 0
db.session.add(rep)
db.session.commit()
flash('1 task undone', 'success')
return redirect(url_for('index'))
@app.route('/privious-undone-tasks')
def undonePrev():
today = datetime.datetime.now().date()
# today = datetime.date(2020,10,29)
# today is in the form yyyy-mm-dd
reps = Reps.query.all()
list_of_reps = []
for r in reps:
print(r.date)
y, m, d = str(r.date).split()[0].split('-')
y = int(y)
m = int(m)
d = int(d)
date = datetime.date(y,m,d)
if date<=today and r.status==0:
task = Tasks.query.get(r.task)
rep = { 'name': task.name, 'id': r.id, 'status': r.status, 'task': task.id, 'date': r.date }
list_of_reps.append(rep)
params = {
'reps': list_of_reps,
'header': 'Previous Undone Tasks'
}
return render_template('otherdaytasks.html', params=params)
@app.route('/tomorrow')
def tomorrowTasks():
today = datetime.datetime.now().date()
# today = datetime.date(2020,10,29)
# today is in the form yyyy-mm-dd
tomorrow = datetime.date.today() + datetime.timedelta(days=1)
print(tomorrow)
reps = Reps.query.all()
list_of_reps = []
for r in reps:
# print(r.date)
y, m, d = str(r.date).split()[0].split('-')
y = int(y)
m = int(m)
d = int(d)
date = datetime.date(y,m,d)
if date==tomorrow:
task = Tasks.query.get(r.task)
rep = { 'name': task.name, 'id': r.id, 'status': r.status, 'task': task.id, 'date': r.date }
list_of_reps.append(rep)
params = {
'reps': list_of_reps,
'header': 'Tomorrow\'s Tasks',
'date': tomorrow
}
return render_template('otherdaytasks.html', params=params)
@app.route('/goto')
def goto():
y, m, d = request.args.get('date').split('-')
gotoDate = datetime.date(int(y),int(m),int(d))
reps = Reps.query.all()
list_of_reps = []
for r in reps:
# print(r.date)
y, m, d = str(r.date).split()[0].split('-')
y = int(y)
m = int(m)
d = int(d)
date = datetime.date(y,m,d)
if date==gotoDate:
task = Tasks.query.get(r.task)
rep = { 'name': task.name, 'id': r.id, 'status': r.status, 'task': task.id, 'date': r.date }
list_of_reps.append(rep)
params = {
'reps': list_of_reps,
'header': 'Tasks',
'date': gotoDate
}
return render_template('otherdaytasks.html', params=params)
if __name__ == "__main__":
app.run(debug=True)
|
{"/app.py": ["/myproject/models.py", "/myproject/forms.py", "/repDates.py"], "/repDates.py": ["/dateComparator.py", "/getDatesInSpecificInterval.py", "/getNextOrPreviousDay.py"], "/getDatesInSpecificInterval.py": ["/getNextOrPreviousDay.py"], "/test.py": ["/app.py"], "/test2.py": ["/app.py"]}
|
16,898,052
|
alperiox/fsdtorch
|
refs/heads/master
|
/examples/live_cam.py
|
import cv2
import numpy as np
from fsdtorch.inference import predict_shape
cam = cv2.VideoCapture(0)
while cam.isOpened():
success, input_frame = cam.read()
frame = cv2.cvtColor(input_frame, cv2.COLOR_BGR2RGB)
class_id, class_name, confidence = predict_shape(frame)
print("Predicted class id: {} | class name: {} | confidence: {}".format(class_id, class_name, confidence))
cv2.imshow("Live Source", input_frame)
if cv2.waitKey(1) & 0xFF == 27: # ESC ile çıkış yapılır
cv2.destroyAllWindows()
break
|
{"/examples/live_cam.py": ["/fsdtorch/inference.py"]}
|
16,898,053
|
alperiox/fsdtorch
|
refs/heads/master
|
/examples/example_usage.py
|
from fsdtorch import inference
image_path = "example.jpg"
image = cv2.imread(image_path)
image_rgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
class_id, class_name, confidence = inference(image_rgb)
print(class_id, class_name, confidence)
cv2.imshow("Example Input", image_rgb)
|
{"/examples/live_cam.py": ["/fsdtorch/inference.py"]}
|
16,898,054
|
alperiox/fsdtorch
|
refs/heads/master
|
/inference.py
|
import cv2
import numpy as np
import onnx
import onnxruntime
import os
import gdown
idx_to_class = {0: 'Heart', 1: 'Oblong', 2: 'Oval', 3: 'Round', 4: 'Square'}
model_name = "2021911-8.21-pretrained_resnetv1.onnx"
if model_name not in os.listdir(os.getcwd()):
print("[HATA] Pretrained model bulunamadı!")
print("[] Google drive üzerinden model indiriliyor...")
url = 'https://drive.google.com/uc?id=1A2pCRXjpfnZ8yrPbJLHZVHqgi0R7jqzb'
output = model_name
gdown.download(url, output, quiet = False)
print("[] Model indirildi.")
else:
print("[] %s bulundu!"%model_name.split('-')[1])
onnx_model = onnx.load(model_name)
onnx.checker.check_model(onnx_model)
ort_session = onnxruntime.InferenceSession(model_name)
def to_numpy(tensor):
""" istersek torch tensor girdi de verebiliriz """
return tensor.detach().cpu().numpy() if tensor.requires_grad else tensor.cpu().numpy()
def preprocess(input_frame):
"""
Verilen girdi frame ini düzenler, bu fonksiyon proje geneli için değil modelin çalışması için tasarlandı.
Dolayısıyla tahmin yaparken buraya gelen frame i önceden gerektiği gibi düzenleyip, sonra burada model için düzenlenmesine izin vermek gerekiyor.
Girdi:
input_frame - np.array: girdi framei
Çıktı:
frame - np.array: düzenlenip işlenen frame
"""
frame = np.copy(input_frame)
frame = frame / 255.
frame = cv2.resize(frame, (160, 160))
frame = np.expand_dims(frame.transpose(2, 0, 1), 0) # convert it to 1x3x160x160
frame = np.array(frame, dtype = np.float32)
return frame
def predict_shape(frame):
"""
Verilen frame i kullanarak frame de bulunan yüzü sınıflandırır ve şekli döndürür.
Bu fonksiyonu override ederek batchler halinde girdi göndermek mümkün
Kullanılan model: Fine-tunelanmış Inception_Resnetv1
Model google colabde fine-tune edildi:
https://drive.google.com/file/d/1EcWicvZAtQuggPhQn4Z0Y0Z6kJQspBZG/view?usp=sharing
Input:
frame - np.array: Tahmin için kaynak frame, RGB formatında olmalı.
Returns:
class_id - int: tahmin edilen sınıfın IDsi
class_name - string: class_id kullanılarak elde edilen sınıf ismi, idxten sınıf ismine geçmek için idx_to_class kullanılıyor
confidence - float: modelin tahmin confidence ı
"""
processed_frame = preprocess(frame)
inputs = {ort_session.get_inputs()[0].name: processed_frame}
ort_outs = ort_session.run(None, inputs)
out = ort_outs[0]
class_id = np.argmax(out)
class_name = idx_to_class[class_id]
confidence = out[0][class_id]
return class_id, class_name, confidence
|
{"/examples/live_cam.py": ["/fsdtorch/inference.py"]}
|
16,898,829
|
ling199104/coolpc_line_bot
|
refs/heads/master
|
/app.py
|
from controllers.line_bot import *
from os import environ
if __name__ == "__main__":
app.run(host='0.0.0.0', port=environ['PORT'])
|
{"/controllers/line_bot.py": ["/models/s3_storage.py", "/models/parser.py", "/settings.py"], "/app.py": ["/controllers/line_bot.py"], "/models/s3_storage.py": ["/settings.py"], "/models/chatterbot_train.py": ["/models/parser.py"]}
|
16,898,830
|
ling199104/coolpc_line_bot
|
refs/heads/master
|
/models/s3_storage.py
|
# from settings import keys
from settings import *
import boto3
# build aws s3 client
s3_client = boto3.client(
's3',
aws_access_key_id=AWS_ACCESS_KEY_ID,
aws_secret_access_key=AWS_SECRET_ACCESS_KEY
)
# example usage: s3_operation('upload', 'iii-tutorial-v2', 'student99/<filename>')
def s3_operation(operator, bucket, key, filename=None):
if operator == 'upload':
# upload object with aws s3 client
s3_client.upload_file(Bucket=bucket, Key=key, Filename=filename)
elif operator == 'download':
# download object with aws s3 client
s3_client.download_file(Bucket=bucket, Key=key, Filename=filename)
elif operator == 'delete':
# delete object with aws s3 client
s3_client.delete_object(Bucket=bucket, Key=key)
else:
print('operator missing or wrong typing')
|
{"/controllers/line_bot.py": ["/models/s3_storage.py", "/models/parser.py", "/settings.py"], "/app.py": ["/controllers/line_bot.py"], "/models/s3_storage.py": ["/settings.py"], "/models/chatterbot_train.py": ["/models/parser.py"]}
|
16,898,831
|
ling199104/coolpc_line_bot
|
refs/heads/master
|
/models/chatterbot_train.py
|
from chatterbot.trainers import ChatterBotCorpusTrainer, ListTrainer
from chatterbot import ChatBot
from models.parser import CoolPcCrawler
import re
first_soup = CoolPcCrawler.get_response()
cool_pc_data = CoolPcCrawler.get_data(first_soup)
chat_bot = ChatBot('Cool_PC_Raw')
trainer_corpus = ChatterBotCorpusTrainer(chat_bot)
trainer_corpus.train(
"chatterbot.corpus.english",
"chatterbot.corpus.traditionalchinese",
# "chatterbot.corpus.japanese"
)
# train with chinese character and first 10 word
# trainer_list = ListTrainer(chat_bot)
# for cool_pc_dataset in cool_pc_data:
# for item in cool_pc_dataset[-1]:
# # mix_words = ' '.join(re.findall(re.compile(u"[\u4e00-\u9fa5a-zA-Z0-9]+"), item))
# # trainer_list.train([mix_words, item])
# # trainer_list.train([item[0:15], item])
# # trainer_list.train([item, item])
# chinese_words = ' '.join(re.findall(re.compile(u"[\u4e00-\u9fa5]+"), item))
# trainer_list.train([chinese_words, item])
# english_words = ' '.join(re.findall(re.compile(u"[a-zA-Z0-9]+"), item))
# trainer_list.train([english_words, item])
|
{"/controllers/line_bot.py": ["/models/s3_storage.py", "/models/parser.py", "/settings.py"], "/app.py": ["/controllers/line_bot.py"], "/models/s3_storage.py": ["/settings.py"], "/models/chatterbot_train.py": ["/models/parser.py"]}
|
16,898,832
|
ling199104/coolpc_line_bot
|
refs/heads/master
|
/models/_coolpc_data.py
|
# import sqlite3
# connector = sqlite3.connect('db.sqlite3')
# table initialize
def table_init(connector):
c = connector.cursor()
# 資料建立時間、資料更新時間、商品屬類、商品名稱、商品圖片
# 商品價格、商品是否特價、商品是否熱賣、被檢索次數、被估價次數
c.execute(
'''CREATE TABLE products (create_date timestamp, update_date timestamp, item_type text, item_name text,
item_img blob, price integer, on_sale integer, hot_sale integer, search_count integer, match_count integer)'''
)
# 資料建立時間、資料更新時間、類別名稱
# 類別內參數:商品熱賣數、圖片數、文章數、價格異動數、現實下殺數
c.execute(
'''CREATE TABLE types (create_date timestamp, update_date timestamp, type_name text,
hot_sale integer, image_count integer, discussion integer, price_changed integer, on_sale integer)'''
)
# Save (commit) the changes
connector.commit()
connector.close()
# # Insert a row of data
# c.execute("INSERT INTO stocks VALUES ('2006-01-05','BUY','RHAT',100,35.14)")
|
{"/controllers/line_bot.py": ["/models/s3_storage.py", "/models/parser.py", "/settings.py"], "/app.py": ["/controllers/line_bot.py"], "/models/s3_storage.py": ["/settings.py"], "/models/chatterbot_train.py": ["/models/parser.py"]}
|
16,898,833
|
ling199104/coolpc_line_bot
|
refs/heads/master
|
/controllers/line_bot.py
|
import re
import json
import math
import random
from models.s3_storage import s3_client
from flask import Flask, request, abort, send_file
from models.parser import CoolPcCrawler
from settings import CHANNEL_ACCESS_TOKEN, CHANNEL_SECRET
from linebot import (
LineBotApi, WebhookHandler
)
from linebot.models import (
MessageEvent, TextMessage, TextSendMessage, FollowEvent, ImageMessage, QuickReply, QuickReplyButton, MessageAction,
TemplateSendMessage, ImageCarouselTemplate, ImageCarouselColumn, PostbackAction, ImageSendMessage
)
from linebot.exceptions import (
InvalidSignatureError
)
from chatterbot import ChatBot
# line handler start-up
line_bot_api = LineBotApi(CHANNEL_ACCESS_TOKEN)
handler = WebhookHandler(CHANNEL_SECRET)
# first of crawling data
first_soup = CoolPcCrawler.get_response()
cool_pc_data = CoolPcCrawler.get_data(first_soup)
# assign chatterbot
chat_bot = ChatBot('Cool_PC_Raw')
app = Flask(__name__)
@app.route("/images", methods=['GET'])
def get_image():
if request.args.get('name') == 'panda.jpg':
filename = '../statics/images/panda.jpg'
return send_file(filename, mimetype='image/gif')
elif request.args.get('name'):
filename = '../statics/images/{}'.format(request.args.get('name'))
return send_file(filename, mimetype='image/gif')
else:
abort(404, description="Resource not found")
@app.route("/", methods=['POST'])
def callback():
# get X-Line-Signature header value
signature = request.headers['X-Line-Signature']
# get request body as text
body = request.get_data(as_text=True)
app.logger.info("Request body: " + body)
# handle webhook body
try:
handler.handle(body, signature)
except InvalidSignatureError:
print("Invalid signature. Please check your channel access token/channel secret.")
abort(400)
return 'OK'
@handler.add(MessageEvent, message=TextMessage)
def handle_text_message(event):
global cool_pc_data
# read text from user
text = event.message.text
if text == "!我想重來" or text == "!使用教學":
line_bot_api.reply_message(
event.reply_token,
TextSendMessage(text='好的,沒問題!\n請問您有明確想找的商品嗎?', quick_reply=QuickReply(items=[
QuickReplyButton(action=MessageAction(label="是", text="!我有明確想找的商品")),
QuickReplyButton(action=MessageAction(label="否", text="!我沒有明確想找的商品"))
]))
)
elif text == "!我有明確想找的商品":
line_bot_api.reply_message(
event.reply_token,
TextSendMessage(text='請問您曉得確切的商品名稱嗎?', quick_reply=QuickReply(items=[
QuickReplyButton(action=MessageAction(label="是", text="!我知道我想找的商品名稱")),
QuickReplyButton(action=MessageAction(label="否", text="!我不知道我想找的商品名稱")),
QuickReplyButton(action=MessageAction(label="重來", text="!我想重來"))
]))
)
elif text == "!我沒有明確想找的商品":
line_bot_api.reply_message(
event.reply_token,
TextSendMessage(text='那麼您有特別想了解的商品類別嗎?例如:處理器 CPU', quick_reply=QuickReply(items=[
QuickReplyButton(action=MessageAction(label="是", text="!我有想了解的商品類別")),
QuickReplyButton(action=MessageAction(label="否", text="!我沒有特別想了解的商品類別")),
QuickReplyButton(action=MessageAction(label="重來", text="!我想重來"))
]))
)
elif text == "!我有想了解的商品類別" or text == '!我想看第一頁的分類':
# update data
soup = CoolPcCrawler.get_response()
cool_pc_data = CoolPcCrawler.get_data(soup)
line_bot_api.reply_message(
event.reply_token,
TextSendMessage(text='愛你所擇,擇你所愛。', quick_reply=QuickReply(items=[
QuickReplyButton(action=MessageAction(label=dataset[0], text="!我想查看分類 {}".format(dataset[0])))
for dataset in cool_pc_data[0:11]] +
[QuickReplyButton(action=MessageAction(label="看其他的分類", text="!我想看第二頁的分類"))] +
[QuickReplyButton(action=MessageAction(label="重來", text="!我想重來"))]))
)
elif text == "!我想看第二頁的分類":
line_bot_api.reply_message(
event.reply_token,
TextSendMessage(text='愛你所擇,擇你所愛。', quick_reply=QuickReply(items=[
QuickReplyButton(action=MessageAction(label=dataset[0], text="!我想查看分類 {}".format(dataset[0])))
for dataset in cool_pc_data[11:21]] +
[QuickReplyButton(action=MessageAction(label="上一頁", text="!我想看第一頁的分類"))] +
[QuickReplyButton(action=MessageAction(label="下一頁", text="!我想看第三頁的分類"))] +
[QuickReplyButton(action=MessageAction(label="重來", text="!我想重來"))]))
)
elif text == "!我想看第三頁的分類":
line_bot_api.reply_message(
event.reply_token,
TextSendMessage(text='愛你所擇,擇你所愛。', quick_reply=QuickReply(items=[
QuickReplyButton(action=MessageAction(label=dataset[0], text="!我想查看分類 {}".format(dataset[0])))
for dataset in cool_pc_data[21:]] +
[QuickReplyButton(action=MessageAction(label="上一頁", text="!我想看第二頁的分類"))] +
[QuickReplyButton(action=MessageAction(label="重來", text="!我想重來"))]))
)
elif text == "!我沒有特別想了解的商品類別":
line_bot_api.reply_message(
event.reply_token,
TextSendMessage(text='那麼您願意參考一下促銷商品嗎?', quick_reply=QuickReply(items=[
QuickReplyButton(action=MessageAction(label="是", text="!我想參考促銷商品")),
QuickReplyButton(action=MessageAction(label="否", text="!我沒有特別想了解促銷商品")),
QuickReplyButton(action=MessageAction(label="查看功能選單", text="!我想查看功能選單"))
]))
)
elif re.match(r"!\u6211\u60f3\u67e5\u770b\u5206\u985e\s", text): # !我想查看分類\s
# title = re.sub(r'!\u6211\u60f3\u67e5\u770b\u5206\u985e\s', '', text)
# for dataset in cool_pc_data:
# if title == dataset[0]:
# image_carousel_template_message = TemplateSendMessage(
# alt_text='ImageCarousel template', template=ImageCarouselTemplate(columns=[
# ImageCarouselColumn(
# image_url=CoolPcCrawler.get_feebee_image(' '.join(re.findall(
# re.compile(u"[\u4e00-\u9fa5a-zA-Z0-9]+"), dataset[-1][0]))),
# action=PostbackAction(
# label='GG',
# display_text='postback text1',
# data='action=buy&itemid=1'
# )
# ),
# ImageCarouselColumn(
# image_url='https://a32ac8b205b1.ap.ngrok.io/images?name=panda.jpg',
# action=PostbackAction(
# label='看日出',
# display_text='postback text2',
# data='action=buy&itemid=2'
# )
# )
# ]))
# line_bot_api.reply_message(event.reply_token, image_carousel_template_message)
image_carousel_template_message = TemplateSendMessage(
alt_text='ImageCarousel template',
template=ImageCarouselTemplate(
columns=[
ImageCarouselColumn(
image_url='https://a32ac8b205b1.ap.ngrok.io/images?name=panda.jpg',
action=PostbackAction(
label='限制14個字元也太少了吧',
display_text='postback text1',
data='action=buy&itemid=1'
)
),
ImageCarouselColumn(
image_url='https://a32ac8b205b1.ap.ngrok.io/images?name=panda.jpg',
action=PostbackAction(
label='測試',
display_text='postback text2',
data='action=buy&itemid=2'
)
)
]
)
)
line_bot_api.reply_message(event.reply_token, image_carousel_template_message)
elif re.match(r"!限時下殺", text): # 限時下殺
soup = CoolPcCrawler.get_response()
cool_pc_data = CoolPcCrawler.get_data(soup)
limited_sale = []
for dataset in cool_pc_data:
limited_sale += dataset[3]
if re.match(r"!限時下殺$", text):
line_bot_api.reply_message(
event.reply_token,
TextSendMessage(text='愛你所擇,擇你所愛。', quick_reply=QuickReply(items=[
QuickReplyButton(action=MessageAction(label="第{}頁".format(i + 1), text="!限時下殺{}".format(i + 1)))
for i in range(0, math.ceil(len(limited_sale) / 5))
]))
)
elif re.match(r"!限時下殺\d+$", text):
index = int(re.sub("!限時下殺", "", text))
try:
line_bot_api.reply_message(event.reply_token, [
TextSendMessage(limited_sale[i - 1]) for i in range(((index - 1) * 5), index * 5)
])
except IndexError:
last_index = (index - 1) * 5
try:
line_bot_api.reply_message(event.reply_token,
[TextSendMessage(limited_sale[i - 1])
for i in range(last_index, last_index + len(limited_sale) % 5)])
except IndexError:
line_bot_api.reply_message(event.reply_token, TextSendMessage(text="好像哪裡怪怪的哦,請重新查詢看看"))
else:
line_bot_api.reply_message(event.reply_token, TextSendMessage(text="好像哪裡怪怪的哦,請重新查詢看看"))
elif re.match(r"!熱賣商品", text): # 熱賣商品
soup = CoolPcCrawler.get_response()
cool_pc_data = CoolPcCrawler.get_data(soup)
if re.match(r"!熱賣商品$", text) or not re.match(r"!熱賣商品:\s", text):
if text == "!熱賣商品!第一頁" or text == "!熱賣商品":
line_bot_api.reply_message(
event.reply_token,
TextSendMessage(text='愛你所擇,擇你所愛。', quick_reply=QuickReply(
items=[QuickReplyButton(action=MessageAction(
label=dataset[0],
text="!熱賣商品: {}".format(dataset[0]))) for dataset in cool_pc_data[0:11]] +
[QuickReplyButton(action=MessageAction(label="看其他的分類", text="!熱賣商品!第二頁"))] +
[QuickReplyButton(action=MessageAction(label="重來", text="!我想重來"))])))
elif text == "!熱賣商品!第二頁":
line_bot_api.reply_message(
event.reply_token,
TextSendMessage(text='愛你所擇,擇你所愛。', quick_reply=QuickReply(
items=[QuickReplyButton(action=MessageAction(
label=dataset[0],
text="!熱賣商品: {}".format(dataset[0]))) for dataset in cool_pc_data[11:21]] +
[QuickReplyButton(action=MessageAction(label="上一頁", text="!熱賣商品!第一頁"))] +
[QuickReplyButton(action=MessageAction(label="下一頁", text="!熱賣商品!第三頁"))] +
[QuickReplyButton(action=MessageAction(label="重來", text="!我想重來"))]))
)
elif text == "!熱賣商品!第三頁":
line_bot_api.reply_message(
event.reply_token,
TextSendMessage(text='愛你所擇,擇你所愛。', quick_reply=QuickReply(
items=[QuickReplyButton(action=MessageAction(
label=dataset[0],
text="!熱賣商品: {}".format(dataset[0]))) for dataset in cool_pc_data[21:]] +
[QuickReplyButton(action=MessageAction(label="上一頁", text="!熱賣商品!第二頁"))] +
[QuickReplyButton(action=MessageAction(label="重來", text="!我想重來"))]))
)
else:
line_bot_api.reply_message(event.reply_token, TextSendMessage(text='阿鬼說中文'))
elif re.match(r"!熱賣商品:\s", text):
sample_items = []
try:
for dataset in cool_pc_data:
if re.sub(r"\s", "", dataset[0]) == re.sub(r"!熱賣商品:|\s", "", text):
sample_items = random.sample(dataset[4], k=5)
break
if sample_items:
line_bot_api.reply_message(
event.reply_token,
[TextSendMessage(text=item) for item in sample_items[:-1]] +
[TextSendMessage(text=sample_items[-1], quick_reply=QuickReply(
items=[QuickReplyButton(action=MessageAction(label="顯示更多", text=text))]))])
else:
# print('no data matched')
raise IndexError
except IndexError:
line_bot_api.reply_message(event.reply_token, TextSendMessage(text="好像怪怪的哦,請重新查詢看看"))
else:
line_bot_api.reply_message(event.reply_token, TextSendMessage(text="好像怪怪的哦,請重新查詢看看"))
elif re.match(r"!價格異動", text): # 價格異動
soup = CoolPcCrawler.get_response()
cool_pc_data = CoolPcCrawler.get_data(soup)
if re.match(r"!價格異動$", text) or not re.match(r"!價格異動:\s", text):
if text == '!價格異動!第一頁' or text == "!價格異動":
line_bot_api.reply_message(
event.reply_token,
TextSendMessage(text='愛你所擇,擇你所愛。', quick_reply=QuickReply(
items=[QuickReplyButton(action=MessageAction(
label=dataset[0],
text="!價格異動: {}".format(dataset[0]))) for dataset in cool_pc_data[0:11]] +
[QuickReplyButton(action=MessageAction(label="看其他的分類", text="!價格異動!第二頁"))] +
[QuickReplyButton(action=MessageAction(label="重來", text="!我想重來"))])))
elif text == "!價格異動!第二頁":
line_bot_api.reply_message(
event.reply_token,
TextSendMessage(text='愛你所擇,擇你所愛。', quick_reply=QuickReply(
items=[QuickReplyButton(action=MessageAction(
label=dataset[0],
text="!價格異動: {}".format(dataset[0]))) for dataset in cool_pc_data[11:21]] +
[QuickReplyButton(action=MessageAction(label="上一頁", text="!價格異動!第一頁"))] +
[QuickReplyButton(action=MessageAction(label="下一頁", text="!價格異動!第三頁"))] +
[QuickReplyButton(action=MessageAction(label="重來", text="!我想重來"))]))
)
elif text == "!價格異動!第三頁":
line_bot_api.reply_message(
event.reply_token,
TextSendMessage(text='愛你所擇,擇你所愛。', quick_reply=QuickReply(
items=[QuickReplyButton(action=MessageAction(
label=dataset[0],
text="!價格異動: {}".format(dataset[0]))) for dataset in cool_pc_data[21:]] +
[QuickReplyButton(action=MessageAction(label="上一頁", text="!價格異動!第二頁"))] +
[QuickReplyButton(action=MessageAction(label="重來", text="!我想重來"))]))
)
else:
line_bot_api.reply_message(event.reply_token, TextSendMessage(text='阿鬼說中文'))
elif re.match(r"!價格異動:\s", text):
sample_items = []
try:
for dataset in cool_pc_data:
if re.sub(r"\s", "", dataset[0]) == re.sub(r"!價格異動:|\s", "", text):
sample_items = random.sample(dataset[5], k=5)
break
if sample_items:
line_bot_api.reply_message(
event.reply_token,
[TextSendMessage(text=item) for item in sample_items[:-1]] +
[TextSendMessage(text=sample_items[-1], quick_reply=QuickReply(
items=[QuickReplyButton(action=MessageAction(label="顯示更多", text=text))]))])
else:
raise IndexError
except IndexError:
line_bot_api.reply_message(event.reply_token, TextSendMessage(text="好像怪怪的哦,請重新查詢看看"))
else:
line_bot_api.reply_message(event.reply_token, TextSendMessage(text="好像怪怪的哦,請重新查詢看看"))
elif re.match(r"^\?", text) or re.match(r"^\uff1f", text):
soup = CoolPcCrawler.get_response()
_all_data = CoolPcCrawler.get_all_data(soup)
_keyword_list = re.sub(r"[??]", "", text).split(' ')
_keyword_list.reverse()
# do something for searching
def keyword_mapping(keyword_list, all_data):
if not keyword_list:
return all_data
else:
pop = keyword_list.pop()
all_data = [data for data in all_data if pop in data]
return keyword_mapping(keyword_list, all_data)
result_list = keyword_mapping(_keyword_list, _all_data)
if result_list:
if len(result_list) >= 5:
line_bot_api.reply_message(event.reply_token, [TextSendMessage(text=result) for result
in random.sample(result_list, k=5)])
else:
line_bot_api.reply_message(event.reply_token, [TextSendMessage(text=result) for result
in random.sample(result_list, k=len(result_list))])
else:
try:
data_tuple = CoolPcCrawler.get_feebee_result(re.sub(r"[??]", "", text))
image_name = ''.join(re.findall(u"[a-zA-Z0-9]+", data_tuple[0]))
image_url = "https://dfba704bd8c0.ap.ngrok.io/images?name={}.jpg".format(image_name)
messages = '{} ${}'.format(data_tuple[0], data_tuple[1])
# image_url = "https://dfba704bd8c0.ap.ngrok.io/images?name=panda.jpg"
if data_tuple:
line_bot_api.reply_message(event.reply_token, [
TextSendMessage(text="找不到商品哦\n以下是網路上的查詢結果。"),
ImageSendMessage(original_content_url=image_url, preview_image_url=image_url),
TextSendMessage(text=messages)
])
else:
line_bot_api.reply_message(event.reply_token, TextSendMessage(text="找不到商品哦"))
except Exception as e:
print(e)
line_bot_api.reply_message(event.reply_token, TextSendMessage(text="找不到商品哦"))
elif not re.match("!", text) and not re.match(r"^\?", text) and not re.match(r"^\uff1f", text):
response = chat_bot.get_response(text)
response_data = response.serialize()
line_bot_api.reply_message(event.reply_token, TextSendMessage(text=response_data['text']))
else:
line_bot_api.reply_message(event.reply_token, TextSendMessage(text="功能尚未開放哦!\n支付1+1份大薯以解鎖進階功能"))
# Read json when get text message from user
# with open('reply.json', encoding='utf8') as rf:
# reply_json = json.load(rf)
# reply_send_message = FlexSendMessage.new_from_json_dict(reply_json)
@handler.add(FollowEvent)
def handle_follow_message(event):
# Get user data
profile = line_bot_api.get_profile(event.source.user_id)
with open('statics/user_data/user.txt', 'a+', encoding='utf8') as fa:
fa.write(json.dumps(vars(profile), sort_keys=True))
# Reply welcome message
line_bot_api.reply_message(
event.reply_token,
TextSendMessage(text='您好!請問您有明確想找的商品嗎?', quick_reply=QuickReply(items=[
QuickReplyButton(action=MessageAction(label="是", text="!我有明確想找的商品")),
QuickReplyButton(action=MessageAction(label="否", text="!我沒有明確想找的商品"))
]))
)
@handler.add(MessageEvent, message=ImageMessage)
def handle_image_message(event):
message_content = line_bot_api.get_message_content(event.message.id)
file_path = event.message.id + '.jpg'
with open(file_path, 'wb') as fd:
for chunk in message_content.iter_content():
fd.write(chunk)
s3_client.upload_file(file_path, "iii-tutorial-v2", "student15/" + file_path)
line_bot_api.reply_message(
event.reply_token,
TextSendMessage('圖片已上傳')
)
if __name__ == "__main__":
# _soup = CoolPcCrawler.get_response()
# cool_pc_data = CoolPcCrawler.get_data(_soup)
# print(cool_pc_data[5][0])
pass
|
{"/controllers/line_bot.py": ["/models/s3_storage.py", "/models/parser.py", "/settings.py"], "/app.py": ["/controllers/line_bot.py"], "/models/s3_storage.py": ["/settings.py"], "/models/chatterbot_train.py": ["/models/parser.py"]}
|
16,898,834
|
ling199104/coolpc_line_bot
|
refs/heads/master
|
/models/_user_data.py
|
import sqlite3
connector = sqlite3.connect('../sqlite_db/line_bot.db')
c = connector.cursor()
|
{"/controllers/line_bot.py": ["/models/s3_storage.py", "/models/parser.py", "/settings.py"], "/app.py": ["/controllers/line_bot.py"], "/models/s3_storage.py": ["/settings.py"], "/models/chatterbot_train.py": ["/models/parser.py"]}
|
16,898,835
|
ling199104/coolpc_line_bot
|
refs/heads/master
|
/models/parser.py
|
# encoding: utf8
# import codecs
import requests
import re
from os.path import dirname
from bs4 import BeautifulSoup
class CoolPcCrawler:
@classmethod
def get_response(cls) -> BeautifulSoup:
response = requests.get(
url="http://www.coolpc.com.tw/evaluate.php",
params={
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:81.0) Gecko/20100101 Firefox/81.0",
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8",
"Accept-Language": "zh-TW,zh;q=0.8,en-US;q=0.5,en;q=0.3",
"Accept-Encoding": "gzip, deflate",
"DNT": "1",
"Connection": "keep-alive",
"Upgrade-Insecure-Requests": "1",
"Pragma": "no-cache",
"Cache-Control": "no-cache"
}
)
soup = BeautifulSoup(response.text, 'html.parser')
return soup
@classmethod
def get_data(cls, soup) -> list:
# [[title_1, header_1, {info_1}, [limited_sale_items], [hot-sale_items], [price_changed_items], [items]]...]]
text_list = soup.select("tbody#tbdy > tr > td > td")
data = [[] for _ in range(len(text_list)-1)]
for i, content in enumerate(text_list):
if i == 0: # for the first row only
# get title
data[0].append(content.text)
elif i == 1: # for the first row only
# lookahead assertion: match text before \n exclude \n
compiler = re.compile(r'^\u5171\u6709.+\n') # 共有...
# get info
header = re.match(compiler, content('option')[0].text)
if header:
header = re.sub(r'\u25bc', '', header.group()) # \u25bc = ▼
header = re.sub(r'\n', '', header)
data[0].append(header)
# get the numbers in info
info = re.sub(r'(\s+)|(\u25bc)|(\u6a23)', '', header)
if info:
info_list = info.split(',')
info_list = [info for info in info_list]
# ex. {'共有商品': '107', '熱賣': '10', '圖片': '106', '討論': '81', '價格異動': '3'}
info_dict = {re.sub(r'[0-9]+', '', info): re.sub(r'[\u4e00-\u9fa5]+', '', info)
for info in info_list} # \u6a23 = 樣
data[0].append(info_dict)
# find limited price
limited = [re.sub(r'(\u3000)|(\u25c6)|(\u2605)|\n', '', option.text) for option in content('option')
if re.findall('\u4e0b\u6bba\u5230', option.text) != []] # ◆ | ★; \u4e0b\u6bba\u5230 = 下殺到
if limited:
data[0].append(limited)
else:
data[0].append([])
# find hot-sale item
hot_sale = [re.sub(r'(\u3000)|(\u25c6)|(\u2605)|\n', '', option.text) for option in content('option')
if re.findall(r'\u71b1\u8ce3$', option.text) != []]
if hot_sale:
data[0].append(hot_sale)
else:
data[0].append([])
# find price changed
price_changed = [re.sub(r'(\u3000)|(\u25c6)|(\u2605)|\n', '', option.text)
for option in content('option') if re.findall('\u2198', option.text) != []] # ↘
if price_changed:
data[0].append(price_changed)
else:
data[0].append([])
# get ride of those numbers in the end of data
item_list = [re.sub(r'(\u3000)|(\u25c6)|(\u2605)|\n', '', option.text) for option in content('option')
if (re.sub(r'\d+', '', option.text) != '' and re.findall(r'\$', option.text) != [])]
data[0].append(item_list[1:])
else:
# get title from list of find_all()
title = content.text
compiler = re.compile(r'^.+(?=\n)')
title_text = re.match(compiler, title)
if title_text:
data[i-1].append(title_text.group())
# get info
compiler = re.compile(r'^\u5171\u6709.+\n') # 共有...
header = re.match(compiler, content('option')[0].text)
if header:
header = re.sub(r'\u25bc', '', header.group()) # \u25bc = ▼
header = re.sub(r'\n', '', header)
data[i-1].append(header)
# get the numbers in info; \u6a23 = 樣
info_list = [info for info in re.sub(r'\s+|\u25bc|\u6a23', '', header).split(',')]
# ex. {'共有商品': '107', '熱賣': '10', '圖片': '106', '討論': '81', '價格異動': '3'}
info_dict = {re.sub(r'[0-9]+', '', info): re.sub(r'[\u4e00-\u9fa5]+', '', info)
for info in info_list}
data[i-1].append(info_dict)
# find limited price
limited = [re.sub(r'(\u3000)|(\u25c6)|(\u2605)|\n', '', option.text)
for option in content('option')[1:] if re.findall('下殺到', option.text) != []] # ◆ | ★
if limited:
data[i - 1].append(limited)
else:
data[i - 1].append([])
# find hot-sale item
hot_sale = [re.sub(r'(\u3000)|(\u25c6)|(\u2605)|\n', '', option.text)
for option in content('option')[1:] if re.findall('熱賣', option.text) != []]
if hot_sale:
data[i - 1].append(hot_sale)
else:
data[i - 1].append([])
# find price changed
price_changed = [re.sub(r'(\u3000)|(\u25c6)|(\u2605)|\n', '', option.text)
for option in content('option')[1:] if re.findall('\u2198', option.text) != []] # ↘
if price_changed:
data[i - 1].append(price_changed)
else:
data[i - 1].append([])
# get ride of those numbers in the end of data
item_list = [re.sub(r'(\u3000)|(\u25c6)|(\u2605)|\n', '', option.text) for option in
content('option')[1:] if (re.sub(r'\d+', '', option.text) != '' and
re.findall(r'\$', option.text) != [])]
data[i-1].append(item_list[1:])
return data
@classmethod
def get_all_data(cls, soup) -> list:
data_list = []
text_list = soup.select("tbody#tbdy > tr > td > td")
for i, content in enumerate(text_list):
if i == 0:
pass
elif i == 1:
item_list = [re.sub(r'(\u3000)|(\u25c6)|(\u2605)|\n', '', option.text) for option in content('option')
if (re.sub(r'\d+', '', option.text) != '' and re.findall(r'\$', option.text) != [])]
data_list += item_list[1:]
else:
item_list = [re.sub(r'(\u3000)|(\u25c6)|(\u2605)|\n', '', option.text) for option in
content('option')[1:] if (re.sub(r'\d+', '', option.text) != '' and
re.findall(r'\$', option.text) != [])]
data_list += item_list[1:]
return data_list
@classmethod
def get_feebee_result(cls, search_keyword: str) -> tuple:
response = requests.get(
url="https://feebee.com.tw/s/".format(search_keyword),
params={
"q": search_keyword
},
headers={
"Host": "feebee.com.tw",
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:81.0) Gecko/20100101 Firefox/81.0",
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8",
"Accept-Language": "zh-TW,zh;q=0.8,en-US;q=0.5,en;q=0.3",
"Accept-Encoding": "gzip, deflate, br",
"Connection": "keep-alive",
"Upgrade-Insecure-Requests": "1",
"Pragma": "no-cache",
"Cache-Control": "no-cache",
"TE": "Trailers"
}
)
response.encoding = 'utf8'
soup = BeautifulSoup(response.text, 'html.parser')
try:
pre_analyze_image_1 = soup.select_one("li > span > a > img")
pre_analyze_image_2 = soup.select_one("li.pure-g > span > a > img")
pre_analyze_name = soup.select_one("li.pure-g > span > a > h3")
pre_analyze_price_1 = soup.select_one("li.pure-g > span > div > a > span")
pre_analyze_price_2 = soup.select_one("li.pure-g > span > ul > li > span")
image_url = re.sub(r'.+=/|\?\d+', '', (pre_analyze_image_1 or pre_analyze_image_2)['data-src'])
img_data = requests.get(image_url).content
image_file_name = ''.join(re.findall(u"[a-zA-Z0-9]+", pre_analyze_name.text))
with open(dirname(__file__) + '/../statics/images/{}.jpg'.format(image_file_name), 'wb+') as handler:
handler.write(img_data)
return pre_analyze_name.text, (pre_analyze_price_1 or pre_analyze_price_2).text, image_url
except AttributeError as e:
print(e)
return ()
if __name__ == "__main__": # debug-only
first_soup = CoolPcCrawler.get_response()
cool_pc_data = CoolPcCrawler.get_data(first_soup)
for dataset in cool_pc_data:
print(repr(dataset[0]))
|
{"/controllers/line_bot.py": ["/models/s3_storage.py", "/models/parser.py", "/settings.py"], "/app.py": ["/controllers/line_bot.py"], "/models/s3_storage.py": ["/settings.py"], "/models/chatterbot_train.py": ["/models/parser.py"]}
|
16,898,836
|
ling199104/coolpc_line_bot
|
refs/heads/master
|
/settings.py
|
from os import environ
AWS_ACCESS_KEY_ID = environ['AWS_ACCESS_KEY_ID']
AWS_SECRET_ACCESS_KEY = environ['AWS_SECRET_ACCESS_KEY']
CHANNEL_ACCESS_TOKEN = environ['CHANNEL_ACCESS_TOKEN']
CHANNEL_SECRET = environ['CHANNEL_SECRET']
|
{"/controllers/line_bot.py": ["/models/s3_storage.py", "/models/parser.py", "/settings.py"], "/app.py": ["/controllers/line_bot.py"], "/models/s3_storage.py": ["/settings.py"], "/models/chatterbot_train.py": ["/models/parser.py"]}
|
16,968,931
|
0snola/semestral-veranum2
|
refs/heads/main
|
/AppVeranum/models.py
|
from django.forms import ModelForm, TextInput, Textarea
from django.db import models
# Create your models here.
class Hotel(models.Model):
hotel = models.CharField(max_length=100)
class Meta:
db_table: "hotel"
def __str__(self):
return u'{0}'.format(self.hotel)
class ReservaHabitacion(models.Model):
nombre = models.CharField(max_length=50)
apellido = models.CharField(max_length=50)
apellido2 = models.CharField(max_length=50)
rut = models.IntegerField()
fecha = models.DateField()
estadia = models.IntegerField()
hotel = models.ForeignKey(Hotel,on_delete=models.CASCADE)
cantidad = models.IntegerField()
class Meta:
db_table: "reservaHabitacion"
class ReservaSalon(models.Model):
nombre = models.CharField(max_length=50)
apellido = models.CharField(max_length=50)
apellido2 = models.CharField(max_length=50)
rut = models.IntegerField()
fecha = models.DateField()
hotel = models.ForeignKey(Hotel,on_delete=models.CASCADE)
class Meta:
db_table: "reservaSalon"
def __str__(self):
return u'{0}'.format(self.reservaSalon)
|
{"/AppVeranum/forms.py": ["/AppVeranum/models.py"], "/AppVeranum/views.py": ["/AppVeranum/models.py", "/AppVeranum/forms.py"]}
|
16,968,932
|
0snola/semestral-veranum2
|
refs/heads/main
|
/AppVeranum/views.py
|
from django.shortcuts import redirect, render
from AppVeranum.models import *
from AppVeranum.forms import HabitacionForm
# Create your views here.
def home (request):
return render(request,'principal.html')
def reservaHabitacion(request):
if request.method == "POST":
form = HabitacionForm(request.POST)
if form.is_valid():
try:
form.save()
return redirect('/formulario')
except:
pass
else:
form = HabitacionForm()
reservaHabitacion = ReservaHabitacion.objects.all()
return render(request,'mantenedorReservas.html',{'form': form, 'reservaHabitacion': reservaHabitacion})
|
{"/AppVeranum/forms.py": ["/AppVeranum/models.py"], "/AppVeranum/views.py": ["/AppVeranum/models.py", "/AppVeranum/forms.py"]}
|
17,050,727
|
yeti/manticore-tastypie-urbanairship
|
HEAD
|
/manticore_tastypie_urbanairship/utils.py
|
from django.conf import settings
from django.core.mail import EmailMultiAlternatives
from django.utils.html import strip_tags
import urbanairship
from .models import AirshipToken
from .resources import AirshipTokenResource, NotificationSettingResource
# Registers this library's resources
def register_api(api):
api.register(AirshipTokenResource())
api.register(NotificationSettingResource())
return api
def send_push_notification(receiver, message):
if AirshipToken.objects.filter(user=receiver, expired=False).exists():
try:
device_tokens = list(AirshipToken.objects.filter(user=receiver, expired=False).values_list('token',
flat=True))
airship = urbanairship.Airship(settings.AIRSHIP_APP_KEY, settings.AIRSHIP_APP_MASTER_SECRET)
for device_token in device_tokens:
push = airship.create_push()
push.audience = urbanairship.device_token(device_token)
push.notification = urbanairship.notification(ios=urbanairship.ios(alert=message, badge='+1'))
push.device_types = urbanairship.device_types('ios')
push.send()
except urbanairship.AirshipFailure:
pass
def send_email_notification(receiver, message, reply_to=None):
headers = {}
if reply_to:
headers['Reply-To'] = reply_to
text_content = strip_tags(message)
msg = EmailMultiAlternatives(settings.EMAIL_NOTIFICATION_SUBJECT, text_content, settings.DEFAULT_FROM_EMAIL,
[receiver.email], headers=headers)
msg.attach_alternative(message, "text/html")
msg.send()
|
{"/manticore_tastypie_urbanairship/models.py": ["/manticore_tastypie_urbanairship/utils.py"], "/manticore_tastypie_urbanairship/utils.py": ["/manticore_tastypie_urbanairship/models.py", "/manticore_tastypie_urbanairship/resources.py"], "/manticore_tastypie_urbanairship/resources.py": ["/manticore_tastypie_urbanairship/models.py"]}
|
17,050,728
|
yeti/manticore-tastypie-urbanairship
|
HEAD
|
/manticore_tastypie_urbanairship/test.py
|
from django.contrib.auth import get_user_model
from manticore_tastypie_core.manticore_tastypie_core.test import ManticomResourceTestCase
from manticore_tastypie_urbanairship.manticore_tastypie_urbanairship.models import NotificationSetting
User = get_user_model()
class SettingsTests(ManticomResourceTestCase):
def setUp(self):
super(SettingsTests, self).setUp()
user_data = {'email': 'testuser@gmail.com', User.USERNAME_FIELD: 'testuser@gmail.com'}
self.user = User.objects.create_user(**user_data)
def test_notification_settings_get_manticom(self):
self.assertManticomGETResponse('notification_setting', 'notification_setting', '$notificationSetting',
self.user)
def test_notification_settings_patch_manticom(self):
notification_setting = self.user.notification_settings.all()[0]
data = {
'allow_push': False,
'allow_email': False
}
self.assertManticomPATCHResponse('notification_setting/{}'.format(notification_setting.pk),
'$notificationPatchRequest', '$notificationSetting', data, self.user)
updated_notification_setting = NotificationSetting.objects.get(pk=notification_setting.pk)
self.assertFalse(updated_notification_setting.allow_push)
self.assertFalse(updated_notification_setting.allow_email)
|
{"/manticore_tastypie_urbanairship/models.py": ["/manticore_tastypie_urbanairship/utils.py"], "/manticore_tastypie_urbanairship/utils.py": ["/manticore_tastypie_urbanairship/models.py", "/manticore_tastypie_urbanairship/resources.py"], "/manticore_tastypie_urbanairship/resources.py": ["/manticore_tastypie_urbanairship/models.py"]}
|
17,050,729
|
yeti/manticore-tastypie-urbanairship
|
HEAD
|
/manticore_tastypie_urbanairship/models.py
|
from django.conf import settings
from django.contrib.contenttypes import generic
from django.contrib.contenttypes.models import ContentType
from django.contrib.sites.models import Site
from django.db import models
from django.db.models.signals import post_save
from django.template.loader import render_to_string
from celery.task import task
from model_utils import Choices
from manticore_django.manticore_django.models import CoreModel
__author__ = 'rudy'
# Stores user tokens from Urban Airship
class AirshipToken(CoreModel):
user = models.ForeignKey(settings.AUTH_USER_MODEL)
token = models.CharField(max_length=100)
expired = models.BooleanField(default=False)
class Notification(CoreModel):
TYPES = Choices(*settings.NOTIFICATION_TYPES)
PUSH = "push"
EMAIL = "email"
notification_type = models.PositiveSmallIntegerField(choices=TYPES)
template_override = models.CharField(max_length=100, blank=True, null=True)
user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name="receiver", null=True)
reporter = models.ForeignKey(settings.AUTH_USER_MODEL, related_name="reporter", null=True, blank=True)
content_type = models.ForeignKey(ContentType)
object_id = models.PositiveIntegerField(db_index=True)
content_object = generic.GenericForeignKey()
def message(self, location):
"""
Takes our configured notifications and creates a message
replacing the appropriate variables from the content object
"""
# TODO: Right now assumes the content_object has identifier defined
data = {
'domain': Site.objects.get_current(),
'identifier': self.content_object.identifier(),
'reporter': self.reporter.identifier() if self.reporter else ''
}
if hasattr(self.content_object, 'extra_notification_params'):
data.update(self.content_object.extra_notification_params())
configured_template_name = unicode(Notification.TYPES._triples[self.notification_type][2])
template_name = self.template_override if self.template_override else configured_template_name
return render_to_string("notifications/{}/{}".format(location, template_name), data)
def email_message(self):
return self.message(Notification.EMAIL)
def push_message(self):
message = self.message(Notification.PUSH)
if self.reporter:
return "{0} {1}".format(self.reporter, message)
else:
return "{0}".format(message)
def name(self):
return u"{0}".format(Notification.TYPES._triples[self.notification_type][1])
class Meta:
ordering = ['-created']
@task
def create_notification(receiver, reporter, content_object, notification_type, template_override=None, reply_to=None):
# If the receiver of this notification is the same as the reporter or
# if the user has blocked this type, then don't create
if receiver == reporter:
return
notification = Notification.objects.create(user=receiver,
reporter=reporter,
content_object=content_object,
notification_type=notification_type,
template_override=template_override)
notification.save()
notification_setting = NotificationSetting.objects.get(notification_type=notification_type, user=receiver)
if notification_setting.allow_push:
from .utils import send_push_notification
send_push_notification(receiver, notification.push_message())
if notification_setting.allow_email:
from .utils import send_email_notification
send_email_notification(receiver, notification.email_message(), reply_to=reply_to)
class NotificationSetting(CoreModel):
notification_type = models.PositiveSmallIntegerField(choices=Notification.TYPES)
user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='notification_settings')
allow_push = models.BooleanField(default=True)
allow_email = models.BooleanField(default=True)
class Meta:
unique_together = ('notification_type', 'user')
def name(self):
return u"{0}".format(Notification.TYPES._triples[self.notification_type][1])
def create_notifications(sender, **kwargs):
sender_name = "{0}.{1}".format(sender._meta.app_label, sender._meta.object_name)
if sender_name.lower() != settings.AUTH_USER_MODEL.lower():
return
if kwargs['created']:
user = kwargs['instance']
if not user.notification_settings.exists():
user_settings = [NotificationSetting(user=user, notification_type=pk) for pk, name in Notification.TYPES]
NotificationSetting.objects.bulk_create(user_settings)
post_save.connect(create_notifications)
|
{"/manticore_tastypie_urbanairship/models.py": ["/manticore_tastypie_urbanairship/utils.py"], "/manticore_tastypie_urbanairship/utils.py": ["/manticore_tastypie_urbanairship/models.py", "/manticore_tastypie_urbanairship/resources.py"], "/manticore_tastypie_urbanairship/resources.py": ["/manticore_tastypie_urbanairship/models.py"]}
|
17,050,730
|
yeti/manticore-tastypie-urbanairship
|
HEAD
|
/manticore_tastypie_urbanairship/resources.py
|
from datetime import timedelta
from django.conf import settings
from tastypie import fields
from tastypie.exceptions import BadRequest
from tastypie.utils import now
from manticore_tastypie_core.manticore_tastypie_core.resources import ManticoreModelResource
from .models import AirshipToken, NotificationSetting, Notification
from manticore_tastypie_user.manticore_tastypie_user.authentication import ExpireApiKeyAuthentication
from manticore_tastypie_user.manticore_tastypie_user.authorization import UserObjectsOnlyAuthorization
from manticore_tastypie_user.manticore_tastypie_user.resources import UserResource
import urbanairship
class AirshipTokenResource(ManticoreModelResource):
class Meta:
queryset = AirshipToken.objects.all()
allowed_methods = ['get', 'post']
authorization = UserObjectsOnlyAuthorization()
authentication = ExpireApiKeyAuthentication()
resource_name = "airship_token"
always_return_data = True
object_name = "airship_token"
def obj_create(self, bundle, **kwargs):
if 'token' in bundle.data:
airship = urbanairship.Airship(settings.AIRSHIP_APP_KEY, settings.AIRSHIP_APP_MASTER_SECRET)
try:
airship.register(bundle.data['token'], alias="{0}:{1}".format(bundle.request.user.pk,
bundle.request.user.get_username()))
# Delete other usages of this token (i.e. multiple accounts on one device)
AirshipToken.objects.filter(token=bundle.data['token']).delete()
bundle.obj = AirshipToken(user=bundle.request.user, token=bundle.data['token'])
bundle.obj.save()
except urbanairship.AirshipFailure:
raise BadRequest("Failed Authentication")
return bundle
else:
raise BadRequest("Missing token")
class NotificationSettingResource(ManticoreModelResource):
name = fields.CharField(attribute='name', blank=True)
class Meta:
queryset = NotificationSetting.objects.all()
allowed_methods = ['get', 'patch']
authorization = UserObjectsOnlyAuthorization()
authentication = ExpireApiKeyAuthentication()
resource_name = "notification_setting"
always_return_data = True
object_name = "notification_setting"
fields = ['id', 'allow_push', 'allow_email', 'name']
class NotificationResource(ManticoreModelResource):
name = fields.CharField(attribute='name')
message = fields.CharField()
reporter = fields.ToOneField(UserResource, 'reporter', null=True, full=True)
def dehydrate_message(self, bundle):
return bundle.obj.message(Notification.PUSH)
class Meta:
queryset = Notification.objects.all()
allowed_methods = ['get']
authorization = UserObjectsOnlyAuthorization()
authentication = ExpireApiKeyAuthentication()
resource_name = "notification"
object_name = "notification"
fields = ['id', 'created', 'name', 'message', 'reporter']
def get_object_list(self, request=None, **kwargs):
obj_list = super(NotificationResource, self).get_object_list(request)
# Limit the list of notifications if we have the setting defined to the past x hours
if hasattr(settings, 'NOTIFICATION_WINDOW_HOURS'):
date = now() - timedelta(days=settings.NOTIFICATION_WINDOW_HOURS)
obj_list = obj_list.filter(created__gte=date)
return obj_list
|
{"/manticore_tastypie_urbanairship/models.py": ["/manticore_tastypie_urbanairship/utils.py"], "/manticore_tastypie_urbanairship/utils.py": ["/manticore_tastypie_urbanairship/models.py", "/manticore_tastypie_urbanairship/resources.py"], "/manticore_tastypie_urbanairship/resources.py": ["/manticore_tastypie_urbanairship/models.py"]}
|
17,062,968
|
dasje/steganographizer
|
refs/heads/main
|
/images.py
|
from PIL import Image
import numpy as np
#image class
class Pics:
def __init__(self, picture):
self.picture = picture #contains picture location
#create picture object
self.image = Image.open(self.picture)
self.image_array = self.convert_to_array()
self.eight_bit_array = None
self.msb_array = None
def get_dimensions(self):
"""Returns image size as tuple (width, height)"""
return self.image.size
def convert_to_array(self):
"""Converts image to numpy array"""
self.image.convert(mode="P")
return np.array(self.image)
def convert_array_to_8bit(self):
"""Converts the pixels in array to 8bit binary"""
eba = []
bin_color_dic = {}
for x in self.image_array:
col = []
for y in x:
rgb = []
for color in y:
if color not in bin_color_dic:
bin_color_dic[color] = bin(color)[2:].zfill(8)
rgb.append(bin_color_dic[color])
col.append(rgb)
eba.append(col)
eba = np.array(eba)
self.eight_bit_array = eba
def get_msbs(self):
"""Creates array of most significant bits from each pixel"""
msb_array = []
for x in self.eight_bit_array:
col = []
for y in x:
rgb = []
for color in y:
rgb.append(color[:4])
col.append(rgb)
msb_array.append(col)
msb_array = np.array(msb_array)
self.msb_array = msb_array
#get dimensions
#convert image to numpy array
#split pixels and return msb's of pixels
x = Pics('test_images/test1.jpg')
#print(x.image_array)
x.convert_array_to_8bit()
print(x.eight_bit_array)
x.get_msbs()
print(x.msb_array)
|
{"/steganographizer.py": ["/base_pic.py", "/base_file.py"], "/main.py": ["/base_pic.py", "/base_file.py", "/steganographizer.py"]}
|
17,102,972
|
vcvrkp/tictactoe
|
refs/heads/master
|
/gameplay/urls.py
|
from django.conf.urls import url
from django.contrib.auth.views import LoginView, LogoutView
from .views import game_detail,make_move
urlpatterns = [
url(r'detail/(?P<id>\d+)/$',game_detail,name="gameplay_detail"),
url(r'make_move/(?P<id>\d+)/',make_move,name="gameplay_make_move")
]
|
{"/gameplay/urls.py": ["/gameplay/views.py"], "/player/urls.py": ["/player/views.py"]}
|
17,102,973
|
vcvrkp/tictactoe
|
refs/heads/master
|
/gameplay/views.py
|
from django.shortcuts import render, get_object_or_404
from django.contrib.auth.decorators import login_required
from django.core.exceptions import PermissionDenied
from django.shortcuts import render,redirect
from .models import Game
from .forms import MoveForm
# Create your views here.
@login_required
def game_detail(request,id):
game = get_object_or_404(Game,pk=id)
context = {"game" : game}
if game.is_users_move(request.user):
context["form"] = MoveForm()
return render(request,"gameplay/game_detail.html",context=context)
@login_required
def make_move(request,id):
game = get_object_or_404(Game,pk=id)
if not game.is_users_move(request.user):
raise PermissionDenied
move = game.new_move()
form = MoveForm(instance=move, data = request.POST)
if form.is_valid():
move.save()
return redirect("gameplay_detail",id)
else:
return render(request,"gameplay/game_detail.html",{
"game":game,
"form" : form
})
|
{"/gameplay/urls.py": ["/gameplay/views.py"], "/player/urls.py": ["/player/views.py"]}
|
17,102,974
|
vcvrkp/tictactoe
|
refs/heads/master
|
/gameplay/migrations/0006_auto_20201201_2317.py
|
# Generated by Django 3.1.3 on 2020-12-01 17:47
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('gameplay', '0005_auto_20201201_2311'),
]
operations = [
migrations.AlterField(
model_name='move',
name='by_first_player',
field=models.BooleanField(editable=False),
),
]
|
{"/gameplay/urls.py": ["/gameplay/views.py"], "/player/urls.py": ["/player/views.py"]}
|
17,102,975
|
vcvrkp/tictactoe
|
refs/heads/master
|
/tictactoe/views.py
|
from django.shortcuts import render, redirect
from django.http import HttpResponseRedirect
from .forms import UploadFileForm
def welcome(request):
if request.user.is_authenticated:
return redirect('player_home')
else:
return render(request, 'tictactoe/welcome.html')
def upload_file(request):
if request.method == 'POST':
form = UploadFileForm(request.POST, request.FILES)
if form.is_valid():
handle_uploaded_file(request.FILES['file'])
return render(request,'tictactoe/welcome.html')
else:
form = UploadFileForm()
return render(request, 'upload.html', {'form': form})
def handle_uploaded_file(f):
with open('/temp/upload.txt', 'wb+') as destination:
for chunk in f.chunks():
destination.write(chunk)
|
{"/gameplay/urls.py": ["/gameplay/views.py"], "/player/urls.py": ["/player/views.py"]}
|
17,102,976
|
vcvrkp/tictactoe
|
refs/heads/master
|
/player/urls.py
|
"""tictactoe URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/3.1/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.conf.urls import url
from django.contrib import admin
from django.urls import path
from django.contrib.auth.views import LoginView, LogoutView
from .views import home, new_invitation, accept_invitation
urlpatterns = [
# path('admin/', admin.site.urls),
# path('welcome/', welcome),
url(r'home$', home, name="player_home"),
url(r'login$',LoginView.as_view(template_name="player/login_form.html"),name="player_login"),
# url(r'^$', welcome),
url(r'logout$',LogoutView.as_view(),name="player_logout"),
url(r'new_invitation$',new_invitation,name="player_new_invitation"),
url(r'accept_invitation/(?P<id>\d+)/$',accept_invitation,name="player_accept_invitation")
]
|
{"/gameplay/urls.py": ["/gameplay/views.py"], "/player/urls.py": ["/player/views.py"]}
|
17,102,977
|
vcvrkp/tictactoe
|
refs/heads/master
|
/player/views.py
|
from django.core.exceptions import PermissionDenied
from django.shortcuts import render, redirect, get_object_or_404
from gameplay.models import Game,GamesQuerySet
from django.contrib.auth.decorators import login_required
from .forms import InvitationForm
from .forms import Invitation
# Create your views here.
@login_required
def home(request):
# g_f_p = Game.objects.filter(first_player=request.user,status='F')
# g_s_p = Game.objects.filter(second_player=request.user,status='S')
# all_games = list(g_f_p) + list(g_s_p)
my_games = Game.objects.games_for_user(request.user)
active = my_games.active()
old_games = my_games.difference(active)
invitations = request.user.invitations_recieved.all()
dcontext = {}
dcontext['games'] = active
dcontext['old_games'] = old_games
dcontext['invitations'] = invitations
return render(request=request, template_name="player/home.html",
context=dcontext)
@login_required
def new_invitation(request):
if request.method == "POST":
#TODO Handle the request of form submission.
invitation = Invitation(from_user=request.user)
form = InvitationForm(instance=invitation,data=request.POST)
if form.is_valid():
form.save()
return redirect('player_home')
else:
form = InvitationForm()
return render(request,"player/new_invitation_form.html",{"form":form})
@login_required
def accept_invitation(request,id):
invitation = get_object_or_404(Invitation,pk=id)
if not request.user == invitation.to_user:
raise PermissionDenied
if request.method == "POST":
if "accept" in request.POST:
game = Game.objects.create(
first_player = invitation.to_user,
second_player = invitation.from_user,
)
invitation.delete()
return redirect(game)
else:
return render(request,"player/accept_invitation_form.html",{"invitation":invitation})
|
{"/gameplay/urls.py": ["/gameplay/views.py"], "/player/urls.py": ["/player/views.py"]}
|
17,102,978
|
vcvrkp/tictactoe
|
refs/heads/master
|
/player/models.py
|
from django.db import models
from django.contrib.auth.models import User
# Create your models here.
class Invitation(models.Model):
from_user = models.ForeignKey(
User,
related_name="invitations_sent",
on_delete=models.CASCADE)
to_user = models.ForeignKey(
User,
related_name="invitations_recieved",
verbose_name="User to invite ",
help_text="Please select the user you wish to play a game with. ",
on_delete=models.CASCADE)
message = models.CharField(
max_length=300,
verbose_name="Optional Message.",
help_text="It's always nice to add a friendly message!")
timestamp = models.DateTimeField(auto_now_add=True)
def __str__(self):
return " {0} sent {1} an Invitation".format(self.from_user, self.to_user)
|
{"/gameplay/urls.py": ["/gameplay/views.py"], "/player/urls.py": ["/player/views.py"]}
|
17,158,024
|
momen-awad/Django-Movies-website
|
refs/heads/master
|
/movie/urls.py
|
from django.urls import path
from .views import movie_list, movie_details, movie_create, movie_delete , movie_update
app_name = 'movie'
urlpatterns = [
path('', movie_list, name='movie_list'),
path('details/<int:id>', movie_details, name='movie_details'),
path('create/', movie_create, name='movie_create'),
path('delete/<int:pk>/', movie_delete, name='movie_delete'),
path('update/<int:pk>/', movie_update, name='movie_update')
]
|
{"/movie/urls.py": ["/movie/views.py", "/movie/api.py"], "/ToDo/urls.py": ["/ToDo/views.py"], "/accounts/api/v1/urls.py": ["/accounts/api/v1/views.py"], "/movie/views.py": ["/movie/models.py"], "/movie/api.py": ["/movie/models.py"], "/movie/admin.py": ["/movie/models.py"], "/movie/signals.py": ["/movie/models.py"]}
|
17,215,703
|
expert40rus/expert40rusrepozitoriy
|
refs/heads/master
|
/sticker.py
|
hello_sticker = 'CAACAgIAAxkBAALKQGAek25AlerPVL4DwkAYqCbZUcnvAAKpCQACeVziCRbryzP9_dc6HgQ'
bye_sticker = 'CAACAgIAAxkBAALKQ2Aek_Q1xznJSFFKT15RdS0HBLLtAAIKAAMkcWIa1JSZpG-I8EYeBA'
wtf_sticker = 'CAACAgIAAxkBAALKNGAejF3p09-9xwnqqjVHg2Vx-GALAAJkAAM0IuoFKnXdXBIl-cUeBA'
mask_sticker = 'CAACAgIAAxkBAAEBbJRgwNEGjQbI7y2_0FnTMvbiMnt7iQACkAgAAnlc4glscGtRc0A8wh8E'
|
{"/kinopoisk.py": ["/config.py"], "/bot.py": ["/config.py", "/sticker.py", "/kinopoisk.py"]}
|
17,215,704
|
expert40rus/expert40rusrepozitoriy
|
refs/heads/master
|
/kinopoisk.py
|
from kinopoisk_api import KP
import random
import config
kinopoisk = KP(token=config.kpoisk)
def get_cinema(genre):
search_result = kinopoisk.search(genre)
if genre == 'Аниме':
x = random.randrange(0, 4)
list1 = ['Название: ' + search_result[x].ru_name +
'\nГод: ' + search_result[x].year +
'\nРейтинг: ' + search_result[x].kp_rate +
'\nСсылка на Кинопоиск: ' + search_result[x].kp_url +
'\nДлительность: ' + search_result[x].duration +
'\nСсылка на постер' + search_result[x].poster_preview]
return list1
else:
x = random.randrange(0, 6)
list2 = ['Название: ' + search_result[x].ru_name +
'\nГод: ' + search_result[x].year +
'\nРейтинг: ' + search_result[x].kp_rate +
'\nСсылка на Кинопоиск: ' + search_result[x].kp_url +
'\nДлительность: ' + search_result[x].duration +
'\nСсылка на постер' + search_result[x].poster_preview]
return list2
|
{"/kinopoisk.py": ["/config.py"], "/bot.py": ["/config.py", "/sticker.py", "/kinopoisk.py"]}
|
17,215,705
|
expert40rus/expert40rusrepozitoriy
|
refs/heads/master
|
/bot.py
|
import telebot
from telebot import apihelper
import config
import sticker
from kinopoisk import get_cinema
bot = telebot.TeleBot(config.token)
apihelper.proxy = {'http': config.proxy}
START = 'start'
HELP = 'help'
keyboard1 = telebot.types.ReplyKeyboardMarkup(resize_keyboard=True)
keyboard1.row('Привет')
keyboard2 = telebot.types.ReplyKeyboardMarkup(resize_keyboard=True)
keyboard2.row('Фильм')
@bot.message_handler(commands=['help'])
def send_help(message):
bot.send_message(message.chat.id, f'Напиши команду /start и мы начнем также можешь прописать Топ 500')
@bot.message_handler(commands=['start'])
def send_welcome(message):
bot.send_message(message.chat.id, f'Вас приветствует КиноджоБот', reply_markup=keyboard1)
@bot.message_handler(content_types=['text'])
def get_text_messages(message):
chat_id = message.from_user.id
username = message.from_user.first_name
user_text = message.text.lower
if user_text() == 'привет':
bot.send_message(chat_id, f'Привет, {username}', reply_markup=keyboard2)
bot.send_sticker(chat_id, sticker.hello_sticker)
elif user_text() == 'фильм':
markup = telebot.types.InlineKeyboardMarkup()
markup.add(telebot.types.InlineKeyboardButton(text='Аниме', callback_data='Аниме'))
markup.add(telebot.types.InlineKeyboardButton(text='Комедия', callback_data='Комедия'))
markup.add(telebot.types.InlineKeyboardButton(text='Боевик', callback_data='Боевик'))
markup.add(telebot.types.InlineKeyboardButton(text='Детектив', callback_data='Детектив'))
markup.add(telebot.types.InlineKeyboardButton(text='Мультфильм', callback_data='Мультфильм'))
markup.add(telebot.types.InlineKeyboardButton(text='Драма', callback_data='Драма'))
markup.add(telebot.types.InlineKeyboardButton(text='Мелодрама', callback_data='Мелодрама'))
markup.add(telebot.types.InlineKeyboardButton(text='Научный', callback_data='Научный'))
markup.add(telebot.types.InlineKeyboardButton(text='Криминал', callback_data='Криминал'))
markup.add(telebot.types.InlineKeyboardButton(text='Ужасы', callback_data='Ужасы'))
markup.add(telebot.types.InlineKeyboardButton(text='Фантастика', callback_data='Фантастика'))
markup.add(telebot.types.InlineKeyboardButton(text='Триллер', callback_data='Триллер'))
markup.add(telebot.types.InlineKeyboardButton(text='Документальный', callback_data='Документальный'))
markup.add(telebot.types.InlineKeyboardButton(text='Ничего не подходит', callback_data='Ничего не подходит'))
bot.send_message(message.chat.id, text="Какой жанр предпочитаете?", reply_markup=markup)
else:
bot.send_sticker(chat_id, sticker.wtf_sticker)
cinema = {
'Аниме': 'https://jut.su/jojo-bizarre-adventure/season-1/episode-1.html',
'Комедия': 'https://www.kinopoisk.ru/film/535341',
'Боевик': 'https://www.kinopoisk.ru/film/1009536/',
'Детектив': 'https://www.kinopoisk.ru/film/467099/',
'Мультфильм': 'https://www.kinopoisk.ru/film/81621/',
'Драма': 'https://www.kinopoisk.ru/film/220541/',
'Мелодрама': 'https://www.kinopoisk.ru/film/22803/',
'Научный': 'https://www.kinopoisk.ru/film/652833/',
'Криминал': 'https://www.kinopoisk.ru/film/278522/',
'Ужасы': 'https://www.kinopoisk.ru/film/686898/',
'Фантастика': 'https://www.kinopoisk.ru/film/538225',
'Триллер': 'https://www.kinopoisk.ru/film/572461/',
'Документальный': 'https://www.kinopoisk.ru/film/424378/',
}
@bot.callback_query_handler(func=lambda call: True)
def query_handler(call):
bot.answer_callback_query(callback_query_id=call.id)
sad = 'Возвращайтесь, мы исправимся'
if call.data in cinema:
answer = get_cinema(call.data)
bot.send_message(call.message.chat.id, answer)
else:
bot.send_message(call.message.chat.id, sad, reply_markup=keyboard2)
bot.send_sticker(call.message.chat.id, sticker.mask_sticker)
if __name__ == '__main__':
bot.polling(none_stop=True)
|
{"/kinopoisk.py": ["/config.py"], "/bot.py": ["/config.py", "/sticker.py", "/kinopoisk.py"]}
|
17,215,706
|
expert40rus/expert40rusrepozitoriy
|
refs/heads/master
|
/config.py
|
token = '1804502896:AAEHWNH4Jvcs3JTBnkMEJJLi3aRI_SVKRXg'
proxy = 'socks5://Proxy_User:Proxy_Password@Proxy_IP:Proxy_Port'
kpoisk = '9736285b-b7d0-4a40-9f9e-7cfb09354984'
|
{"/kinopoisk.py": ["/config.py"], "/bot.py": ["/config.py", "/sticker.py", "/kinopoisk.py"]}
|
17,219,802
|
michael-martinson/MyFinancials
|
refs/heads/main
|
/db.py
|
import sqlite3
import csv
import hashlib
import os
from flask.cli import with_appcontext
from datetime import date, timedelta, datetime
import calendar
# helper function that converts query result to json, after cursor has executed query
def to_json(cursor):
results = cursor.fetchall()
headers = [d[0] for d in cursor.description]
return [dict(zip(headers, row)) for row in results]
# Error class for when a key is not found
class KeyNotFound(Exception):
def __init__(self, message=None):
Exception.__init__(self)
if message:
self.message = message
else:
self.message = "Key/Id not found"
def to_dict(self):
rv = dict()
rv["message"] = self.message
return rv
# Error class for when a new user has the same username
class UsernameAlreadyExists(Exception):
def __init__(self, message=None):
Exception.__init__(self)
if message:
self.message = message
else:
self.message = "Key/Id not found"
def to_dict(self):
rv = dict()
rv["message"] = self.message
return rv
# Error class for when request data is bad
class BadRequest(Exception):
def __init__(self, message=None, error_code=400):
Exception.__init__(self)
if message:
self.message = message
else:
self.message = "Bad Request"
self.error_code = error_code
def to_dict(self):
rv = dict()
rv["message"] = self.message
return rv
# hash the password and return the salt and key
def hash_password(password, salt = None):
if not salt:
salt = os.urandom(32) # A new salt for this user
key = hashlib.pbkdf2_hmac('sha256', password.encode('utf-8'), salt, 100000)
return (salt, key)
"""
Wraps a single connection to the database with higher-level functionality.
Holds the DB connection
"""
class DB:
def __init__(self, connection):
self.conn = connection
# Simple example of how to execute a query against the DB.
# Again never do this, you should only execute parameterized query
# See https://docs.python.org/3/library/sqlite3.html#sqlite3.Cursor.execute
# This is the qmark style:
# cur.execute("insert into people values (%s, %s)", (who, age))
# And this is the named style:
# cur.execute("select * from people where name_last=:who and age=:age", {"who": who, "age": age})
def run_query(self, query):
c = self.conn.cursor()
c.execute(query)
res = to_json(c)
self.conn.commit()
return res
# Run script that drops and creates all tables
def create_db(self, create_file):
print("Running SQL script file %s" % create_file)
with open(create_file, "r") as f:
self.conn.executescript(f.read())
return '{"message":"created"}'
def import_csvdata(self, username, file, tablename):
c = self.conn.cursor()
c.execute("select user_id from users where username = %s", (username,))
user_id = c.fetchone()[0]
try:
# csv.DictReader uses first line in file for column headings by default
rows = csv.DictReader(file.read().decode().splitlines()) # comma is default delimiter
to_db = None
print("table", tablename)
if tablename == "spending":
to_db = [(row['name'].strip().capitalize(),row['amount'].strip(),row['date'].strip(),row['category'].strip().lower(),row['owner'].strip().capitalize(),row['expense_name'].strip().capitalize(), user_id) for row in rows]
elif tablename == "expenses":
to_db = [(row['name'].strip().capitalize(),row['expected'].strip(),row['due_date'].strip(),row['repeat_type'].strip().lower(),row['owner'].strip().capitalize(), user_id) for row in rows]
elif tablename == "goals":
to_db = [(row['name'].strip().capitalize(),row['target'].strip(),row['amount'].strip(),row['target_date'].strip(),row['owner'].strip().capitalize(), user_id) for row in rows]
elif tablename == "debt":
to_db = [(row['name'].strip().capitalize(),row['amount'].strip(),row['target_date'].strip(),row['owner'].strip().capitalize(), user_id) for row in rows]
elif tablename == "income":
to_db = [(row['name'].strip().capitalize(),row['amount'].strip(),row['date'].strip(),row['type'].strip(),row['owner'].strip().capitalize(), user_id) for row in rows]
else:
raise Exception("need a valid tablename")
except Exception as e:
print("csv import failed: {}".format(e))
return BadRequest(e)
print(to_db)
whichtable = {
"spending":"insert into spending (name,amount,date,category,owner,expense_name,user_id) values (%s,%s,%s,%s,%s,%s,%s)",
"expenses":"insert into expenses (name,expected,due_date,repeat_type,owner,user_id) values (%s,%s,%s,%s,%s,%s)",
"goals":"insert into goals (name,target,amount,target_date,owner,user_id) values (%s,%s,%s,%s,%s,%s)",
"debt":"insert into debt (name,amount,target_date,owner,user_id) values (%s,%s,%s,%s,%s)",
"income":"insert into income (name,amount,date,type,owner,user_id) values (%s,%s,%s,%s,%s,%s)"
}
try:
c.executemany(whichtable[tablename], to_db)
except Exception as e:
print("csv import failed: {}".format(e))
raise BadRequest("make sure the data is formated correctly")
c.close()
self.conn.commit()
return '{"message":"data imported successfully"}'
########################################
## User management ##
########################################
def add_user(self, request):
username = request.form['username']
password = request.form['password']
# encrypt password
# https://nitratine.net/blog/post/how-to-hash-passwords-in-python/#why-you-need-to-hash-passwords
(salt, key) = hash_password(password)
c = self.conn.cursor()
# enforce unique usernames
c.execute(f"select * from users where username = %s", (username,))
record = c.fetchone()
if record:
print("The username {} already exists".format(username))
raise UsernameAlreadyExists("username already exists")
try:
print((salt+key), (salt+key).hex())
c.execute("insert into users (username,password) values (%s,%s)", (username, (salt+key).hex()))
except UsernameAlreadyExists as e:
print("Failed to add new user: {}".format(e))
raise BadRequest(e)
c.close()
self.conn.commit()
return '{"message":"new user inserted"}'
def validate_user(self, request):
username = request.form['username']
password = request.form['password']
# validate password
# https://nitratine.net/blog/post/how-to-hash-passwords-in-python/#why-you-need-to-hash-passwords
c = self.conn.cursor()
try:
c.execute("select * from users where username = %s", (username,))
record = c.fetchone()
if not record:
print("No user with username {} exists".format(username))
return False
except Exception as e:
print("sql error: {}".format(e))
return False
c.close()
print(f"found user with that username: {record}")
print(record[2])
hashed_password = bytes.fromhex(record[2])
print(hashed_password)
salt = hashed_password[:32]
key = hashed_password[32:]
if (hash_password(password, salt)[1] != key):
print("wrong password for user {}".format(username))
return False
return True
########################################
## All Tables ##
########################################
def delete_record(self, username, tablename, rid):
c = self.conn.cursor()
# get active user
c.execute("select user_id from users where username = %s", (username,))
user_id = c.fetchone()[0]
# users can only delete records they created
whichtable = {
"spending":"delete from spending where spending_id = %s and user_id = %s",
"expenses":"delete from expenses where expense_id = %s and user_id = %s",
"goals":"delete from goals where goal_id = %s and user_id = %s",
"debt":"delete from debt where debt_id = %s and user_id = %s",
"income":"delete from income where income_id = %s and user_id = %s",
}
try:
c.execute(whichtable[tablename], (rid,user_id))
except Exception as e:
print("Failed to delete record: {}".format(e))
raise BadRequest(e)
c.close()
self.conn.commit()
return '{"message":"record deleted"}'
########################################
## Expense management ##
########################################
def insert_expense(self, record):
'''
insert an expense given a tuple of values.
assumes that validation has been done
record format: (name, expected, due_date, repeat_type, owner, user_id)
'''
# get active user
c = self.conn.cursor()
# enforce unique names per month
duedate = datetime.strptime(record[2], "%Y-%m-%d").date()
target_month = date(duedate.year, duedate.month, 1).strftime("%Y-%m-%d")
if duedate.month == 12:
next_month = date(duedate.year+1, 1, 1).strftime("%Y-%m-%d")
else:
next_month = date(duedate.year, duedate.month+1, 1).strftime("%Y-%m-%d")
c.execute("select name from expenses where user_id = %s and name = %s and due_date > %s and due_date < %s", (record[5], record[0], target_month, next_month))
res = c.fetchone()
if res:
print("The expense name {} already exists".format(res[0]))
raise UsernameAlreadyExists("Expense name already exists")
try:
print("insert record", record)
c.execute("insert into expenses (name,expected,due_date,repeat_type,owner,user_id) values (%s,%s,%s,%s,%s,%s)", record)
c.execute("select expense_id from expenses where user_id = %s and name = %s", (record[5], record[0]))
except Exception as e:
print("Failed to add expense: {}".format(e))
raise BadRequest(e)
eid = c.fetchone()
c.close()
self.conn.commit()
return eid
def addexpense(self, username, request):
# validate that all required info is here
name = request.form['name'].capitalize()
expected = request.form['expected']
repeat_type = request.form['repeat']
owner = request.form['owner'].capitalize()
if not owner:
owner = username
edate = request.form['date']
if not edate:
edate = date.today().strftime("%Y-%m-%d")
# get active user
c = self.conn.cursor()
c.execute("select user_id from users where username = %s", (username,))
user_id = c.fetchone()[0]
try:
self.insert_expense((name,expected,edate,repeat_type,owner,user_id))
except Exception as e:
print("addexpense error: {}".format(e))
raise BadRequest(e)
c.close()
self.conn.commit()
return '{"message":"new expense inserted"}'
def myexpenses(self, username, target_date):
# get active user
c = self.conn.cursor()
target_month = date(target_date.year, target_date.month, 1).strftime("%Y-%m-%d")
if target_date.month == 12:
next_month = date(target_date.year+1, 1, 1).strftime("%Y-%m-%d")
else:
next_month = date(target_date.year, target_date.month+1, 1).strftime("%Y-%m-%d")
try:
c.execute("select user_id from users where username = %s", (username,))
user_id = c.fetchone()[0]
except Exception as e:
raise Exception("no user_id")
try:
# totals per month
c.execute("select sum(expected) from expenses where user_id = %s and due_date >= %s and due_date < %s", (user_id, target_month, next_month))
etotal = c.fetchone()[0]
if not etotal:
etotal = 0
c.execute("select sum(amount) from spending where user_id = %s and expense_name != '' and date >= %s and date < %s", (user_id, target_month, next_month))
stotal = c.fetchone()[0]
if not stotal:
stotal = 0
c.execute(
'''
select expense_id,to_char(due_date, 'MM/DD/YYYY'),name,expected,repeat_type,owner from expenses
where user_id = %s and due_date >= %s and due_date < %s or repeat_type = 'monthly'
order by due_date asc, name;
''', (user_id,target_month, next_month,)
)
expenses = c.fetchall()
result = []
for e in expenses:
c.execute("select sum(amount) from spending where user_id = %s and expense_name = %s and date >= %s and date < %s", (user_id,e[2],target_month, next_month))
tot = c.fetchone()[0]
if not tot:
tot = 0
c.execute(
'''
select spending_id,to_char(date, 'MM/DD/YY'),name,amount,expense_name,category,owner from spending
where user_id = %s and expense_name = %s and date >= %s and date < %s
order by date desc, name;
''', (user_id, e[2], target_month, next_month)
)
if e[4] == "monthly":
dt = datetime.strptime(e[1], "%m/%d/%Y")
if dt.month == 12:
ad = date(dt.year + 1, 1, dt.day).strftime("%m/%d/%Y")
else:
ad = date(dt.year, target_date.month, dt.day).strftime("%m/%d/%Y")
e = (e[0], ad, e[2], e[3],e[4],e[5])
result += [(e, tot, c.fetchall())]
except Exception as e:
print("Failed to get expenses: {}".format(e))
raise BadRequest(e)
c.close()
self.conn.commit()
return (result, etotal, stotal)
########################################
## Spending management ##
########################################
def addspending(self, username, request):
# validate that all required info is here
name = request.form['name'].capitalize()
amount = request.form['amount']
expensename = request.form['linkedExpense'].capitalize()
if expensename == "":
expensename = None
category = request.form['category'].lower()
owner = request.form['owner']
if not owner:
owner = username
sdate = request.form['date']
if not sdate:
sdate = date.today().strftime("%Y-%m-%d")
c = self.conn.cursor()
# get active user
c.execute("select user_id from users where username = %s", (username,))
user_id = c.fetchone()[0]
try:
c.execute("insert into spending (name,amount,date,category,owner,expense_name,user_id) values (%s,%s,%s,%s,%s,%s,%s)", (name,amount,sdate,category,owner,expensename,user_id))
except Exception as e:
print("Failed to add spending: {}".format(e))
raise BadRequest(e)
c.close()
self.conn.commit()
return '{"message":"new spending inserted"}'
def myspending(self, username, target_date):
# get active user
c = self.conn.cursor()
target_month = date(target_date.year, target_date.month, 1).strftime("%Y-%m-%d")
if target_date.month == 12:
next_month = date(target_date.year+1, 1, 1).strftime("%Y-%m-%d")
else:
next_month = date(target_date.year, target_date.month+1, 1).strftime("%Y-%m-%d")
total = None
try:
c.execute("select user_id from users where username = %s", (username,))
user_id = c.fetchone()[0]
except Exception as e:
raise Exception("no user_id")
try:
c.execute("select sum(amount) from spending where user_id = %s and date >= %s and date < %s", (user_id,target_month,next_month))
total = c.fetchone()[0]
c.execute(
'''
select spending_id,to_char(date, 'MM/DD/YY'),name,amount,expense_name,category,owner from spending
where user_id = %s and date >= %s and date < %s
order by date desc, name;
''', (user_id,target_month,next_month)
)
except Exception as e:
print("Failed to get spending: {}".format(e))
raise BadRequest(e)
result = c.fetchall()
c.close()
self.conn.commit()
return (result, total)
########################################
## Goal management ##
########################################
def addgoal(self, username, request):
# validate that all required info is here
name = request.form['name']
target = request.form['target']
amount = request.form['amount']
owner = request.form['owner']
if not owner:
owner = username
gdate = request.form['date']
# get active user
c = self.conn.cursor()
c.execute("select user_id from users where username = %s", (username,))
user_id = c.fetchone()[0]
try:
c.execute("insert into goals (name,target,amount,target_date,owner,user_id) values (%s,%s,%s,%s,%s,%s)", (name,target,amount,gdate,owner,user_id))
except Exception as e:
print("Failed to add goal: {}".format(e))
raise BadRequest(e)
c.close()
self.conn.commit()
return '{"message":"new goal inserted"}'
def mygoals(self, username):
# get active user
c = self.conn.cursor()
try:
c.execute("select user_id from users where username = %s", (username,))
user_id = c.fetchone()[0]
except Exception as e:
raise Exception("no user_id")
try:
c.execute("select sum(target) from goals where user_id = %s", (user_id,))
total = c.fetchone()[0]
c.execute(
'''
select goal_id,to_char(target_date, 'MM/DD/YY'),name,target,amount,owner from goals
where user_id = %s
order by target_date desc, name;
''', (user_id,)
)
except Exception as e:
print("Failed to get goals: {}".format(e))
raise BadRequest(e)
result = c.fetchall()
c.close()
self.conn.commit()
return (result, total)
########################################
## Debt management ##
########################################
def adddebt(self, username, request):
# validate that all required info is here
name = request.form['name'].capitalize()
amount = request.form['amount']
owner = request.form['owner']
if not owner:
owner = username
ddate = request.form['date']
# get active user
c = self.conn.cursor()
try:
user_id = c.execute("select user_id from users where username = %s", (username,)).fetchone()[0]
c.execute("insert into debt (name,amount,target_date,owner,user_id) values (%s,%s,%s,%s,%s)", (name,amount,ddate,owner,user_id))
except Exception as e:
print("Failed to add debt: {}".format(e))
raise BadRequest(e)
c.close()
self.conn.commit()
return '{"message":"new debt inserted"}'
def mydebt(self, username):
# get active user
c = self.conn.cursor()
try:
c.execute("select user_id from users where username = %s", (username,))
user_id = c.fetchone()[0]
except Exception as e:
raise Exception("no user_id")
try:
total = c.fetchone()[0]
c.execute(
'''
select debt_id,to_char(target_date, 'MM/DD/YY'),name,amount,owner from debt
where user_id = %s
order by target_date desc, name;
''', (user_id,)
)
except Exception as e:
print("Failed to get debt: {}".format(e))
raise BadRequest(e)
result = c.fetchall()
c.close()
self.conn.commit()
return (result, total)
########################################
## Income management ##
########################################
def addincome(self, username, request):
# validate that all required info is here
name = request.form['name'].capitalize()
amount = request.form['amount']
owner = request.form['owner']
type = request.form['type'].lower()
if not owner:
owner = username
idate = request.form['date']
if not idate:
idate = date.today().strftime("%Y-%m-%d")
# get active user
c = self.conn.cursor()
c.execute("select user_id from users where username = %s", (username,))
user_id = c.fetchone()[0]
try:
c.execute("insert into income (name,amount,date,type,owner,user_id) values (%s,%s,%s,%s,%s,%s)", (name,amount,idate,type,owner,user_id))
except Exception as e:
print("Failed to add income: {}".format(e))
raise BadRequest(e)
c.close()
self.conn.commit()
return '{"message":"new income inserted"}'
def myincome(self, username, target_date):
# get active user
c = self.conn.cursor()
target_month = date(target_date.year, target_date.month, 1).strftime("%Y-%m-%d")
if target_date.month == 12:
next_month = date(target_date.year+1, 1, 1).strftime("%Y-%m-%d")
else:
next_month = date(target_date.year, target_date.month+1, 1).strftime("%Y-%m-%d")
try:
c.execute("select user_id from users where username = %s", (username,))
user_id = c.fetchone()[0]
except Exception as e:
raise Exception("no user_id")
try:
c.execute("select sum(amount) from income where user_id = %s and date >= %s and date < %s", (user_id,target_month,next_month))
total = c.fetchone()[0]
c.execute(
'''
select income_id,to_char(date, 'MM/DD/YY'),name,amount,type,owner from income
where user_id = %s and date >= %s and date < %s
order by date desc, name;
''', (user_id,target_month,next_month)
)
except Exception as e:
print("Failed to get income: {}".format(e))
raise BadRequest(e)
result = c.fetchall()
c.close()
self.conn.commit()
return (result, total)
|
{"/app.py": ["/db.py"]}
|
17,219,803
|
michael-martinson/MyFinancials
|
refs/heads/main
|
/app.py
|
from flask import (
Flask,
render_template,
request,
redirect,
url_for,
logging,
session,
g,
Response,
)
# import sqlite3
import json
from markupsafe import escape
import secrets
import os
import datetime, calendar
from db import (DB, BadRequest, KeyNotFound, UsernameAlreadyExists)
import psycopg2
# Configure application
app = Flask(__name__)
app.config.update(SESSION_COOKIE_SAMESITE="None", SESSION_COOKIE_SECURE=True)
# path to database
# DATABASE = './myfinancials.db'
# Set the secret key to some random bytes. Keep this really secret!
app.secret_key = 'f4_LpwUFVA2WaLjsjcwrgS8WrFt4pmAa4A'
########################################
## login endpoints ##
########################################
@app.route("/login", methods=["GET", "POST"])
def login():
error = None
if request.method == 'POST':
if request.form['username'] and request.form['password']:
db = DB(get_db())
try:
if db.validate_user(request):
session['username'] = request.form['username']
else:
error = 'Invalid Credentials. Please try again.'
return render_template('login.html', newuser=False, error=error)
except Exception as e:
app.logger.error(e)
error = 'Invalid Credentials. Please try again.'
return render_template('login.html', newuser=False, error=error)
return redirect(url_for('myexpenses'))
else:
error = 'Username or Password was empty. Please try again.'
return render_template('login.html', newuser=False, error=error)
@app.route("/newuser", methods=["GET", "POST"])
def createuser():
error = None
if request.method == 'POST':
db = DB(get_db())
try:
db.add_user(request)
session['username'] = request.form['username']
except UsernameAlreadyExists as e:
app.logger.error(e.message)
error = "Username already exists. Try a different one."
return render_template('login.html', newuser=True, error=error)
except Exception as e:
app.logger.error(e)
return render_template('login.html', newuser=True, error=e)
return redirect(url_for('myexpenses'))
return render_template('login.html', newuser=True, error=error)
@app.route('/logout')
def logout():
# remove the username from the session if it's there
session.pop('username', None)
return redirect(url_for('login'))
########################################
## Expense endpoints ##
########################################
@app.route('/addexpense', methods=['POST'])
def addexpense():
if not check_logged_in():
return redirect(url_for('login'))
db = DB(get_db())
message = "Expense added successfully"
try:
db.addexpense(session['username'], request)
except BadRequest as e:
app.logger.error(f"{e}")
message = "Add expense failed. Make user form input is correct"
return redirect(url_for('myexpenses'))
@app.route("/")
@app.route("/myexpenses/")
@app.route('/myexpenses/<target_date>', methods=['Get'])
def myexpenses(target_date = None):
if not check_logged_in():
print("hiiiii")
return redirect(url_for('login'))
db = DB(get_db())
message = None
myexpenses = None
etot = None
stot = None
if not target_date:
target_date = datetime.date.today()
else:
target_date = datetime.datetime.strptime(target_date, "%Y-%m-%d").date()
try:
(myexpenses,etot,stot) = db.myexpenses(session['username'], target_date)
except BadRequest as e:
app.logger.error(f"{e}")
message = "Something went wrong. Please try again"
except Exception as e:
return redirect(url_for('login'))
return render_template(
"myexpenses.html",
rows=myexpenses,
etotal=etot,
stotal=stot,
month=calendar.month_name[target_date.month],
year=target_date.year,
table="expenses",
message=message,
username=session['username']
)
########################################
## Spending endpoints ##
########################################
@app.route('/addspending', methods=['POST'])
def addspending():
if not check_logged_in():
return redirect(url_for('login'))
db = DB(get_db())
message = "Spending added successfully"
try:
db.addspending(session['username'], request)
except BadRequest as e:
app.logger.error(f"{e}")
message = "Add spending failed. Make user form input is correct"
return redirect(url_for('myspending'))
@app.route('/myspending/', methods=['Get'])
@app.route('/myspending/<target_date>', methods=['Get'])
def myspending(target_date = None):
if not check_logged_in():
return redirect(url_for('login'))
db = DB(get_db())
message = None
myspending = None
if not target_date:
target_date = datetime.date.today()
else:
target_date = datetime.datetime.strptime(target_date, "%Y-%m-%d").date()
try:
(myspending, total) = db.myspending(session['username'], target_date)
except BadRequest as e:
app.logger.error(f"{e}")
message = "Something went wrong. Please try again"
return render_template(
"myspending.html",
rows=myspending,
total=total,
month=calendar.month_name[target_date.month],
year=target_date.year,
table="spending",
message=message,
username=session['username']
)
########################################
## Goal endpoints ##
########################################
@app.route('/addgoal', methods=['POST'])
def addgoal():
if not check_logged_in():
return redirect(url_for('login'))
db = DB(get_db())
message = "goal added successfully"
try:
db.addgoal(session['username'], request)
except BadRequest as e:
app.logger.error(f"{e}")
message = "Add goal failed. Make user form input is correct"
return redirect(url_for('mygoals'))
@app.route('/mygoals/', methods=['Get'])
def mygoals():
if not check_logged_in():
return redirect(url_for('login'))
db = DB(get_db())
message = None
mygoals = None
try:
(mygoals, total) = db.mygoals(session['username'])
except BadRequest as e:
app.logger.error(f"{e}")
message = "Something went wrong. Please try again"
return render_template(
"mygoals.html",
rows=mygoals,
total=total,
table="goals",
message=message,
username=session['username']
)
########################################
## Debt endpoints ##
########################################
@app.route('/adddebt', methods=['POST'])
def adddebt():
if not check_logged_in():
return redirect(url_for('login'))
db = DB(get_db())
message = "Debt added successfully"
try:
db.adddebt(session['username'], request)
except BadRequest as e:
app.logger.error(f"{e}")
message = "Add Debt failed. Make user form input is correct"
return redirect(url_for('mydebt'))
@app.route('/mydebt/', methods=['Get'])
def mydebt():
if not check_logged_in():
return redirect(url_for('login'))
db = DB(get_db())
message = None
mydebt = None
try:
(mydebt, total) = db.mydebt(session['username'])
except BadRequest as e:
app.logger.error(f"{e}")
message = "Something went wrong. Please try again"
return render_template(
"mydebt.html",
total=total,
rows=mydebt,
table="debt",
message=message,
username=session['username']
)
########################################
## Income endpoints ##
########################################
@app.route('/addincome', methods=['POST'])
def addincome():
if not check_logged_in():
return redirect(url_for('login'))
db = DB(get_db())
message = "Income added successfully"
try:
db.addincome(session['username'], request)
except BadRequest as e:
app.logger.error(f"{e}")
message = "Add income failed. Make user form input is correct"
return redirect(url_for('myincome'))
@app.route('/myincome/', methods=['Get'])
@app.route('/myincome/<target_date>', methods=['Get'])
def myincome(target_date = None):
if not check_logged_in():
return redirect(url_for('login'))
db = DB(get_db())
message = None
myincome = None
if not target_date:
target_date = datetime.date.today()
else:
target_date = datetime.datetime.strptime(target_date, "%Y-%m-%d").date()
try:
(myincome, total) = db.myincome(session['username'], target_date)
except BadRequest as e:
app.logger.error(f"{e}")
message = "Something went wrong. Please try again"
return render_template(
"myincome.html",
rows=myincome,
total=total,
month=calendar.month_name[target_date.month],
year=target_date.year,
table="income",
message=message,
username=session['username']
)
########################################
## Delete endpoints ##
########################################
@app.route('/deleterow', methods=['POST'])
def deleterow():
if not check_logged_in():
return redirect(url_for('login'))
db = DB(get_db())
message = "row deleted successfully"
try:
data = json.loads(request.data.decode())
db.delete_record(session['username'], data['tablename'], data['rid'])
except BadRequest as e:
app.logger.error(f"{e}")
message = "Something went wrong. Please try again"
return redirect(url_for("my{}".format(data['tablename']), message=message))
########################################
## Import endpoints ##
########################################
@app.route('/importcsv', methods=['GET', 'POST'])
def importcsv():
if not check_logged_in():
return redirect(url_for('login'))
db = DB(get_db())
message = None
try:
db.import_csvdata(session['username'], request.files['csvfile'], request.form['tablename'])
except BadRequest as e:
app.logger.error(f"{e}")
message = "Something went wrong. Please try again"
return redirect(url_for("my{}".format(request.form['tablename']), message=message))
########################################
## Utility functions ##
########################################
def check_logged_in():
print(session)
if 'username' in session:
print("you are logged in! " + session['username'])
return True
print("go log in")
return False
# connect to db
def get_db():
db = getattr(g, '_database', None)
if db is None:
# db = g._database = sqlite3.connect(DATABASE)
#establishing the connection
db = g._database = psycopg2.connect(
database="d6coe2acjtc5c2",
user='hivembvhcpxsdb',
password='1321404f100002f28266e3b26d0b79106cd73fb9e58d7ad4127d759d8482b649',
port='5432',
host='ec2-52-21-153-207.compute-1.amazonaws.com',
)
db.autocommit = True
return db
# close connectiong to db
@app.teardown_appcontext
def close_connection(exception):
db = getattr(g, '_database', None)
if db is not None:
db.close()
# Create Database
def init_db():
with app.app_context():
db = get_db()
with app.open_resource('./static/schema.sql', mode='r') as f:
db.cursor().execute(f.read())
db.commit()
if __name__ == "__main__":
app.run(threaded=True, port=5000, debug=False)
|
{"/app.py": ["/db.py"]}
|
17,239,805
|
shahinaca/Teacher-Directory-App
|
refs/heads/master
|
/app/migrations/0001_initial.py
|
# Generated by Django 3.2.7 on 2021-09-28 19:39
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Teacher',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('first_name', models.CharField(max_length=255)),
('last_name', models.CharField(max_length=255)),
('profile_picture', models.CharField(max_length=2500)),
('email_address', models.CharField(max_length=255, unique=True)),
('phone_number', models.CharField(max_length=20)),
('room_number', models.CharField(max_length=20)),
('subject_taught', models.TextField()),
],
),
]
|
{"/portal/teacher_app/views.py": ["/portal/teacher_app/forms.py"], "/app/forms.py": ["/app/models.py"], "/app/views.py": ["/app/models.py", "/app/forms.py"], "/app/admin.py": ["/app/models.py"]}
|
17,239,806
|
shahinaca/Teacher-Directory-App
|
refs/heads/master
|
/app/forms.py
|
from django import forms
from .models import Teacher
class TeacherForm(forms.ModelForm):
first_name = forms.CharField(
required=True)
last_name = forms.CharField(
required=True)
profile_picture = forms.CharField(
required=False)
email_address = forms.CharField(
required=True)
phone_number = forms.CharField(
required=False)
room_number = forms.CharField(
required=False)
subjects_taught = forms.CharField(
required=False)
profile_path = forms.CharField(
required=False)
class Meta:
model = Teacher
fields = [
'first_name',
'last_name',
'profile_picture',
'email_address',
'phone_number',
'room_number',
'subjects_taught',
'profile_path'
]
def __init__(self, *args, **kwargs):
super(TeacherForm, self).__init__(*args, **kwargs)
self.fields['first_name'].error_messages = {'required': 'The field First Name is required. '}
self.fields['last_name'].error_messages = {'required': 'The field Last Name is required. '}
self.fields['email_address'].error_messages = {'required': 'The field Email is required. '}
|
{"/portal/teacher_app/views.py": ["/portal/teacher_app/forms.py"], "/app/forms.py": ["/app/models.py"], "/app/views.py": ["/app/models.py", "/app/forms.py"], "/app/admin.py": ["/app/models.py"]}
|
17,239,807
|
shahinaca/Teacher-Directory-App
|
refs/heads/master
|
/app/urls.py
|
from django.urls import path
from . import views
urlpatterns = [
path('', views.dashboard.as_view(), name='dashboard'),
path('<tagname>', views.htmlView.as_view(), name='htmlview'),
path('teacher-view/<id>', views.teacherView.as_view(), name='teacherview')
]
|
{"/portal/teacher_app/views.py": ["/portal/teacher_app/forms.py"], "/app/forms.py": ["/app/models.py"], "/app/views.py": ["/app/models.py", "/app/forms.py"], "/app/admin.py": ["/app/models.py"]}
|
17,239,808
|
shahinaca/Teacher-Directory-App
|
refs/heads/master
|
/app/migrations/0003_auto_20210929_1810.py
|
# Generated by Django 3.2.7 on 2021-09-29 14:10
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('app', '0002_auto_20210929_1236'),
]
operations = [
migrations.CreateModel(
name='UploadLog',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('teachers_details', models.FileField(upload_to='')),
('image_details', models.FileField(default=False, upload_to='')),
],
),
migrations.AlterField(
model_name='teacher',
name='profile_picture',
field=models.CharField(default='null', max_length=255),
),
]
|
{"/portal/teacher_app/views.py": ["/portal/teacher_app/forms.py"], "/app/forms.py": ["/app/models.py"], "/app/views.py": ["/app/models.py", "/app/forms.py"], "/app/admin.py": ["/app/models.py"]}
|
17,239,809
|
shahinaca/Teacher-Directory-App
|
refs/heads/master
|
/app/views.py
|
from django.shortcuts import render
# Create your views here.
from django.shortcuts import render
from django.http import HttpResponseRedirect, HttpResponse
from django.views import View
from .models import Teacher
from django.contrib.auth.models import User
from django.contrib.auth import authenticate, login, logout
from django.db.models import ObjectDoesNotExist
from django.core.paginator import Paginator #import Paginator
from django import forms
from .forms import TeacherForm
from django.contrib import messages
from zipfile import ZipFile
from django.conf import settings
from io import BytesIO
import os
from django.core.files.storage import default_storage
from django.core.files.base import ContentFile
import io
import csv
# Create your views here.
#
class dashboard(View):
def get(self, request):
teachers = Teacher.objects.all()
return render(request, 'dashboard.html', {'teachers': teachers, 'filename': 'dashboard'})
class htmlView(View):
def get(self, request, tagname):
# Teacher List
if tagname in ["teachers"]:
last_name = request.GET.get("last_name")
subjects_taught = request.GET.get("subjects_taught")
teachers = Teacher.objects
if last_name or subjects_taught:
if subjects_taught:
teachers = teachers.filter(subjects_taught__contains=subjects_taught)
if last_name:
teachers = teachers.filter(last_name__contains=last_name)
else:
teachers = teachers.all()
paginator = Paginator(teachers, 5)
page_number = request.GET.get('page')
teachers = paginator.get_page(page_number)
return render(request, 'teacher/list.html', {'teachers': teachers, 'filename': tagname, 'subjects_taught': subjects_taught, 'last_name': last_name})
# Teacher Upload
if tagname in ["teacher-upload"]:
if request.user.is_authenticated:
if request.session.get('url_redirect'):
del request.session['url_redirect']
return render(request, 'teacher/upload.html', {'filename': tagname})
else:
request.session['url_redirect'] = "/teacher-upload"
return HttpResponseRedirect('/login')
# Login
if tagname in ["login"]:
if request.user.is_authenticated:
if request.session.get('url_redirect'):
return HttpResponseRedirect(request.session.get('url_redirect'))
return HttpResponseRedirect('/teachers')
else:
return render(request, 'login.html', {'filename': tagname})
if tagname in ["logout"]:
if request.user.is_authenticated:
logout(request)
messages.success(request, "You have successfully logged out")
return HttpResponseRedirect('/teachers')
else:
return render(request, '404.html')
def post(self, request, tagname):
# Login Update
if tagname in ["teacher-upload"]:
if request.user.is_authenticated:
error_all = {}
error_string = str()
try:
# Zip File Getting
zip_file = ZipFile(request.FILES['image_details'])
# Form Validation
form = UploadFileForm(request.POST, request.FILES)
if form.is_valid():
# CSV Data Fetching
csv_file = request.FILES['teachers_details']
if not csv_file.name.endswith('.csv'):
error = 'File is not CSV type'
return HttpResponse(error)
# if file is too large, return
if csv_file.multiple_chunks():
error = "Uploaded file is too big (%.2f MB)." % (csv_file.size / (1000 * 1000),)
return HttpResponse(error)
file_data = csv_file.read().decode("utf-8")
io_string = io.StringIO(file_data)
lines = file_data.split("\n")
headers = lines[0].lower().strip().replace(" ", "_")
array_corrector = headers.split(",")
next(io_string)
# return HttpResponse(csv.reader(io_string))
i = 0
for row in csv.reader(io_string):
i = i + 1
data_dict = {}
data_dict[array_corrector[0]] = row[0]
data_dict[array_corrector[1]] = row[1]
data_dict[array_corrector[2]] = row[2]
data_dict[array_corrector[3]] = row[3]
data_dict[array_corrector[4]] = row[4]
data_dict[array_corrector[5]] = row[5]
data_dict[array_corrector[6]] = row[6]
list_of_subjects_taught = []
subjects_taught = []
if data_dict["subjects_taught"]:
subjects_taught = data_dict["subjects_taught"].split(",")
# Unique Subjects
for single_entry in subjects_taught:
single_entry = single_entry.strip()
if single_entry not in list_of_subjects_taught:
list_of_subjects_taught.append(single_entry)
subjects_taught_total = len(list_of_subjects_taught)
data_dict["subjects_taught"] = ', '.join(list_of_subjects_taught)
form = TeacherForm(data_dict)
try:
if form.is_valid():
# Validate Subjects greater than 5
if subjects_taught_total > 5:
error_string = error_string + ' <br> Row- ' + str(
i) + ' No More than 5 Subjects'
continue
# getting Suitable profile picture for the teacher
if len(data_dict['profile_picture']) >= 3:
name = data_dict['profile_picture']
try:
data = zip_file.read(data_dict['profile_picture'])
from PIL import Image
image = Image.open(BytesIO(data))
image.load()
image = Image.open(BytesIO(data))
image.verify()
name = os.path.split(name)[1]
# You now have an image which you can save
path = os.path.join(settings.MEDIA_ROOT, "app/static/storage/profile",
name)
saved_path = default_storage.save(path, ContentFile(data))
data_dict["profile_path"] = saved_path
except ImportError as e:
error_all[str(i)] = form.errors.as_json()
error_string = error_string + ' <br> Row- ' + str(i) + ' Image Not Exist'
pass
except Exception as e:
error_all[str(i)] = form.errors.as_json()
error_string = error_string + ' <br> Row- ' + str(i) + ' Image Not Exist'
form = TeacherForm(data_dict)
try:
if form.is_valid():
print("true")
else:
error_all[str(i)] = form.errors.as_json()
error_string = error_string + ' <br> Row- ' + str(i) + ' ' + ' '.join(
[' '.join(x for x in l) for l in list(form.errors.values())])
continue
except Exception as e:
error_all[str(i)] = form.errors.as_json()
error_string = error_string + ' <br> Row- ' + str(i) + 'Please Check data'
continue
# form Save
form.save()
else:
if subjects_taught_total > 5:
error_string = error_string + ' <br> Row- ' + str(
i) + ' No More than 5 Subjects'
error_string = error_string + ' <br> Row- ' + str(i) + ' ' + ' '.join(
[' '.join(x for x in l) for l in list(form.errors.values())])
except Exception as e:
error_string = error_string + ' <br> Row- ' + str(i) + 'Please Check the data'
pass
else:
messages.add_message(request, messages.ERROR, "Unable to upload file")
return HttpResponseRedirect("/teacher-upload")
except Exception as e:
messages.add_message(request, messages.ERROR, "Unable to upload file.")
return HttpResponseRedirect("/teacher-upload")
if len(error_string.strip()) >= 1:
messages.add_message(request, messages.WARNING, error_string)
return HttpResponseRedirect("/teacher-upload")
else:
messages.add_message(request, messages.SUCCESS, 'Uploaded Successfully !!')
return HttpResponseRedirect("/teachers")
else:
return HttpResponseRedirect('/login')
# Login Update
if tagname == "login":
if request.user.is_authenticated:
return HttpResponseRedirect('/teacher-upload')
else:
username = request.POST.get("username")
password = request.POST.get("password")
try:
if "@" in username:
user = User.objects.get(email=username)
else:
user = User.objects.get(username=username)
user = authenticate(request, username=user.username, password=password)
if user is not None:
login(request, user)
messages.success(request, "You have successfully logged in")
if request.session.get('url_redirect'):
return HttpResponseRedirect(request.session.get('url_redirect'))
return HttpResponseRedirect("/teachers")
else:
messages.add_message(request, messages.ERROR, "Wrong password")
except ObjectDoesNotExist:
messages.add_message(request, messages.ERROR, "User not found")
return HttpResponseRedirect("/login")
class teacherView(View):
def get(self, request, id):
teacher = Teacher.objects.filter(id = id).first()
return render(request, 'teacher/teacher_view.html', {'teacher': teacher, 'filename': 'teacherview'})
class UploadFileForm(forms.Form):
teachers_details = forms.FileField()
image_details = forms.FileField(allow_empty_file=False)
|
{"/portal/teacher_app/views.py": ["/portal/teacher_app/forms.py"], "/app/forms.py": ["/app/models.py"], "/app/views.py": ["/app/models.py", "/app/forms.py"], "/app/admin.py": ["/app/models.py"]}
|
17,239,810
|
shahinaca/Teacher-Directory-App
|
refs/heads/master
|
/app/models.py
|
from django.db import models
# Create your models here.
class Teacher(models.Model):
first_name = models.CharField(max_length=255)
last_name = models.CharField(max_length=255)
profile_picture = models.CharField(max_length=255, default='null')
email_address = models.CharField(max_length=255, unique=True)
phone_number = models.CharField(max_length=20)
room_number = models.CharField(max_length=20)
subjects_taught = models.TextField()
profile_path = models.CharField(max_length=255, default='null')
# Create your models here.
class UploadLog(models.Model):
teachers_details = models.FileField()
image_details = models.FileField(default=False)
|
{"/portal/teacher_app/views.py": ["/portal/teacher_app/forms.py"], "/app/forms.py": ["/app/models.py"], "/app/views.py": ["/app/models.py", "/app/forms.py"], "/app/admin.py": ["/app/models.py"]}
|
17,239,811
|
shahinaca/Teacher-Directory-App
|
refs/heads/master
|
/app/admin.py
|
from django.contrib import admin
from .models import Teacher
# Register your models here.
class TeacherAdmin(admin.ModelAdmin):
list_display = ('first_name','last_name')
# Register your models here.
admin.site.register(Teacher,TeacherAdmin)
|
{"/portal/teacher_app/views.py": ["/portal/teacher_app/forms.py"], "/app/forms.py": ["/app/models.py"], "/app/views.py": ["/app/models.py", "/app/forms.py"], "/app/admin.py": ["/app/models.py"]}
|
17,337,389
|
mindfirst-admin/mindfirst
|
refs/heads/main
|
/behaviours/models.py
|
from django.db import models
from accounts.models import Users
# Create your models here.
class BehaviourMapping(models.Model):
user = models.ForeignKey(Users, on_delete=models.CASCADE)
title = models.CharField(max_length=255, default='')
description = models.CharField(max_length=1024, default='', blank=True, null=True)
value = models.CharField(max_length=3, default='+ve')
impact = models.IntegerField(default=0)
difficulty = models.IntegerField(default=0)
is_scaled = models.BooleanField(default=False)
is_selected = models.BooleanField(default=False)
done_today = models.BooleanField(default=False)
thumbs_up_today = models.IntegerField(default=0)
thumbs_down_today = models.IntegerField(default=0)
thumbs_up_this_week = models.IntegerField(default=0)
thumbs_down_this_week = models.IntegerField(default=0)
def __str__(self):
return self.title
class DesignPositiveHabits(models.Model):
behaviour = models.OneToOneField(BehaviourMapping, on_delete=models.CASCADE)
after_or_before = models.CharField(max_length=255, default='')
act = models.CharField(max_length=255, default='')
celebrate = models.CharField(max_length=255, default='')
frequency = models.CharField(max_length=255, default='')
number_of_times = models.CharField(max_length=2, default=0)
class DesignNegativeHabits(models.Model):
behaviour = models.OneToOneField(BehaviourMapping, on_delete=models.CASCADE)
trigger = models.CharField(max_length=255, default='')
make_less_obvious = models.CharField(max_length=255, default='')
make_harder = models.CharField(max_length=255, default='')
frequency = models.CharField(max_length=255, default='')
number_of_times = models.CharField(max_length=2, default=0)
class LimitingBeliefs(models.Model):
user = models.ForeignKey(Users, on_delete=models.CASCADE)
beliefs = models.CharField(max_length=10000)
|
{"/accounts/extras_.py": ["/accounts/models.py"], "/accounts/migrations/0017_auto_20210809_2204.py": ["/accounts/models.py"], "/user_files/migrations/0003_auto_20210727_2335.py": ["/user_files/models.py"], "/accounts/migrations/0001_initial.py": ["/accounts/models.py"], "/characters/models.py": ["/accounts/models.py"], "/background_apps/functions.py": ["/accounts/models.py", "/characters/models.py"], "/main/views.py": ["/accounts/models.py", "/accounts/extras_.py", "/user_files/models.py", "/characters/models.py", "/behaviours/models.py", "/files_gallery/models.py"], "/api/views.py": ["/accounts/extras_.py", "/user_files/models.py", "/api/models.py"], "/user_files/views.py": ["/user_files/models.py"], "/characters/views.py": ["/characters/models.py", "/accounts/models.py"], "/accounts/tests.py": ["/accounts/models.py"], "/accounts/views.py": ["/accounts/models.py", "/accounts/extras_.py"], "/behaviours/models.py": ["/accounts/models.py"], "/behaviours/views.py": ["/accounts/models.py", "/behaviours/models.py"], "/files_gallery/models.py": ["/accounts/models.py"], "/behaviours/forms.py": ["/accounts/models.py", "/behaviours/models.py"], "/files_gallery/migrations/0001_initial.py": ["/files_gallery/models.py"], "/files_gallery/views.py": ["/files_gallery/models.py"], "/db_generated/views.py": ["/db_generated/models.py"], "/background/cron.py": ["/accounts/models.py", "/behaviours/models.py"], "/files_gallery/forms.py": ["/files_gallery/models.py"], "/db_generated/admin.py": ["/db_generated/models.py"], "/behaviours/admin.py": ["/behaviours/models.py"], "/files_gallery/admin.py": ["/files_gallery/models.py"], "/payment_system/views.py": ["/payment_system/models.py"]}
|
17,337,390
|
mindfirst-admin/mindfirst
|
refs/heads/main
|
/behaviours/views.py
|
import datetime
from django.contrib import messages
from django.shortcuts import render, redirect
from accounts.models import Users, Profile
from .models import *
# Create your views here.
def behaviour_mapping(request):
if request.user.is_authenticated:
profile = Profile.objects.get(user=request.user)
aspiration_name = profile.aspiration_name
return render(request, 'behaviours/behaviour_mapping.html', {'aspiration_name': aspiration_name})
return redirect('accounts:sign_in_to_members_area')
def habit_design(request, behaviour_id):
if request.user.is_authenticated:
if BehaviourMapping.objects.filter(id=behaviour_id).count() == 0:
messages.error(request, 'This behavior doesn\'t exists')
return redirect('main:members_area')
"""get aspiration image"""
aspiration_image = ''
behaviour = BehaviourMapping.objects.filter(id=behaviour_id).first()
if behaviour.value == '+ve':
print(DesignPositiveHabits.objects.filter(behaviour=behaviour).first())
content = {'aspirations_image': aspiration_image,
'behaviour': BehaviourMapping.objects.filter(id=behaviour_id).first(),
'habit_design': DesignPositiveHabits.objects.filter(behaviour=behaviour).first()}
return render(request, 'behaviours/positive_habit_design.html', content)
else:
content = {'aspirations_image': aspiration_image,
'behaviour': BehaviourMapping.objects.filter(id=behaviour_id).first(),
'habit_design': DesignNegativeHabits.objects.filter(behaviour=behaviour).first()}
return render(request, 'behaviours/negative_habit_design.html', content)
return redirect('accounts:sign_in_to_members_area')
def habit_reporting(request, orientation):
if request.user.is_authenticated:
"""get aspiration image"""
aspiration_image = ''
"""ensure there is a behaviour"""
if BehaviourMapping.objects.filter(user=request.user).count() == 0:
messages.error(request, 'You need to create a behaviour before accessing this page')
return redirect('main:members_area')
"""ensure all habits are designed"""
for i in BehaviourMapping.objects.filter(user=request.user).all():
if i.value == '+ve':
try:
test_habit = i.designpositivehabits
except Exception as e:
messages.error(request,
'You have one or more habits still to design for, please scroll to the habit '
'designer, click the dropdown menus for both positive or negative habits and '
'complete a habit design for each of the listed habits, after this you will be'
' able review them. Thank you.')
return redirect("main:members_area")
elif i.value == '-ve':
try:
test_habit = i.designnegativehabits
except Exception as e:
messages.error(request,
'You have one or more habits still to design for, please scroll to the habit '
'designer, click the dropdown menus for both positive or negative habits and '
'complete a habit design for each of the listed habits, after this you will be'
' able review them. Thank you.')
return redirect("main:members_area")
now = datetime.datetime.now()
today = now.strftime("%A")
if orientation == 'positive':
if today.lower() == 'sunday':
behaviours = [i for i in BehaviourMapping.objects.filter(user=request.user, is_selected=True,
value='+ve').all() if
i.designpositivehabits.frequency == 'weekly']
else:
behaviours = [i for i in BehaviourMapping.objects.filter(user=request.user, is_selected=True,
value='+ve').all() if
i.designpositivehabits.frequency != 'weekly']
return render(request, 'behaviours/positive_habit_reporting.html', {'behaviours': behaviours,
'aspiration_image': aspiration_image, })
elif orientation == 'negative':
if today.lower() == 'sunday':
behaviours = [i for i in BehaviourMapping.objects.filter(user=request.user, is_selected=True,
value='-ve').all() if
i.designnegativehabits.frequency == 'weekly']
else:
behaviours = [i for i in BehaviourMapping.objects.filter(user=request.user, is_selected=True,
value='-ve').all() if
i.designnegativehabits.frequency != 'weekly']
return render(request, 'behaviours/negative_habit_reporting.html', {'behaviours': behaviours,
'aspiration_image': aspiration_image, })
else:
return render(request, 'main/404.html')
return redirect('accounts:sign_in_to_members_area')
def habit_summary(request, orientation):
if request.user.is_authenticated:
"""get aspiration image"""
aspiration_image = ''
"""ensure there is a behaviour"""
if BehaviourMapping.objects.filter(user=request.user).count() == 0:
messages.error(request, 'You need to create a behaviour before accessing this page')
return redirect('main:members_area')
"""ensure all habits are designed"""
for i in BehaviourMapping.objects.filter(user=request.user).all():
if i.value == '+ve':
try:
test_habit = i.designpositivehabits
except Exception as e:
messages.error(request,
'You have one or more habits still to design for, please scroll to the habit '
'designer, click the dropdown menus for both positive or negative habits and '
'complete a habit design for each of the listed habits, after this you will be'
' able review them. Thank you.')
return redirect("main:members_area")
elif i.value == '-ve':
try:
test_habit = i.designnegativehabits
except Exception as e:
messages.error(request,
'You have one or more habits still to design for, please scroll to the habit '
'designer, click the dropdown menus for both positive or negative habits and '
'complete a habit design for each of the listed habits, after this you will be'
' able review them. Thank you.')
return redirect("main:members_area")
now = datetime.datetime.now()
today = now.strftime("%A")
aspiration_name = request.user.profile.aspiration_name
if orientation == 'positive':
if today.lower() == 'sunday':
behaviours = [i for i in BehaviourMapping.objects.filter(user=request.user, is_selected=True,
value='+ve').all() if
i.designpositivehabits.frequency == 'weekly']
else:
behaviours = [i for i in BehaviourMapping.objects.filter(user=request.user, is_selected=True,
value='+ve').all() if
i.designpositivehabits.frequency != 'weekly']
# for habits done today i.e first chart
selected_behaviors = len(behaviours)
positive_habits_done_today = str(len([i for i in behaviours if i.done_today])) + '/' + str(
selected_behaviors)
first_chart_value = (len([i for i in behaviours if i.done_today]) / selected_behaviors) * 100
# for habits done this week i.e second chart
positive_behaviors_done_this_week = request.user.profile.positive_behaviors_done_this_week
if positive_behaviors_done_this_week == '0/0':
second_chart_value = 0
else:
count = positive_behaviors_done_this_week.split('/')[0]
count_2 = positive_behaviors_done_this_week.split('/')[1]
second_chart_value = (int(count) / int(count_2)) * 100
print(first_chart_value)
content = {'behaviours': behaviours,
'aspiration_image': aspiration_image,
'aspiration_name': aspiration_name,
'positive_habits_done_today': positive_habits_done_today,
'first_chart_value': first_chart_value,
'positive_behaviors_done_this_week': positive_behaviors_done_this_week,
'second_chart_value': second_chart_value}
return render(request, 'behaviours/positive_habit_summary.html', content)
elif orientation == 'negative':
if today.lower() == 'sunday':
behaviours = [i for i in BehaviourMapping.objects.filter(user=request.user, is_selected=True,
value='-ve').all() if
i.designnegativehabits.frequency == 'weekly']
else:
behaviours = [i for i in BehaviourMapping.objects.filter(user=request.user, is_selected=True,
value='-ve').all() if
i.designnegativehabits.frequency != 'weekly']
# for habits done today i.e first chart
selected_behaviors = len(behaviours)
negative_habits_done_today = str(len([i for i in behaviours if i.done_today])) + '/' + str(
selected_behaviors)
first_chart_value = (len([i for i in behaviours if i.done_today]) / selected_behaviors) * 100
# for habits done this week i.e second chart
negative_behaviors_done_this_week = request.user.profile.negative_behaviors_done_this_week
if negative_behaviors_done_this_week == '0/0':
second_chart_value = 0
else:
count = negative_behaviors_done_this_week.split('/')[0]
count_2 = negative_behaviors_done_this_week.split('/')[1]
second_chart_value = (int(count) / int(count_2)) * 100
print(first_chart_value)
content = {'behaviours': behaviours,
'aspiration_image': aspiration_image,
'aspiration_name': aspiration_name,
'negative_habits_done_today': negative_habits_done_today,
'first_chart_value': first_chart_value,
'negative_behaviors_done_this_week': negative_behaviors_done_this_week,
'second_chart_value': second_chart_value}
return render(request, 'behaviours/negative_habit_summary.html', content)
else:
return render(request, 'main/404.html')
return redirect('accounts:sign_in_to_members_area')
|
{"/accounts/extras_.py": ["/accounts/models.py"], "/accounts/migrations/0017_auto_20210809_2204.py": ["/accounts/models.py"], "/user_files/migrations/0003_auto_20210727_2335.py": ["/user_files/models.py"], "/accounts/migrations/0001_initial.py": ["/accounts/models.py"], "/characters/models.py": ["/accounts/models.py"], "/background_apps/functions.py": ["/accounts/models.py", "/characters/models.py"], "/main/views.py": ["/accounts/models.py", "/accounts/extras_.py", "/user_files/models.py", "/characters/models.py", "/behaviours/models.py", "/files_gallery/models.py"], "/api/views.py": ["/accounts/extras_.py", "/user_files/models.py", "/api/models.py"], "/user_files/views.py": ["/user_files/models.py"], "/characters/views.py": ["/characters/models.py", "/accounts/models.py"], "/accounts/tests.py": ["/accounts/models.py"], "/accounts/views.py": ["/accounts/models.py", "/accounts/extras_.py"], "/behaviours/models.py": ["/accounts/models.py"], "/behaviours/views.py": ["/accounts/models.py", "/behaviours/models.py"], "/files_gallery/models.py": ["/accounts/models.py"], "/behaviours/forms.py": ["/accounts/models.py", "/behaviours/models.py"], "/files_gallery/migrations/0001_initial.py": ["/files_gallery/models.py"], "/files_gallery/views.py": ["/files_gallery/models.py"], "/db_generated/views.py": ["/db_generated/models.py"], "/background/cron.py": ["/accounts/models.py", "/behaviours/models.py"], "/files_gallery/forms.py": ["/files_gallery/models.py"], "/db_generated/admin.py": ["/db_generated/models.py"], "/behaviours/admin.py": ["/behaviours/models.py"], "/files_gallery/admin.py": ["/files_gallery/models.py"], "/payment_system/views.py": ["/payment_system/models.py"]}
|
17,337,391
|
mindfirst-admin/mindfirst
|
refs/heads/main
|
/files_gallery/models.py
|
from django.db import models
from accounts.models import Users
# Create your models here.
def user_directory_path(instance, filename):
# file will be uploaded to MEDIA_ROOT/user_<id>/<filename>
return 'user_{0}/{1}/{2}'.format(instance.user.id, instance.file_category, filename)
def admin_directory_path(instance, filename):
# file will be uploaded to MEDIA_ROOT/admin/<filename>
return 'admin/{0}'.format(filename)
class VisionGalleryFiles(models.Model):
user = models.ForeignKey(Users, on_delete=models.CASCADE)
file = models.FileField(upload_to=user_directory_path)
file_category = models.CharField(max_length=20) # either 'aspirations', 'values' or 'video'
class AdminValuesImages(models.Model):
image = models.FileField(upload_to=admin_directory_path)
|
{"/accounts/extras_.py": ["/accounts/models.py"], "/accounts/migrations/0017_auto_20210809_2204.py": ["/accounts/models.py"], "/user_files/migrations/0003_auto_20210727_2335.py": ["/user_files/models.py"], "/accounts/migrations/0001_initial.py": ["/accounts/models.py"], "/characters/models.py": ["/accounts/models.py"], "/background_apps/functions.py": ["/accounts/models.py", "/characters/models.py"], "/main/views.py": ["/accounts/models.py", "/accounts/extras_.py", "/user_files/models.py", "/characters/models.py", "/behaviours/models.py", "/files_gallery/models.py"], "/api/views.py": ["/accounts/extras_.py", "/user_files/models.py", "/api/models.py"], "/user_files/views.py": ["/user_files/models.py"], "/characters/views.py": ["/characters/models.py", "/accounts/models.py"], "/accounts/tests.py": ["/accounts/models.py"], "/accounts/views.py": ["/accounts/models.py", "/accounts/extras_.py"], "/behaviours/models.py": ["/accounts/models.py"], "/behaviours/views.py": ["/accounts/models.py", "/behaviours/models.py"], "/files_gallery/models.py": ["/accounts/models.py"], "/behaviours/forms.py": ["/accounts/models.py", "/behaviours/models.py"], "/files_gallery/migrations/0001_initial.py": ["/files_gallery/models.py"], "/files_gallery/views.py": ["/files_gallery/models.py"], "/db_generated/views.py": ["/db_generated/models.py"], "/background/cron.py": ["/accounts/models.py", "/behaviours/models.py"], "/files_gallery/forms.py": ["/files_gallery/models.py"], "/db_generated/admin.py": ["/db_generated/models.py"], "/behaviours/admin.py": ["/behaviours/models.py"], "/files_gallery/admin.py": ["/files_gallery/models.py"], "/payment_system/views.py": ["/payment_system/models.py"]}
|
17,337,392
|
mindfirst-admin/mindfirst
|
refs/heads/main
|
/behaviours/forms.py
|
import json
from django.contrib import messages
from django.core import serializers
from django.http import JsonResponse, HttpResponseRedirect
from django.urls import reverse
from django.views.decorators.csrf import csrf_exempt
from accounts.models import Profile
from .models import *
def change_aspiration_name(request):
data = request.POST
aspiration_name = data['name']
if aspiration_name == '':
messages.error(request, 'Please set an aspiration name')
return HttpResponseRedirect(reverse('behaviours:behaviour_mapping'))
profile = Profile.objects.get(user=request.user)
profile.aspiration_name = aspiration_name
profile.save()
return JsonResponse('done', safe=False)
def select_behavior(request):
response_data = request.POST.get('data', None)
try:
data = json.loads(response_data)
except TypeError:
return HttpResponseRedirect(reverse('main:members_area'))
if data:
behaviors = BehaviourMapping.objects.filter(user=request.user).all()
for i in behaviors:
i.is_selected = False
i.save()
for i in data:
behavior = BehaviourMapping.objects.filter(user=request.user, id=i).first()
behavior.is_selected = True
behavior.save()
return JsonResponse('done', safe=False)
def delete_behaviour(request):
response_data = request.POST.get('data', None)
data = json.loads(response_data)
id_ = data['id']
behavior = BehaviourMapping.objects.filter(user=request.user, id=id_).first()
behavior.delete()
messages.success(request, 'Behavior deleted!')
return JsonResponse('done', safe=False)
def add_behaviour(request):
response_data = request.POST.get('data', None)
data = json.loads(response_data)
data = data[-1]
title = data['heading']
description = data['description']
behaviour_value = '+ve' if data['behavior'] == 1 else '-ve'
impact = data['impact']
difficulty = data['feasibility']
new_behavior = BehaviourMapping(user=request.user, title=title, description=description, value=behaviour_value,
impact=impact, difficulty=difficulty)
new_behavior.save()
messages.success(request, 'Behavior added!')
return JsonResponse('done', safe=False)
def update_behaviour(request):
response_data = request.POST.get('data', None)
data = json.loads(response_data)
id_ = data['id']
title = data['heading']
description = data['description']
print(data['behavior'])
behaviour_value = '+ve' if data['behavior'] == 1 else '-ve'
impact = data['impact']
difficulty = data['feasibility']
behavior = BehaviourMapping.objects.filter(user=request.user, id=id_).first()
behavior.title = title
behavior.description = description
behavior.value = behaviour_value
behavior.impact = impact
behavior.difficulty = difficulty
behavior.save()
messages.success(request, 'Behavior updated!')
return JsonResponse('done', safe=False)
@csrf_exempt
def get_behaviours(request):
db_data = BehaviourMapping.objects.filter(user=request.user).all()
serialized_data = serializers.serialize('json', [i for i in db_data])
return JsonResponse({'data': json.loads(serialized_data)}, status=200)
def design_positive_habit(request):
data = request.POST
id_ = int(data['behaviour_id'])
after_or_before = data['before_after']
frequency = data['frequency']
celebrate = data['celebrate']
act = data['act_']
number_of_times = data['number_of_times']
behaviour = BehaviourMapping.objects.filter(user=request.user, id=id_).first()
if any(values == '' for key, values in data.items() if key != 'csrfmiddlewaretoken'):
messages.error(request, 'All input fields need to be appropriately filled')
return HttpResponseRedirect(reverse('behaviours:habit_design'), behaviour_id=id_)
try:
habit_exists = DesignPositiveHabits.objects.get(behaviour=behaviour)
if habit_exists:
habit_exists.after_or_before = after_or_before
habit_exists.frequency = frequency
habit_exists.act = act
habit_exists.celebrate = celebrate
habit_exists.number_of_times = number_of_times
habit_exists.save()
except Exception as e:
new_habit = DesignPositiveHabits(behaviour=behaviour, after_or_before=after_or_before, frequency=frequency,
celebrate=celebrate, act=act, number_of_times=number_of_times)
new_habit.save()
messages.success(request, 'Good job designing your habit')
return HttpResponseRedirect(reverse('main:members_area'))
def design_negative_habits(request):
data = request.POST
id_ = int(data['behaviour_id'])
trigger = data['trigger']
frequency = data['frequency']
make_harder = data['make_harder']
make_less_obvious = data['make_less_obvious']
number_of_times = data['number_of_times']
behaviour = BehaviourMapping.objects.filter(user=request.user, id=id_).first()
if any(values == '' for key, values in data.items() if key != 'csrfmiddlewaretoken'):
messages.error(request, 'All input fields need to be appropriately filled')
return HttpResponseRedirect(reverse('main:habit_design'))
try:
habit_exists = DesignNegativeHabits.objects.get(behaviour=behaviour)
if habit_exists:
habit_exists.trigger = trigger
habit_exists.frequency = frequency
habit_exists.make_harder = make_harder
habit_exists.make_less_obvious = make_less_obvious
habit_exists.number_of_times = number_of_times
habit_exists.save()
except Exception as e:
new_habit = DesignNegativeHabits(behaviour=behaviour, make_less_obvious=make_less_obvious, frequency=frequency,
trigger=trigger, make_harder=make_harder, number_of_times=number_of_times)
new_habit.save()
messages.success(request, 'Good job designing your habit')
return HttpResponseRedirect(reverse('main:members_area'))
def record_todays_habit(request):
thumbs_up = request.POST.get('thumbsUp', None)
thumbs_down = request.POST.get('thumbsDown', None)
if thumbs_up:
behaviour = BehaviourMapping.objects.filter(user=request.user, id=thumbs_up).first()
behaviour.done_today = True
behaviour.thumbs_up_today += 1
behaviour.thumbs_up_this_week += 1
behaviour.save()
elif thumbs_down:
behaviour = BehaviourMapping.objects.filter(user=request.user, id=thumbs_down).first()
behaviour.done_today = False
behaviour.thumbs_down_today += 1
behaviour.thumbs_down_this_week += 1
behaviour.save()
return JsonResponse('done', safe=False)
def scale_habit(request):
response_data = request.POST.get('data', None)
data = json.loads(response_data)
id_ = data['id']
behavior = BehaviourMapping.objects.filter(user=request.user, id=id_).first()
behavior.is_scaled = True
behavior.save()
return JsonResponse('done', safe=False)
def update_beliefs(request):
data = request.POST.get('data')
old_belief = LimitingBeliefs.objects.filter(user=request.user).first()
if old_belief is not None:
old_belief.beliefs = data
old_belief.save()
else:
new_belief = LimitingBeliefs(user=request.user, beliefs=data)
new_belief.save()
return JsonResponse('done', safe=False)
def get_weekly_chart_data(request):
positive_habits_done = json.loads(request.user.profile.all_positive_habits_this_week)
negative_habits_done = json.loads(request.user.profile.all_scaled_habits_this_week)
scaled_habit = json.loads(request.user.profile.all_negative_habits_this_week)
try:
max_number = max([max(positive_habits_done), max(negative_habits_done), max(scaled_habit)])
except ValueError:
max_number = 10
if max_number < 10:
max_number = 10
return JsonResponse(data={
'positive': positive_habits_done,
'negative': negative_habits_done,
'scaled': scaled_habit,
'max_number': max_number
})
def get_trimonthly_chart_data(request):
positive_habits_done = json.loads(request.user.profile.all_positive_habits_in_twelve_weeks)
negative_habits_done = json.loads(request.user.profile.all_negative_habits_in_twelve_weeks)
scaled_habit = json.loads(request.user.profile.all_scaled_habits_in_twelve_weeks)
try:
max_number = max([max(positive_habits_done), max(negative_habits_done), max(scaled_habit)])
except ValueError:
max_number = 10
if max_number < 10:
max_number = 10
return JsonResponse(data={
'positive': positive_habits_done,
'negative': negative_habits_done,
'scaled': scaled_habit,
'max_number': max_number
})
|
{"/accounts/extras_.py": ["/accounts/models.py"], "/accounts/migrations/0017_auto_20210809_2204.py": ["/accounts/models.py"], "/user_files/migrations/0003_auto_20210727_2335.py": ["/user_files/models.py"], "/accounts/migrations/0001_initial.py": ["/accounts/models.py"], "/characters/models.py": ["/accounts/models.py"], "/background_apps/functions.py": ["/accounts/models.py", "/characters/models.py"], "/main/views.py": ["/accounts/models.py", "/accounts/extras_.py", "/user_files/models.py", "/characters/models.py", "/behaviours/models.py", "/files_gallery/models.py"], "/api/views.py": ["/accounts/extras_.py", "/user_files/models.py", "/api/models.py"], "/user_files/views.py": ["/user_files/models.py"], "/characters/views.py": ["/characters/models.py", "/accounts/models.py"], "/accounts/tests.py": ["/accounts/models.py"], "/accounts/views.py": ["/accounts/models.py", "/accounts/extras_.py"], "/behaviours/models.py": ["/accounts/models.py"], "/behaviours/views.py": ["/accounts/models.py", "/behaviours/models.py"], "/files_gallery/models.py": ["/accounts/models.py"], "/behaviours/forms.py": ["/accounts/models.py", "/behaviours/models.py"], "/files_gallery/migrations/0001_initial.py": ["/files_gallery/models.py"], "/files_gallery/views.py": ["/files_gallery/models.py"], "/db_generated/views.py": ["/db_generated/models.py"], "/background/cron.py": ["/accounts/models.py", "/behaviours/models.py"], "/files_gallery/forms.py": ["/files_gallery/models.py"], "/db_generated/admin.py": ["/db_generated/models.py"], "/behaviours/admin.py": ["/behaviours/models.py"], "/files_gallery/admin.py": ["/files_gallery/models.py"], "/payment_system/views.py": ["/payment_system/models.py"]}
|
17,337,393
|
mindfirst-admin/mindfirst
|
refs/heads/main
|
/payment_system/models.py
|
from django.db import models
# Create your models here.
class UserPurchases(models.Model):
purchase = models.CharField(max_length=255, default='')
stripe_customer_id = models.CharField(max_length=255, default='')
stripe_checkout_id = models.CharField(max_length=255, default='')
email = models.EmailField(max_length=255, default='')
date_paid = models.DateTimeField(auto_now_add=True)
|
{"/accounts/extras_.py": ["/accounts/models.py"], "/accounts/migrations/0017_auto_20210809_2204.py": ["/accounts/models.py"], "/user_files/migrations/0003_auto_20210727_2335.py": ["/user_files/models.py"], "/accounts/migrations/0001_initial.py": ["/accounts/models.py"], "/characters/models.py": ["/accounts/models.py"], "/background_apps/functions.py": ["/accounts/models.py", "/characters/models.py"], "/main/views.py": ["/accounts/models.py", "/accounts/extras_.py", "/user_files/models.py", "/characters/models.py", "/behaviours/models.py", "/files_gallery/models.py"], "/api/views.py": ["/accounts/extras_.py", "/user_files/models.py", "/api/models.py"], "/user_files/views.py": ["/user_files/models.py"], "/characters/views.py": ["/characters/models.py", "/accounts/models.py"], "/accounts/tests.py": ["/accounts/models.py"], "/accounts/views.py": ["/accounts/models.py", "/accounts/extras_.py"], "/behaviours/models.py": ["/accounts/models.py"], "/behaviours/views.py": ["/accounts/models.py", "/behaviours/models.py"], "/files_gallery/models.py": ["/accounts/models.py"], "/behaviours/forms.py": ["/accounts/models.py", "/behaviours/models.py"], "/files_gallery/migrations/0001_initial.py": ["/files_gallery/models.py"], "/files_gallery/views.py": ["/files_gallery/models.py"], "/db_generated/views.py": ["/db_generated/models.py"], "/background/cron.py": ["/accounts/models.py", "/behaviours/models.py"], "/files_gallery/forms.py": ["/files_gallery/models.py"], "/db_generated/admin.py": ["/db_generated/models.py"], "/behaviours/admin.py": ["/behaviours/models.py"], "/files_gallery/admin.py": ["/files_gallery/models.py"], "/payment_system/views.py": ["/payment_system/models.py"]}
|
17,337,394
|
mindfirst-admin/mindfirst
|
refs/heads/main
|
/main/views.py
|
from django.shortcuts import render, redirect
from accounts.models import Profile
from behaviours.models import LimitingBeliefs, BehaviourMapping
from files_gallery.models import VisionGalleryFiles
# Create your views here.
def homepage(request):
return render(request, 'main/homepage.html')
def our_products(request):
return render(request, 'main/products.html')
def product_details(request, product):
if product == '5-day-challenge':
main_header = '5-Day Challenge'
sub_header = 'Repeatable, Practical, Proven, Peer-Reviewed Science'
p1 = 'From cradle to the grave, your brain will process more events than there are stars in our universe. ' \
'As your body’s “central processing unit,” your brain is in charge of a staggering array of functions,' \
' from processing and perceiving stimuli to motor control and memory storage. ' \
'Habits and beliefs progr' \
'ammed into your mind over a lifetime of responding to experiences are stored in long-term memory, ' \
'and may cause you to resist new ways of doing things.'
p2 = 'From cradle to the grave, your brain will process more events than there are stars in our universe. ' \
'As your body’s “central processing unit,” your brain is in charge of a staggering array of functions,' \
' from processing and perceiving stimuli to motor control and memory storage. Habits and beliefs progr' \
'ammed into your mind over a lifetime of responding to experiences are stored in long-term memory, ' \
'and may cause you to resist new ways of doing things.'
p3 = 'From cradle to the grave, your brain will process more events than there are stars in our universe. ' \
'As your body’s “central processing unit,” your brain is in charge of a staggering array of functions,' \
' from processing and perceiving stimuli to motor control and memory storage. Habits and beliefs progr' \
'ammed into your mind over a lifetime of responding to experiences are stored in long-term memory, ' \
'and may cause you to resist new ways of doing things.'
link = '/accounts/5-day-challenge'
image = 'main/assets/landing_image.jpg'
elif product == 'book':
main_header = 'Progress Equals Happiness'
sub_header = 'Repeatable, Practical, Proven, Peer-Reviewed Science'
p1 = 'From cradle to the grave, your brain will process more events than there are stars in our universe. ' \
'As your body’s “central processing unit,” your brain is in charge of a staggering array of functions,' \
' from processing and perceiving stimuli to motor control and memory storage. Habits and beliefs progr' \
'ammed into your mind over a lifetime of responding to experiences are stored in long-term memory, ' \
'and may cause you to resist new ways of doing things.'
p2 = 'From cradle to the grave, your brain will process more events than there are stars in our universe. ' \
'As your body’s “central processing unit,” your brain is in charge of a staggering array of functions,' \
' from processing and perceiving stimuli to motor control and memory storage. Habits and beliefs progr' \
'ammed into your mind over a lifetime of responding to experiences are stored in long-term memory, ' \
'and may cause you to resist new ways of doing things.'
p3 = 'From cradle to the grave, your brain will process more events than there are stars in our universe. ' \
'As your body’s “central processing unit,” your brain is in charge of a staggering array of functions,' \
' from processing and perceiving stimuli to motor control and memory storage. Habits and beliefs progr' \
'ammed into your mind over a lifetime of responding to experiences are stored in long-term memory, ' \
'and may cause you to resist new ways of doing things.'
link = '/payment/~book'
image = 'main/assets/landing_image.jpg'
elif product == 'workbook':
main_header = 'Our Workbook'
sub_header = 'Repeatable, Practical, Proven, Peer-Reviewed Science'
p1 = 'From cradle to the grave, your brain will process more events than there are stars in our universe. ' \
'As your body’s “central processing unit,” your brain is in charge of a staggering array of functions,' \
' from processing and perceiving stimuli to motor control and memory storage. Habits and beliefs progr' \
'ammed into your mind over a lifetime of responding to experiences are stored in long-term memory, ' \
'and may cause you to resist new ways of doing things.'
p2 = 'From cradle to the grave, your brain will process more events than there are stars in our universe. ' \
'As your body’s “central processing unit,” your brain is in charge of a staggering array of functions,' \
' from processing and perceiving stimuli to motor control and memory storage. Habits and beliefs progr' \
'ammed into your mind over a lifetime of responding to experiences are stored in long-term memory, ' \
'and may cause you to resist new ways of doing things.'
p3 = 'From cradle to the grave, your brain will process more events than there are stars in our universe. ' \
'As your body’s “central processing unit,” your brain is in charge of a staggering array of functions,' \
' from processing and perceiving stimuli to motor control and memory storage. Habits and beliefs progr' \
'ammed into your mind over a lifetime of responding to experiences are stored in long-term memory, ' \
'and may cause you to resist new ways of doing things.'
link = '/payment/~workbook'
image = 'main/assets/landing_image.jpg'
elif product == 'membership':
main_header = 'Mind First Membership'
sub_header = 'Repeatable, Practical, Proven, Peer-Reviewed Science'
p1 = 'From cradle to the grave, your brain will process more events than there are stars in our universe. ' \
'As your body’s “central processing unit,” your brain is in charge of a staggering array of functions,' \
' from processing and perceiving stimuli to motor control and memory storage. Habits and beliefs progr' \
'ammed into your mind over a lifetime of responding to experiences are stored in long-term memory, ' \
'and may cause you to resist new ways of doing things.'
p2 = 'From cradle to the grave, your brain will process more events than there are stars in our universe. ' \
'As your body’s “central processing unit,” your brain is in charge of a staggering array of functions,' \
' from processing and perceiving stimuli to motor control and memory storage. Habits and beliefs progr' \
'ammed into your mind over a lifetime of responding to experiences are stored in long-term memory, ' \
'and may cause you to resist new ways of doing things.'
p3 = 'From cradle to the grave, your brain will process more events than there are stars in our universe. ' \
'As your body’s “central processing unit,” your brain is in charge of a staggering array of functions,' \
' from processing and perceiving stimuli to motor control and memory storage. Habits and beliefs progr' \
'ammed into your mind over a lifetime of responding to experiences are stored in long-term memory, ' \
'and may cause you to resist new ways of doing things.'
link = '/payment/~membership'
image = 'main/assets/landing_image.jpg'
else:
return render(request, 'main/404.html')
return render(request, 'main/product_details.html', {
'main_header': main_header,
'sub_header': sub_header,
'p1': p1,
'p2': p2,
'p3': p3,
'image': image,
'link': link,
})
def members_area(request):
if request.user.is_authenticated:
aspiration_files = VisionGalleryFiles.objects.filter(user=request.user, file_category='aspirations').first()
video_file = VisionGalleryFiles.objects.filter(user=request.user, file_category='video').first()
profile = Profile.objects.get(user=request.user)
if not aspiration_files:
aspiration_image = 'main/assets/landing_image.jpg'
else:
# add file
aspiration_image = 'media/' + str(aspiration_files)
if not video_file:
has_video = False
else:
has_video = True
aspiration_name = profile.aspiration_name
behaviours_list = BehaviourMapping.objects.filter(user=request.user, is_selected=True).all()
content = {
'vision_gallery_video': video_file,
'has_video': has_video,
'profile': profile,
'aspiration_image': aspiration_image,
'aspiration_name': aspiration_name,
'behaviours_list': behaviours_list,
}
return render(request, 'main/members_area.html', content)
return redirect('accounts:sign_in_to_members_area')
def limiting_beliefs(request):
if request.user.is_authenticated:
beliefs = LimitingBeliefs.objects.filter(user=request.user).first()
if beliefs is not None:
data = beliefs.beliefs
else:
data = ['12 Love']
nums = [5, 4, 3, 2, 2]
words = ('Liebe,ፍቅር,Lufu,حب,Aimor,Amor,Heyran,ভালোবাসা,Каханне,Любоў,Любов,བརྩེ་དུང་།,' +
'Ljubav,Karantez,Юрату,Láska,Amore,Cariad,Kærlighed,Armastus,Αγάπη,Amo,Amol,Maitasun,' +
'عشق,Pyar,Amour,Leafde,Gràdh,愛,爱,પ્રેમ,사랑,Սեր,Ihunanya,Cinta,ᑕᑯᑦᓱᒍᓱᑉᐳᖅ,Ást,אהבה,' +
'ಪ್ರೀತಿ,სიყვარული,Махаббат,Pendo,Сүйүү,Mīlestība,Meilė,Leefde,Bolingo,Szerelem,' +
'Љубов,സ്നേഹം,Imħabba,प्रेम,Ái,Хайр,အချစ်,Tlazohtiliztli,Liefde,माया,मतिना,' +
'Kjærlighet,Kjærleik,ପ୍ରେମ,Sevgi,ਪਿਆਰ,پیار,Miłość,Leevde,Dragoste,' +
'Khuyay,Любовь,Таптал,Dashuria,Amuri,ආදරය,Ljubezen,Jaceyl,خۆشەویستی,Љубав,Rakkaus,' +
'Kärlek,Pag-ibig,காதல்,ప్రేమ,ความรัก,Ишқ,Aşk,محبت,Tình yêu,Higugma,ליבע').split(',')
for num in nums:
for word in words:
data.append(str(num) + ' ' + str(word))
data = '\n'.join(data)
return render(request, 'main/limiting_beliefs.html', {'data': data})
return redirect('accounts:sign_in_to_members_area')
|
{"/accounts/extras_.py": ["/accounts/models.py"], "/accounts/migrations/0017_auto_20210809_2204.py": ["/accounts/models.py"], "/user_files/migrations/0003_auto_20210727_2335.py": ["/user_files/models.py"], "/accounts/migrations/0001_initial.py": ["/accounts/models.py"], "/characters/models.py": ["/accounts/models.py"], "/background_apps/functions.py": ["/accounts/models.py", "/characters/models.py"], "/main/views.py": ["/accounts/models.py", "/accounts/extras_.py", "/user_files/models.py", "/characters/models.py", "/behaviours/models.py", "/files_gallery/models.py"], "/api/views.py": ["/accounts/extras_.py", "/user_files/models.py", "/api/models.py"], "/user_files/views.py": ["/user_files/models.py"], "/characters/views.py": ["/characters/models.py", "/accounts/models.py"], "/accounts/tests.py": ["/accounts/models.py"], "/accounts/views.py": ["/accounts/models.py", "/accounts/extras_.py"], "/behaviours/models.py": ["/accounts/models.py"], "/behaviours/views.py": ["/accounts/models.py", "/behaviours/models.py"], "/files_gallery/models.py": ["/accounts/models.py"], "/behaviours/forms.py": ["/accounts/models.py", "/behaviours/models.py"], "/files_gallery/migrations/0001_initial.py": ["/files_gallery/models.py"], "/files_gallery/views.py": ["/files_gallery/models.py"], "/db_generated/views.py": ["/db_generated/models.py"], "/background/cron.py": ["/accounts/models.py", "/behaviours/models.py"], "/files_gallery/forms.py": ["/files_gallery/models.py"], "/db_generated/admin.py": ["/db_generated/models.py"], "/behaviours/admin.py": ["/behaviours/models.py"], "/files_gallery/admin.py": ["/files_gallery/models.py"], "/payment_system/views.py": ["/payment_system/models.py"]}
|
17,337,395
|
mindfirst-admin/mindfirst
|
refs/heads/main
|
/payment_system/migrations/0001_initial.py
|
# Generated by Django 3.2.5 on 2021-10-15 23:09
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='UserPurchases',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('purchase', models.CharField(default='', max_length=255)),
('stripe_customer_id', models.CharField(default='', max_length=255)),
('stripe_checkout_id', models.CharField(default='', max_length=255)),
('email', models.EmailField(default='', max_length=255)),
('date_paid', models.DateTimeField(auto_now_add=True)),
],
),
]
|
{"/accounts/extras_.py": ["/accounts/models.py"], "/accounts/migrations/0017_auto_20210809_2204.py": ["/accounts/models.py"], "/user_files/migrations/0003_auto_20210727_2335.py": ["/user_files/models.py"], "/accounts/migrations/0001_initial.py": ["/accounts/models.py"], "/characters/models.py": ["/accounts/models.py"], "/background_apps/functions.py": ["/accounts/models.py", "/characters/models.py"], "/main/views.py": ["/accounts/models.py", "/accounts/extras_.py", "/user_files/models.py", "/characters/models.py", "/behaviours/models.py", "/files_gallery/models.py"], "/api/views.py": ["/accounts/extras_.py", "/user_files/models.py", "/api/models.py"], "/user_files/views.py": ["/user_files/models.py"], "/characters/views.py": ["/characters/models.py", "/accounts/models.py"], "/accounts/tests.py": ["/accounts/models.py"], "/accounts/views.py": ["/accounts/models.py", "/accounts/extras_.py"], "/behaviours/models.py": ["/accounts/models.py"], "/behaviours/views.py": ["/accounts/models.py", "/behaviours/models.py"], "/files_gallery/models.py": ["/accounts/models.py"], "/behaviours/forms.py": ["/accounts/models.py", "/behaviours/models.py"], "/files_gallery/migrations/0001_initial.py": ["/files_gallery/models.py"], "/files_gallery/views.py": ["/files_gallery/models.py"], "/db_generated/views.py": ["/db_generated/models.py"], "/background/cron.py": ["/accounts/models.py", "/behaviours/models.py"], "/files_gallery/forms.py": ["/files_gallery/models.py"], "/db_generated/admin.py": ["/db_generated/models.py"], "/behaviours/admin.py": ["/behaviours/models.py"], "/files_gallery/admin.py": ["/files_gallery/models.py"], "/payment_system/views.py": ["/payment_system/models.py"]}
|
17,337,396
|
mindfirst-admin/mindfirst
|
refs/heads/main
|
/behaviours/migrations/0001_initial.py
|
# Generated by Django 3.2.5 on 2021-10-15 23:09
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
name='BehaviourMapping',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('title', models.CharField(default='', max_length=255)),
('description', models.CharField(blank=True, default='', max_length=1024, null=True)),
('value', models.CharField(default='+ve', max_length=3)),
('impact', models.IntegerField(default=0)),
('difficulty', models.IntegerField(default=0)),
('is_scaled', models.BooleanField(default=False)),
('is_selected', models.BooleanField(default=False)),
('done_today', models.BooleanField(default=False)),
('thumbs_up_today', models.IntegerField(default=0)),
('thumbs_down_today', models.IntegerField(default=0)),
('thumbs_up_this_week', models.IntegerField(default=0)),
('thumbs_down_this_week', models.IntegerField(default=0)),
('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
],
),
migrations.CreateModel(
name='LimitingBeliefs',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('beliefs', models.CharField(max_length=10000)),
('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
],
),
migrations.CreateModel(
name='DesignPositiveHabits',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('after_or_before', models.CharField(default='', max_length=255)),
('act', models.CharField(default='', max_length=255)),
('celebrate', models.CharField(default='', max_length=255)),
('frequency', models.CharField(default='', max_length=255)),
('number_of_times', models.CharField(default=0, max_length=2)),
('behaviour', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, to='behaviours.behaviourmapping')),
],
),
migrations.CreateModel(
name='DesignNegativeHabits',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('trigger', models.CharField(default='', max_length=255)),
('make_less_obvious', models.CharField(default='', max_length=255)),
('make_harder', models.CharField(default='', max_length=255)),
('frequency', models.CharField(default='', max_length=255)),
('number_of_times', models.CharField(default=0, max_length=2)),
('behaviour', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, to='behaviours.behaviourmapping')),
],
),
]
|
{"/accounts/extras_.py": ["/accounts/models.py"], "/accounts/migrations/0017_auto_20210809_2204.py": ["/accounts/models.py"], "/user_files/migrations/0003_auto_20210727_2335.py": ["/user_files/models.py"], "/accounts/migrations/0001_initial.py": ["/accounts/models.py"], "/characters/models.py": ["/accounts/models.py"], "/background_apps/functions.py": ["/accounts/models.py", "/characters/models.py"], "/main/views.py": ["/accounts/models.py", "/accounts/extras_.py", "/user_files/models.py", "/characters/models.py", "/behaviours/models.py", "/files_gallery/models.py"], "/api/views.py": ["/accounts/extras_.py", "/user_files/models.py", "/api/models.py"], "/user_files/views.py": ["/user_files/models.py"], "/characters/views.py": ["/characters/models.py", "/accounts/models.py"], "/accounts/tests.py": ["/accounts/models.py"], "/accounts/views.py": ["/accounts/models.py", "/accounts/extras_.py"], "/behaviours/models.py": ["/accounts/models.py"], "/behaviours/views.py": ["/accounts/models.py", "/behaviours/models.py"], "/files_gallery/models.py": ["/accounts/models.py"], "/behaviours/forms.py": ["/accounts/models.py", "/behaviours/models.py"], "/files_gallery/migrations/0001_initial.py": ["/files_gallery/models.py"], "/files_gallery/views.py": ["/files_gallery/models.py"], "/db_generated/views.py": ["/db_generated/models.py"], "/background/cron.py": ["/accounts/models.py", "/behaviours/models.py"], "/files_gallery/forms.py": ["/files_gallery/models.py"], "/db_generated/admin.py": ["/db_generated/models.py"], "/behaviours/admin.py": ["/behaviours/models.py"], "/files_gallery/admin.py": ["/files_gallery/models.py"], "/payment_system/views.py": ["/payment_system/models.py"]}
|
17,337,397
|
mindfirst-admin/mindfirst
|
refs/heads/main
|
/db_generated/models.py
|
from django.db import models
# Create your models here.
class DayModel(models.Model):
day_id = models.IntegerField(default=0)
title = models.CharField(max_length=255, default='')
file = models.FileField(upload_to='admin/days/video_images')
description = models.CharField(max_length=1024, default='')
def __str__(self):
return self.title
class FiveDayModel(models.Model):
day_id = models.IntegerField(default=0)
title = models.CharField(max_length=255, default='')
file = models.FileField(upload_to='admin/5days/video_images')
description = models.CharField(max_length=1024, default='')
def __str__(self):
return self.title
class WeekModel(models.Model):
week_id = models.IntegerField(default=0)
title = models.CharField(max_length=255, default='')
file = models.FileField(upload_to='admin/weeks/video_images')
description = models.CharField(max_length=1024, default='')
def __str__(self):
return self.title
class MindWorkshopModel(models.Model):
week_id = models.IntegerField(default=0)
title = models.CharField(max_length=255, default='')
file = models.FileField(upload_to='admin/mind_workshop/video_images')
description = models.CharField(max_length=1024, default='')
def __str__(self):
return self.title
class ResourcesModel(models.Model):
day = models.ForeignKey(DayModel, on_delete=models.CASCADE, default=None, blank=True, null=True)
five_day = models.ForeignKey(FiveDayModel, on_delete=models.CASCADE, default=None, blank=True, null=True)
week = models.ForeignKey(WeekModel, on_delete=models.CASCADE, default=None, blank=True, null=True)
mind_workshop = models.ForeignKey(MindWorkshopModel, on_delete=models.CASCADE, default=None, blank=True, null=True)
file = models.FileField(upload_to='admin/data/folder')
file_name = models.CharField(max_length=255, default='')
def __str__(self):
return self.file_name
class WhatYoullLearnModel(models.Model):
day = models.ForeignKey(DayModel, on_delete=models.CASCADE, default=None, blank=True, null=True)
five_day = models.ForeignKey(FiveDayModel, on_delete=models.CASCADE, default=None, blank=True, null=True)
week = models.ForeignKey(WeekModel, on_delete=models.CASCADE, default=None, blank=True, null=True)
mind_workshop = models.ForeignKey(MindWorkshopModel, on_delete=models.CASCADE, default=None, blank=True, null=True)
image = models.FileField(upload_to='admin/what_you\'ll_learn/', blank=True, null=True)
video = models.FileField(upload_to='admin/what_you\'ll_learn/', blank=True, null=True)
text = models.CharField(max_length=1024, default='', blank=True, null=True)
|
{"/accounts/extras_.py": ["/accounts/models.py"], "/accounts/migrations/0017_auto_20210809_2204.py": ["/accounts/models.py"], "/user_files/migrations/0003_auto_20210727_2335.py": ["/user_files/models.py"], "/accounts/migrations/0001_initial.py": ["/accounts/models.py"], "/characters/models.py": ["/accounts/models.py"], "/background_apps/functions.py": ["/accounts/models.py", "/characters/models.py"], "/main/views.py": ["/accounts/models.py", "/accounts/extras_.py", "/user_files/models.py", "/characters/models.py", "/behaviours/models.py", "/files_gallery/models.py"], "/api/views.py": ["/accounts/extras_.py", "/user_files/models.py", "/api/models.py"], "/user_files/views.py": ["/user_files/models.py"], "/characters/views.py": ["/characters/models.py", "/accounts/models.py"], "/accounts/tests.py": ["/accounts/models.py"], "/accounts/views.py": ["/accounts/models.py", "/accounts/extras_.py"], "/behaviours/models.py": ["/accounts/models.py"], "/behaviours/views.py": ["/accounts/models.py", "/behaviours/models.py"], "/files_gallery/models.py": ["/accounts/models.py"], "/behaviours/forms.py": ["/accounts/models.py", "/behaviours/models.py"], "/files_gallery/migrations/0001_initial.py": ["/files_gallery/models.py"], "/files_gallery/views.py": ["/files_gallery/models.py"], "/db_generated/views.py": ["/db_generated/models.py"], "/background/cron.py": ["/accounts/models.py", "/behaviours/models.py"], "/files_gallery/forms.py": ["/files_gallery/models.py"], "/db_generated/admin.py": ["/db_generated/models.py"], "/behaviours/admin.py": ["/behaviours/models.py"], "/files_gallery/admin.py": ["/files_gallery/models.py"], "/payment_system/views.py": ["/payment_system/models.py"]}
|
17,337,398
|
mindfirst-admin/mindfirst
|
refs/heads/main
|
/files_gallery/migrations/0001_initial.py
|
# Generated by Django 3.2.5 on 2021-10-15 23:09
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import files_gallery.models
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
name='AdminValuesImages',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('image', models.FileField(upload_to=files_gallery.models.admin_directory_path)),
],
),
migrations.CreateModel(
name='VisionGalleryFiles',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('file', models.FileField(upload_to=files_gallery.models.user_directory_path)),
('file_category', models.CharField(max_length=20)),
('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
],
),
]
|
{"/accounts/extras_.py": ["/accounts/models.py"], "/accounts/migrations/0017_auto_20210809_2204.py": ["/accounts/models.py"], "/user_files/migrations/0003_auto_20210727_2335.py": ["/user_files/models.py"], "/accounts/migrations/0001_initial.py": ["/accounts/models.py"], "/characters/models.py": ["/accounts/models.py"], "/background_apps/functions.py": ["/accounts/models.py", "/characters/models.py"], "/main/views.py": ["/accounts/models.py", "/accounts/extras_.py", "/user_files/models.py", "/characters/models.py", "/behaviours/models.py", "/files_gallery/models.py"], "/api/views.py": ["/accounts/extras_.py", "/user_files/models.py", "/api/models.py"], "/user_files/views.py": ["/user_files/models.py"], "/characters/views.py": ["/characters/models.py", "/accounts/models.py"], "/accounts/tests.py": ["/accounts/models.py"], "/accounts/views.py": ["/accounts/models.py", "/accounts/extras_.py"], "/behaviours/models.py": ["/accounts/models.py"], "/behaviours/views.py": ["/accounts/models.py", "/behaviours/models.py"], "/files_gallery/models.py": ["/accounts/models.py"], "/behaviours/forms.py": ["/accounts/models.py", "/behaviours/models.py"], "/files_gallery/migrations/0001_initial.py": ["/files_gallery/models.py"], "/files_gallery/views.py": ["/files_gallery/models.py"], "/db_generated/views.py": ["/db_generated/models.py"], "/background/cron.py": ["/accounts/models.py", "/behaviours/models.py"], "/files_gallery/forms.py": ["/files_gallery/models.py"], "/db_generated/admin.py": ["/db_generated/models.py"], "/behaviours/admin.py": ["/behaviours/models.py"], "/files_gallery/admin.py": ["/files_gallery/models.py"], "/payment_system/views.py": ["/payment_system/models.py"]}
|
17,337,399
|
mindfirst-admin/mindfirst
|
refs/heads/main
|
/payment_system/urls.py
|
from django.urls import path
from . import views
app_name = "payments"
urlpatterns = [
path('~<str:product>/', views.payment_pages, name="payment_pages"),
path('membership_monthly/', views.membership_monthly, name="membership_monthly"),
path('membership_annually/', views.membership_annually, name="membership_annually"),
path('ebook_purchase/', views.ebook_purchase, name="ebook_purchase"),
path('audiobook_purchase/', views.audiobook_purchase, name="audiobook_purchase"),
path('audiobook_n_ebook_purchase/', views.audiobook_n_ebook_purchase, name="audiobook_n_ebook_purchase"),
path('workbook_purchase/', views.workbook_purchase, name="workbook_purchase"),
path('payment-unsuccessful/', views.payment_unsuccessful, name="payment_unsuccessful"),
path('thank-you/', views.thank_you, name="thank_you"),
]
|
{"/accounts/extras_.py": ["/accounts/models.py"], "/accounts/migrations/0017_auto_20210809_2204.py": ["/accounts/models.py"], "/user_files/migrations/0003_auto_20210727_2335.py": ["/user_files/models.py"], "/accounts/migrations/0001_initial.py": ["/accounts/models.py"], "/characters/models.py": ["/accounts/models.py"], "/background_apps/functions.py": ["/accounts/models.py", "/characters/models.py"], "/main/views.py": ["/accounts/models.py", "/accounts/extras_.py", "/user_files/models.py", "/characters/models.py", "/behaviours/models.py", "/files_gallery/models.py"], "/api/views.py": ["/accounts/extras_.py", "/user_files/models.py", "/api/models.py"], "/user_files/views.py": ["/user_files/models.py"], "/characters/views.py": ["/characters/models.py", "/accounts/models.py"], "/accounts/tests.py": ["/accounts/models.py"], "/accounts/views.py": ["/accounts/models.py", "/accounts/extras_.py"], "/behaviours/models.py": ["/accounts/models.py"], "/behaviours/views.py": ["/accounts/models.py", "/behaviours/models.py"], "/files_gallery/models.py": ["/accounts/models.py"], "/behaviours/forms.py": ["/accounts/models.py", "/behaviours/models.py"], "/files_gallery/migrations/0001_initial.py": ["/files_gallery/models.py"], "/files_gallery/views.py": ["/files_gallery/models.py"], "/db_generated/views.py": ["/db_generated/models.py"], "/background/cron.py": ["/accounts/models.py", "/behaviours/models.py"], "/files_gallery/forms.py": ["/files_gallery/models.py"], "/db_generated/admin.py": ["/db_generated/models.py"], "/behaviours/admin.py": ["/behaviours/models.py"], "/files_gallery/admin.py": ["/files_gallery/models.py"], "/payment_system/views.py": ["/payment_system/models.py"]}
|
17,337,400
|
mindfirst-admin/mindfirst
|
refs/heads/main
|
/files_gallery/views.py
|
import os
from django.shortcuts import render, redirect
from .models import *
# Create your views here.
def vision_gallery(request):
if request.user.is_authenticated:
aspiration_images = VisionGalleryFiles.objects.filter(user=request.user, file_category='aspirations').all()
values_images = VisionGalleryFiles.objects.filter(user=request.user, file_category='values').all()
content = {
'aspiration_images': aspiration_images,
'values_images': values_images
}
return render(request, 'user_files/vision_gallery.html', content)
else:
return redirect('accounts:sign_in_to_members_area')
def edit_aspirations(request):
if request.user.is_authenticated:
aspiration_files = VisionGalleryFiles.objects.filter(user=request.user, file_category='aspirations').all()
return render(request, 'user_files/edit_aspirations.html', {'aspirations': aspiration_files})
else:
return redirect('accounts:sign_in_to_members_area')
def edit_values(response):
if response.user.is_authenticated:
user_value_files = [str(i.file) for i in
VisionGalleryFiles.objects.filter(user=response.user, file_category='values').all()]
admin_value_files = [str(i.image) for i in AdminValuesImages.objects.all()]
user_value_files_stripped = [os.path.basename(i) for i in user_value_files] # getting the file names
values_image_files = []
for file in admin_value_files:
file_name = os.path.basename(file)
if file_name in user_value_files_stripped:
image_meta = {
'url': file,
'check': True,
'name': file_name
}
else:
image_meta = {
'url': file,
'check': False,
'name': file_name
}
values_image_files.append(image_meta)
return render(response, 'user_files/edit_values.html', {'images': values_image_files})
else:
return redirect('accounts:sign_in_to_members_area')
def watch_video(response):
if response.user.is_authenticated:
video_file = VisionGalleryFiles.objects.filter(user=response.user, file_category='video').first()
return render(response, 'user_files/watch_video.html', {'video_file': video_file})
else:
return redirect('accounts:sign_in_to_members_area')
def processing_video(response):
if response.user.is_authenticated:
return render(response, 'user_files/processing_video.html', {})
else:
return redirect('accounts:sign_in_to_members_area')
|
{"/accounts/extras_.py": ["/accounts/models.py"], "/accounts/migrations/0017_auto_20210809_2204.py": ["/accounts/models.py"], "/user_files/migrations/0003_auto_20210727_2335.py": ["/user_files/models.py"], "/accounts/migrations/0001_initial.py": ["/accounts/models.py"], "/characters/models.py": ["/accounts/models.py"], "/background_apps/functions.py": ["/accounts/models.py", "/characters/models.py"], "/main/views.py": ["/accounts/models.py", "/accounts/extras_.py", "/user_files/models.py", "/characters/models.py", "/behaviours/models.py", "/files_gallery/models.py"], "/api/views.py": ["/accounts/extras_.py", "/user_files/models.py", "/api/models.py"], "/user_files/views.py": ["/user_files/models.py"], "/characters/views.py": ["/characters/models.py", "/accounts/models.py"], "/accounts/tests.py": ["/accounts/models.py"], "/accounts/views.py": ["/accounts/models.py", "/accounts/extras_.py"], "/behaviours/models.py": ["/accounts/models.py"], "/behaviours/views.py": ["/accounts/models.py", "/behaviours/models.py"], "/files_gallery/models.py": ["/accounts/models.py"], "/behaviours/forms.py": ["/accounts/models.py", "/behaviours/models.py"], "/files_gallery/migrations/0001_initial.py": ["/files_gallery/models.py"], "/files_gallery/views.py": ["/files_gallery/models.py"], "/db_generated/views.py": ["/db_generated/models.py"], "/background/cron.py": ["/accounts/models.py", "/behaviours/models.py"], "/files_gallery/forms.py": ["/files_gallery/models.py"], "/db_generated/admin.py": ["/db_generated/models.py"], "/behaviours/admin.py": ["/behaviours/models.py"], "/files_gallery/admin.py": ["/files_gallery/models.py"], "/payment_system/views.py": ["/payment_system/models.py"]}
|
17,337,401
|
mindfirst-admin/mindfirst
|
refs/heads/main
|
/accounts/models.py
|
from django.db import models
from django.contrib.auth.models import (
AbstractBaseUser, BaseUserManager
)
import string
import random
def generate_user_token():
length = 36
small_letters = string.ascii_lowercase
numbers = string.digits
code_ = small_letters + numbers
while True:
token = ''.join(random.choices(code_, k=length)) # generates random code for alphabets
if Profile.objects.filter(user_token=token).count() == 0:
break
return token
def create_password():
length = 16
small_letters = string.ascii_lowercase
numbers = string.digits
p_wrd_list = small_letters + numbers
while True:
p_wrd = ''.join(random.choices(p_wrd_list, k=length))
if Users.objects.filter(password=p_wrd).count() == 0:
break
return p_wrd
class UserManager(BaseUserManager):
def create_user(self, email, password=None, phone_number=None, is_staff=False, is_active=True, is_admin=False):
if not email:
raise ValueError("All the fields haven't been adequately filled")
if not password:
raise ValueError("All the fields haven't been adequately filled - password")
user_obj = self.model(
email=self.normalize_email(email),
)
user_obj.set_password(password)
user_obj.staff = is_staff
user_obj.active = is_active
user_obj.admin = is_admin
user_obj.phone_number = phone_number
user_obj.save(using=self._db)
return user_obj
def create_staffuser(self, email, password=None, phone_number=None):
user = self.create_user(
email,
password=password,
phone_number=phone_number,
)
user.staff = True
user.save(using=self._db)
return user
def create_superuser(self, email, password=None, phone_number=None):
user = self.create_user(
email,
password=password,
phone_number=phone_number,
)
user.staff = True
user.admin = True
user.save(using=self._db)
return user
# Create your user models here.
class Users(AbstractBaseUser):
email = models.EmailField(max_length=255, unique=True)
phone_number = models.IntegerField()
# django defaults
is_active = models.BooleanField(default=True)
staff = models.BooleanField(default=False)
admin = models.BooleanField(default=False)
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['phone_number']
objects = UserManager()
def __str__(self):
return self.email
# django default functions
def get_full_name(self):
return self.email
def get_short_name(self):
return self.email
def has_perm(self, perm, obj=None):
return True
def has_module_perms(self, app_label):
return True
@property
def is_staff(self):
return self.staff
@property
def is_admin(self):
return self.admin
class Profile(models.Model):
user = models.OneToOneField(Users, on_delete=models.CASCADE, primary_key=True)
user_token = models.CharField(max_length=36, default=generate_user_token)
aspiration_name = models.CharField(max_length=255, default="Aspiration")
is_subscribed = models.BooleanField(null=False, default=False)
customer_id = models.CharField(max_length=50, default='')
scaled_habits = models.IntegerField(default=0)
yellow_habits = models.IntegerField(default=0)
red_habits = models.IntegerField(default=0)
green_habits = models.IntegerField(default=0)
negative_behaviors_done_this_week = models.CharField(max_length=10, default='0/0')
positive_behaviors_done_this_week = models.CharField(max_length=10, default='0/0')
all_positive_habits_this_week = models.CharField(max_length=20, default='[]')
all_scaled_habits_this_week = models.CharField(max_length=20, default='[]')
all_negative_habits_this_week = models.CharField(max_length=20, default='[]')
all_positive_habits_in_twelve_weeks = models.CharField(max_length=40, default='[]')
all_scaled_habits_in_twelve_weeks = models.CharField(max_length=40, default='[]')
all_negative_habits_in_twelve_weeks = models.CharField(max_length=40, default='[]')
def change_token(self):
self.user_token = generate_user_token()
def __str__(self):
return self.user.email
class FiveDayWaitingList(models.Model):
email = models.EmailField(max_length=255, unique=True)
first_name = models.CharField(max_length=255, unique=True)
last_name = models.CharField(max_length=255, unique=True)
def __str__(self):
return self.email
class MembershipWaitingList(models.Model):
email = models.EmailField(max_length=255, unique=True)
first_name = models.CharField(max_length=255, unique=True)
last_name = models.CharField(max_length=255, unique=True)
def __str__(self):
return self.email
|
{"/accounts/extras_.py": ["/accounts/models.py"], "/accounts/migrations/0017_auto_20210809_2204.py": ["/accounts/models.py"], "/user_files/migrations/0003_auto_20210727_2335.py": ["/user_files/models.py"], "/accounts/migrations/0001_initial.py": ["/accounts/models.py"], "/characters/models.py": ["/accounts/models.py"], "/background_apps/functions.py": ["/accounts/models.py", "/characters/models.py"], "/main/views.py": ["/accounts/models.py", "/accounts/extras_.py", "/user_files/models.py", "/characters/models.py", "/behaviours/models.py", "/files_gallery/models.py"], "/api/views.py": ["/accounts/extras_.py", "/user_files/models.py", "/api/models.py"], "/user_files/views.py": ["/user_files/models.py"], "/characters/views.py": ["/characters/models.py", "/accounts/models.py"], "/accounts/tests.py": ["/accounts/models.py"], "/accounts/views.py": ["/accounts/models.py", "/accounts/extras_.py"], "/behaviours/models.py": ["/accounts/models.py"], "/behaviours/views.py": ["/accounts/models.py", "/behaviours/models.py"], "/files_gallery/models.py": ["/accounts/models.py"], "/behaviours/forms.py": ["/accounts/models.py", "/behaviours/models.py"], "/files_gallery/migrations/0001_initial.py": ["/files_gallery/models.py"], "/files_gallery/views.py": ["/files_gallery/models.py"], "/db_generated/views.py": ["/db_generated/models.py"], "/background/cron.py": ["/accounts/models.py", "/behaviours/models.py"], "/files_gallery/forms.py": ["/files_gallery/models.py"], "/db_generated/admin.py": ["/db_generated/models.py"], "/behaviours/admin.py": ["/behaviours/models.py"], "/files_gallery/admin.py": ["/files_gallery/models.py"], "/payment_system/views.py": ["/payment_system/models.py"]}
|
17,337,402
|
mindfirst-admin/mindfirst
|
refs/heads/main
|
/db_generated/views.py
|
import os
from django.shortcuts import render, redirect
from .models import *
# Create your views here.
def take_control_over_your_habits(request, week_id):
if request.user.is_authenticated:
week_data = WeekModel.objects.filter(week_id=week_id).first()
if week_data is not None:
# getting resources and what you'll learn image/video and text
resources = ResourcesModel.objects.filter(week=week_data).all()
w_y_learn = WhatYoullLearnModel.objects.filter(week=week_data).all()
# for the header on page
main_title = 'Take Control Over Your Habits'
# checking if that weeks file is a video or not
file_name, extension = os.path.splitext(str(week_data.file))
is_video = False
if extension == '.mp4':
is_video = True
return render(request, 'template_pages/video_template.html',
{'data': week_data, 'resources': resources, 'w_y_learn': w_y_learn, 'main_title': main_title,
'sub_title': week_data.title, 'is_video': is_video})
else:
return render(request, 'main/404.html', {})
else:
return redirect('accounts:sign_in_to_members_area')
def mind_workshop(request, week_id):
if request.user.is_authenticated:
week_data = MindWorkshopModel.objects.filter(week_id=week_id).first()
if week_data is not None:
# getting resources and what you'll learn image/video and text
resources = ResourcesModel.objects.filter(mind_workshop=week_data).all()
w_y_learn = WhatYoullLearnModel.objects.filter(mind_workshop=week_data).all()
# for the header on page
main_title = 'Mind Workshop'
# checking if that weeks file is a video or not
file_name, extension = os.path.splitext(str(week_data.file))
is_video = False
if extension == '.mp4':
is_video = True
return render(request, 'template_pages/video_template.html',
{'data': week_data, 'resources': resources, 'w_y_learn': w_y_learn, 'main_title': main_title,
'sub_title': week_data.title, 'is_video': is_video})
else:
return render(request, 'main/404.html', {})
else:
return redirect('accounts:sign_in_to_members_area')
def day_(request, day_id):
if request.user.is_authenticated:
day_data = DayModel.objects.filter(day_id=day_id).first()
if day_data is not None:
# getting resources and what you'll learn image/video and text
resources = ResourcesModel.objects.filter(day=day_data).all()
w_y_learn = WhatYoullLearnModel.objects.filter(day=day_data).all()
# header and sub header
main_title = day_data.title.strip().split('-')[1]
sub_title = day_data.title.strip().split('-')[0]
# checking if that days file is a video or not
file_name, extension = os.path.splitext(str(day_data.file))
is_video = False
if extension == '.mp4':
is_video = True
return render(request, 'template_pages/template.html',
{'data': day_data, 'resources': resources, 'w_y_learn': w_y_learn, 'main_title': main_title,
'sub_title': sub_title, 'is_video': is_video})
else:
return render(request, 'main/404.html', {})
else:
return redirect('accounts:sign_in_to_members_area')
def five_day(request, day_id):
if request.user.is_authenticated:
day_data = FiveDayModel.objects.filter(day_id=day_id).first()
if day_data is not None:
# getting resources and what you'll learn image/video and text
resources = ResourcesModel.objects.filter(five_day=day_data).all()
w_y_learn = WhatYoullLearnModel.objects.filter(five_day=day_data).all()
# header and sub header
main_title = 'Five Days Challenge'
sub_title = day_data.title
# checking if that days file is a video or not
file_name, extension = os.path.splitext(str(day_data.file))
is_video = False
if extension == '.mp4':
is_video = True
return render(request, 'template_pages/template.html',
{'data': day_data, 'resources': resources, 'w_y_learn': w_y_learn, 'main_title': main_title,
'sub_title': sub_title, 'is_video': is_video})
else:
return render(request, 'main/404.html', {})
else:
return redirect('accounts:sign_in_to_members_area')
|
{"/accounts/extras_.py": ["/accounts/models.py"], "/accounts/migrations/0017_auto_20210809_2204.py": ["/accounts/models.py"], "/user_files/migrations/0003_auto_20210727_2335.py": ["/user_files/models.py"], "/accounts/migrations/0001_initial.py": ["/accounts/models.py"], "/characters/models.py": ["/accounts/models.py"], "/background_apps/functions.py": ["/accounts/models.py", "/characters/models.py"], "/main/views.py": ["/accounts/models.py", "/accounts/extras_.py", "/user_files/models.py", "/characters/models.py", "/behaviours/models.py", "/files_gallery/models.py"], "/api/views.py": ["/accounts/extras_.py", "/user_files/models.py", "/api/models.py"], "/user_files/views.py": ["/user_files/models.py"], "/characters/views.py": ["/characters/models.py", "/accounts/models.py"], "/accounts/tests.py": ["/accounts/models.py"], "/accounts/views.py": ["/accounts/models.py", "/accounts/extras_.py"], "/behaviours/models.py": ["/accounts/models.py"], "/behaviours/views.py": ["/accounts/models.py", "/behaviours/models.py"], "/files_gallery/models.py": ["/accounts/models.py"], "/behaviours/forms.py": ["/accounts/models.py", "/behaviours/models.py"], "/files_gallery/migrations/0001_initial.py": ["/files_gallery/models.py"], "/files_gallery/views.py": ["/files_gallery/models.py"], "/db_generated/views.py": ["/db_generated/models.py"], "/background/cron.py": ["/accounts/models.py", "/behaviours/models.py"], "/files_gallery/forms.py": ["/files_gallery/models.py"], "/db_generated/admin.py": ["/db_generated/models.py"], "/behaviours/admin.py": ["/behaviours/models.py"], "/files_gallery/admin.py": ["/files_gallery/models.py"], "/payment_system/views.py": ["/payment_system/models.py"]}
|
17,337,403
|
mindfirst-admin/mindfirst
|
refs/heads/main
|
/background/cron.py
|
import json
from accounts.models import Users
from apscheduler.schedulers.background import BackgroundScheduler
from behaviours.models import *
scheduled = BackgroundScheduler()
users = Users.objects.all()
# daily
def update_daily_behavior_record():
for user in users:
positive_habits_done_count = 0 # for positive habits done the prev day
all_selected_positive_habits = 0 # for all selected positive behaviours
negative_habits_n_done_count = 0 # for negative habits not done the prev day
all_selected_negative_habits = 0 # for all selected negative behaviours
user_behaviours = BehaviourMapping.objects.filter(user=user, is_selected=True).all()
for behaviour in user_behaviours:
# for positive behaviors
if behaviour.value == '+ve':
good_behaviour = DesignPositiveHabits.objects.filter(behaviour=behaviour).first()
if good_behaviour is not None:
if good_behaviour.frequency != 'weekly':
all_selected_positive_habits += 1
if behaviour.done_today:
positive_habits_done_count += 1
# for negative behaviors
elif behaviour.value == '-ve':
bad_behaviour = DesignNegativeHabits.objects.filter(behaviour=behaviour).first()
if bad_behaviour is not None:
if bad_behaviour.frequency != 'weekly':
all_selected_negative_habits += 1
if behaviour.done_today:
negative_habits_n_done_count += 1
# resetting it for new day
behaviour.done_today = False
behaviour.save()
# adding to weeks total
positive_behaviours_done_this_week = user.profile.positive_behaviors_done_this_week
negative_behaviours_done_this_week = user.profile.negative_behaviors_done_this_week
try:
# if there was data already present
# getting previous positive habit data
positive_habits_weekly_total = int(positive_behaviours_done_this_week.split('/')[0])
positive_selected_habits_weekly_total = int(positive_behaviours_done_this_week.split('/')[1])
# getting previous negative habit data
negative_habits_weekly_total = int(negative_behaviours_done_this_week.split('/')[0])
negative_selected_habits_weekly_total = int(negative_behaviours_done_this_week.split('/')[1])
# incrementing positive habits profile
positive_habits_weekly_total = positive_habits_weekly_total + positive_habits_done_count
positive_selected_habits_weekly_total = positive_selected_habits_weekly_total + all_selected_positive_habits
user.profile.positive_behaviors_done_this_week = f'{positive_habits_weekly_total}/' \
f'{positive_selected_habits_weekly_total}'
# incrementing negative habits profile
negative_habits_weekly_total = negative_habits_weekly_total + negative_habits_n_done_count
negative_selected_habits_weekly_total = negative_selected_habits_weekly_total + all_selected_negative_habits
user.profile.negative_behaviors_done_this_week = f'{negative_habits_weekly_total}/' \
f'{negative_selected_habits_weekly_total}'
# save
user.profile.save()
except Exception as e: # some django exception
# new weeks data
user.profile.positive_behaviors_done_this_week = f'{positive_habits_done_count}/' \
f'{all_selected_positive_habits}'
user.profile.negative_behaviors_done_this_week = f'{negative_habits_n_done_count}/' \
f'{all_selected_negative_habits}'
user.profile.save()
def update_daily_chart_using_thumb_clicks():
for user in users:
try:
# retrieving previous data from profile
positive_habits_done = json.loads(user.profile.all_positive_habits_this_week)
negative_habits_done = json.loads(user.profile.all_negative_habits_this_week)
scaled_habits = json.loads(user.profile.all_scaled_habits_this_week)
positive_thumbs_up_count = 0
negative_thumbs_up_count = 0
scaled_thumbs_up_count = 0
# getting positive behaviours with thumbs up on prev day
positive_user_behaviours = BehaviourMapping.objects.filter(user=user, is_selected=True, value='+ve').all()
if positive_user_behaviours is not None:
for behaviour in positive_user_behaviours:
positive_thumbs_up_count += behaviour.thumbs_up_today
# checking if behaviour is scaled so its moved to scaled list
if any(i.is_scaled == True for i in positive_user_behaviours):
# this is done for easier representation on chart
scaled_thumbs_up_count = positive_thumbs_up_count
positive_thumbs_up_count = 0
# appending data to previous data on list
positive_habits_done.append(positive_thumbs_up_count)
scaled_habits.append(scaled_thumbs_up_count)
# getting negative behaviours with thumbs up on prev day
negative_user_behaviours = BehaviourMapping.objects.filter(user=user, is_selected=True, value='-ve').all()
if negative_user_behaviours is not None:
for behaviour in negative_user_behaviours:
negative_thumbs_up_count += behaviour.thumbs_down_today
# appending data to previous data on list
negative_habits_done.append(negative_thumbs_up_count)
# entering new data to profile
user.profile.all_positive_habits_this_week = json.dumps(positive_habits_done)
user.profile.all_negative_habits_this_week = json.dumps(negative_habits_done)
user.profile.all_scaled_habits_this_week = json.dumps(scaled_habits)
user.profile.save()
except Exception as e:
pass
def analyze_daily_habit_n_reset_thumb_click():
for user in users:
user.profile.red_habits = 0
user.profile.yellow_habits = 0
user.profile.green_habits = 0
user.profile.scaled_habits = 0
user_behaviour = BehaviourMapping.objects.filter(user=user, is_selected=True).all()
if user_behaviour is not None:
for behaviour in user_behaviour:
thumbs_up = int(behaviour.thumbs_up_today)
thumbs_down = int(behaviour.thumbs_down_today)
if thumbs_up != 0 and thumbs_down != 0:
percentage_number = thumbs_up / (thumbs_up + thumbs_down)
percentage = percentage_number * 100
if 49 >= percentage >= 0:
user.profile.red_habits += 1
elif 79 >= percentage >= 50:
user.profile.yellow_habits += 1
elif 100 >= percentage >= 80:
user.profile.green_habits += 1
else:
if thumbs_up != 0:
user.profile.green_habits += 1
elif thumbs_down != 0:
user.profile.red_habits += 1
if behaviour.is_scaled:
user.profile.scaled_habits += 1
behaviour.thumbs_up_today = 0
behaviour.thumbs_down_today = 0
behaviour.save()
user.profile.save()
@scheduled.scheduled_job('cron', day_of_week='mon-sat', hour=23, minute=59)
def daily():
update_daily_behavior_record()
update_daily_chart_using_thumb_clicks()
analyze_daily_habit_n_reset_thumb_click()
# weekly
def weekly_record_refresh():
for user in users:
user_behaviours = BehaviourMapping.objects.filter(user=user).all()
if user_behaviours is not None:
for behaviour in user_behaviours:
behaviour.done_today = False
behaviour.save()
user.profile.positive_behaviors_done_this_week = '0/0'
user.profile.negative_behaviors_done_this_week = '0/0'
user.profile.all_positive_habits_this_week = '[]'
user.profile.all_scaled_habits_this_week = '[]'
user.profile.all_negative_habits_this_week = '[]'
user.profile.save()
def update_twelve_week_chart_using_thumb_clicks():
for user in users:
try:
positive_habits_done = json.loads(user.profile.all_positive_habits_in_twelve_weeks)
negative_habits_done = json.loads(user.profile.all_negative_habits_in_twelve_weeks)
scaled_habits = json.loads(user.profile.all_scaled_habits_in_twelve_weeks)
positive_thumbs_up_count = 0
negative_thumbs_up_count = 0
scaled_thumbs_up_count = 0
# getting positive behaviours with thumbs up on prev day
positive_user_behaviours = BehaviourMapping.objects.filter(user=user, is_selected=True, value='+ve').all()
if positive_user_behaviours is not None:
for behaviour in positive_user_behaviours:
positive_thumbs_up_count += behaviour.thumbs_up_this_week
# checking if behaviour is scaled so its moved to scaled list
if any(i.is_scaled == True for i in positive_user_behaviours):
# this is done for easier representation on chart
scaled_thumbs_up_count = positive_thumbs_up_count
positive_thumbs_up_count = 0
# appending data to previous data on list
positive_habits_done.append(positive_thumbs_up_count)
scaled_habits.append(scaled_thumbs_up_count)
# getting negative behaviours with thumbs up on prev day
negative_user_behaviours = BehaviourMapping.objects.filter(user=user, is_selected=True, value='-ve').all()
if negative_user_behaviours is not None:
for behaviour in negative_user_behaviours:
negative_thumbs_up_count += behaviour.thumbs_down_this_week
# appending data to previous data on list
negative_habits_done.append(negative_thumbs_up_count)
# entering new data to profile
user.profile.all_positive_habits_in_twelve_weeks = json.dumps(positive_habits_done)
user.profile.all_negative_habits_in_twelve_weeks = json.dumps(negative_habits_done)
user.profile.all_scaled_habits_in_twelve_weeks = json.dumps(scaled_habits)
user.profile.save()
except Exception as e:
pass
@scheduled.scheduled_job('cron', day_of_week='sun', hour=23, minute=55)
def weekly():
weekly_record_refresh()
update_twelve_week_chart_using_thumb_clicks()
# trimonthly
"""Todo: make scheduler for 3 months"""
|
{"/accounts/extras_.py": ["/accounts/models.py"], "/accounts/migrations/0017_auto_20210809_2204.py": ["/accounts/models.py"], "/user_files/migrations/0003_auto_20210727_2335.py": ["/user_files/models.py"], "/accounts/migrations/0001_initial.py": ["/accounts/models.py"], "/characters/models.py": ["/accounts/models.py"], "/background_apps/functions.py": ["/accounts/models.py", "/characters/models.py"], "/main/views.py": ["/accounts/models.py", "/accounts/extras_.py", "/user_files/models.py", "/characters/models.py", "/behaviours/models.py", "/files_gallery/models.py"], "/api/views.py": ["/accounts/extras_.py", "/user_files/models.py", "/api/models.py"], "/user_files/views.py": ["/user_files/models.py"], "/characters/views.py": ["/characters/models.py", "/accounts/models.py"], "/accounts/tests.py": ["/accounts/models.py"], "/accounts/views.py": ["/accounts/models.py", "/accounts/extras_.py"], "/behaviours/models.py": ["/accounts/models.py"], "/behaviours/views.py": ["/accounts/models.py", "/behaviours/models.py"], "/files_gallery/models.py": ["/accounts/models.py"], "/behaviours/forms.py": ["/accounts/models.py", "/behaviours/models.py"], "/files_gallery/migrations/0001_initial.py": ["/files_gallery/models.py"], "/files_gallery/views.py": ["/files_gallery/models.py"], "/db_generated/views.py": ["/db_generated/models.py"], "/background/cron.py": ["/accounts/models.py", "/behaviours/models.py"], "/files_gallery/forms.py": ["/files_gallery/models.py"], "/db_generated/admin.py": ["/db_generated/models.py"], "/behaviours/admin.py": ["/behaviours/models.py"], "/files_gallery/admin.py": ["/files_gallery/models.py"], "/payment_system/views.py": ["/payment_system/models.py"]}
|
17,337,404
|
mindfirst-admin/mindfirst
|
refs/heads/main
|
/files_gallery/urls.py
|
from django.urls import path
from . import views, forms
app_name = 'gallery'
urlpatterns = [
path("", views.vision_gallery, name="vision_gallery"),
path("edit-aspirations/", views.edit_aspirations, name="edit_aspirations"),
path("edit-values/", views.edit_values, name="edit_values"),
path("processing-video/", views.processing_video, name="processing_video"),
path("watch-video/", views.watch_video, name="watch_video"),
# form
path("delete-file/", forms.delete_file, name="delete_file"),
path("upload-files/", forms.upload_files, name="upload_files"),
path("process-files", forms.process_video, name="process_video"),
path("add-to-values", forms.add_to_values, name="add_to_values"),
]
|
{"/accounts/extras_.py": ["/accounts/models.py"], "/accounts/migrations/0017_auto_20210809_2204.py": ["/accounts/models.py"], "/user_files/migrations/0003_auto_20210727_2335.py": ["/user_files/models.py"], "/accounts/migrations/0001_initial.py": ["/accounts/models.py"], "/characters/models.py": ["/accounts/models.py"], "/background_apps/functions.py": ["/accounts/models.py", "/characters/models.py"], "/main/views.py": ["/accounts/models.py", "/accounts/extras_.py", "/user_files/models.py", "/characters/models.py", "/behaviours/models.py", "/files_gallery/models.py"], "/api/views.py": ["/accounts/extras_.py", "/user_files/models.py", "/api/models.py"], "/user_files/views.py": ["/user_files/models.py"], "/characters/views.py": ["/characters/models.py", "/accounts/models.py"], "/accounts/tests.py": ["/accounts/models.py"], "/accounts/views.py": ["/accounts/models.py", "/accounts/extras_.py"], "/behaviours/models.py": ["/accounts/models.py"], "/behaviours/views.py": ["/accounts/models.py", "/behaviours/models.py"], "/files_gallery/models.py": ["/accounts/models.py"], "/behaviours/forms.py": ["/accounts/models.py", "/behaviours/models.py"], "/files_gallery/migrations/0001_initial.py": ["/files_gallery/models.py"], "/files_gallery/views.py": ["/files_gallery/models.py"], "/db_generated/views.py": ["/db_generated/models.py"], "/background/cron.py": ["/accounts/models.py", "/behaviours/models.py"], "/files_gallery/forms.py": ["/files_gallery/models.py"], "/db_generated/admin.py": ["/db_generated/models.py"], "/behaviours/admin.py": ["/behaviours/models.py"], "/files_gallery/admin.py": ["/files_gallery/models.py"], "/payment_system/views.py": ["/payment_system/models.py"]}
|
17,337,405
|
mindfirst-admin/mindfirst
|
refs/heads/main
|
/files_gallery/forms.py
|
import os
import random
import string
import cv2 as cv
import numpy as np
from django.conf import settings
from django.http import HttpResponseRedirect, JsonResponse
from django.urls import reverse
from django.core.files import File
from .models import *
def generate_random_path():
length = 12
small_letters = string.ascii_lowercase
numbers = string.digits
code_ = small_letters + numbers
random_number = ''.join(random.choices(code_, k=length))
return random_number
def delete_file(request):
file_names = request.POST
for file_name in file_names:
if file_name != 'csrfmiddlewaretoken':
file_name = file_name.replace('media/', '')
path = VisionGalleryFiles.objects.get(user=request.user, file=file_name)
if path:
path.delete()
os.remove(os.path.join(settings.MEDIA_ROOT, file_name))
return HttpResponseRedirect(reverse('gallery:edit_aspirations'))
def upload_files(request):
file = request.FILES['aspirations_upload']
if file:
new_file = VisionGalleryFiles(user=request.user, file=file, file_category="aspirations")
new_file.save()
return HttpResponseRedirect(reverse('gallery:edit_aspirations'))
def process_video(request):
# main variables
resolution = (500, 500)
_ = cv.VideoWriter_fourcc(*'vp80') # webm file
rate = 40
image_dimensions = (500, 500)
# get files
aspirations_image = str(
VisionGalleryFiles.objects.filter(user=request.user, file_category='aspirations').first().file)
values = [str(i.file) for i in VisionGalleryFiles.objects.filter(user=request.user, file_category='values').all()]
values.insert(0, aspirations_image)
print('here 1')
image_video_files = values
# remove all the video files if any, in the directory
video_file = VisionGalleryFiles.objects.filter(user=request.user, file_category="video").all()
if video_file:
for file in video_file:
file_ = file.file
os.remove(os.path.join(settings.MEDIA_ROOT, str(file_)))
file.delete()
# create output video path and name
video_path = f'{settings.MEDIA_REL_PATH}start_video_{generate_random_path()}.webm'
output_video = cv.VideoWriter(video_path, _, rate, resolution)
print('here 2')
# run loop
prev_image = np.zeros((500, 500, 3), np.uint8)
for file in image_video_files:
print(file)
file_path = settings.MEDIA_ROOT + '/' + file
image = cv.imread(file_path)
image = cv.resize(image, image_dimensions, interpolation=cv.INTER_AREA)
# main part
for i in range(101):
alpha = i / 100
beta = 1.0 - alpha
dst = image
try:
dst = cv.addWeighted(image, alpha, prev_image, beta, 0.0)
except Exception as e:
print(e)
pass
finally:
if i == 100:
for j in range(150):
output_video.write(dst)
output_video.write(dst)
if cv.waitKey(1) == ord('q'):
return
prev_image = image
if cv.waitKey(5000) == ord('q'):
return
# close video writer
output_video.release()
print('here 3')
# save video
video = video_path.replace(settings.MEDIA_REL_PATH, '')
with open(video_path, 'rb') as f:
new_video = VisionGalleryFiles(user=request.user, file=File(f, name=video),
file_category="video")
new_video.save()
"""Todo: fix the remove file from other dir after save"""
os.remove(os.path.join(settings.MEDIA_ROOT, video))
# return Response
return JsonResponse('done', safe=False)
def add_to_values(request):
file_names = request.POST
if file_names:
# removing previous files
all_files = VisionGalleryFiles.objects.filter(user=request.user, file_category="values").all()
if all_files:
for file in all_files:
file = file.file
os.remove(os.path.join(settings.MEDIA_ROOT, str(file)))
all_files.delete()
# adding new files
for name in file_names:
if name != 'csrfmiddlewaretoken':
admin_file = f'{settings.MEDIA_REL_PATH}{name}'
print(admin_file)
with open(admin_file, 'rb') as f:
new_file = VisionGalleryFiles(user=request.user, file=File(f, name=admin_file.split('\\')[-1]),
file_category="values")
new_file.save()
return HttpResponseRedirect(reverse('gallery:vision_gallery'))
|
{"/accounts/extras_.py": ["/accounts/models.py"], "/accounts/migrations/0017_auto_20210809_2204.py": ["/accounts/models.py"], "/user_files/migrations/0003_auto_20210727_2335.py": ["/user_files/models.py"], "/accounts/migrations/0001_initial.py": ["/accounts/models.py"], "/characters/models.py": ["/accounts/models.py"], "/background_apps/functions.py": ["/accounts/models.py", "/characters/models.py"], "/main/views.py": ["/accounts/models.py", "/accounts/extras_.py", "/user_files/models.py", "/characters/models.py", "/behaviours/models.py", "/files_gallery/models.py"], "/api/views.py": ["/accounts/extras_.py", "/user_files/models.py", "/api/models.py"], "/user_files/views.py": ["/user_files/models.py"], "/characters/views.py": ["/characters/models.py", "/accounts/models.py"], "/accounts/tests.py": ["/accounts/models.py"], "/accounts/views.py": ["/accounts/models.py", "/accounts/extras_.py"], "/behaviours/models.py": ["/accounts/models.py"], "/behaviours/views.py": ["/accounts/models.py", "/behaviours/models.py"], "/files_gallery/models.py": ["/accounts/models.py"], "/behaviours/forms.py": ["/accounts/models.py", "/behaviours/models.py"], "/files_gallery/migrations/0001_initial.py": ["/files_gallery/models.py"], "/files_gallery/views.py": ["/files_gallery/models.py"], "/db_generated/views.py": ["/db_generated/models.py"], "/background/cron.py": ["/accounts/models.py", "/behaviours/models.py"], "/files_gallery/forms.py": ["/files_gallery/models.py"], "/db_generated/admin.py": ["/db_generated/models.py"], "/behaviours/admin.py": ["/behaviours/models.py"], "/files_gallery/admin.py": ["/files_gallery/models.py"], "/payment_system/views.py": ["/payment_system/models.py"]}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.