index
int64 | repo_name
string | branch_name
string | path
string | content
string | import_graph
string |
|---|---|---|---|---|---|
22,452,993
|
AkarasateH/PyRouterSimulation
|
refs/heads/main
|
/helper.py
|
from tabulate import tabulate
import json
import os
def DisplayObjectTable(headers: [str], data: dict, tableName: str = 'Table'):
primaryKeys = data.keys()
dataDisplay = []
for key in primaryKeys:
newArray = [key]
for val in data[key].values():
newArray.append(val)
dataDisplay.append(newArray)
os.system('clear')
print('\n ----------- {} ----------- '.format(tableName) )
print(tabulate(dataDisplay, headers=headers, tablefmt='fancy_grid'))
def ConvertJsonToString(data: dict):
return json.dumps(data)
def ConvertStringToJson(data: str):
return json.loads(data)
|
{"/main.py": ["/router.py", "/profileManager.py", "/helper.py", "/routeTable.py"], "/routerF.py": ["/router.py", "/profileManager.py", "/helper.py", "/routeTable.py"], "/profileManager.py": ["/helper.py"], "/routeTable.py": ["/helper.py"], "/routerB.py": ["/router.py", "/profileManager.py"], "/router.py": ["/profileManager.py", "/routeTable.py", "/helper.py"], "/routerG.py": ["/router.py", "/profileManager.py"], "/routerD.py": ["/router.py", "/profileManager.py"], "/routerC.py": ["/router.py", "/profileManager.py"], "/setting.py": ["/router.py", "/profileManager.py", "/helper.py", "/routeTable.py"]}
|
22,452,994
|
AkarasateH/PyRouterSimulation
|
refs/heads/main
|
/routerG.py
|
from router import Router
from profileManager import ProfileManager
import logging
logging.basicConfig(format='%(asctime)s - Router F:%(message)s', level=logging.INFO)
profile = ProfileManager()
profiles = profile.getAllProfiles()
router = Router(profiles['G']['ip'], profiles['G']['port'], 'G')
router.run()
# router.updateRoutingTable()
|
{"/main.py": ["/router.py", "/profileManager.py", "/helper.py", "/routeTable.py"], "/routerF.py": ["/router.py", "/profileManager.py", "/helper.py", "/routeTable.py"], "/profileManager.py": ["/helper.py"], "/routeTable.py": ["/helper.py"], "/routerB.py": ["/router.py", "/profileManager.py"], "/router.py": ["/profileManager.py", "/routeTable.py", "/helper.py"], "/routerG.py": ["/router.py", "/profileManager.py"], "/routerD.py": ["/router.py", "/profileManager.py"], "/routerC.py": ["/router.py", "/profileManager.py"], "/setting.py": ["/router.py", "/profileManager.py", "/helper.py", "/routeTable.py"]}
|
22,452,995
|
AkarasateH/PyRouterSimulation
|
refs/heads/main
|
/routerF.py
|
from router import Router
from profileManager import ProfileManager
import logging
logging.basicConfig(format='%(asctime)s - Router F:%(message)s', level=logging.INFO)
profile = ProfileManager()
profiles = profile.getAllProfiles()
router = Router(profiles['F']['ip'], profiles['F']['port'], 'F')
router.run()
# router.updateRoutingTable()
|
{"/main.py": ["/router.py", "/profileManager.py", "/helper.py", "/routeTable.py"], "/routerF.py": ["/router.py", "/profileManager.py", "/helper.py", "/routeTable.py"], "/profileManager.py": ["/helper.py"], "/routeTable.py": ["/helper.py"], "/routerB.py": ["/router.py", "/profileManager.py"], "/router.py": ["/profileManager.py", "/routeTable.py", "/helper.py"], "/routerG.py": ["/router.py", "/profileManager.py"], "/routerD.py": ["/router.py", "/profileManager.py"], "/routerC.py": ["/router.py", "/profileManager.py"], "/setting.py": ["/router.py", "/profileManager.py", "/helper.py", "/routeTable.py"]}
|
22,452,996
|
AkarasateH/PyRouterSimulation
|
refs/heads/main
|
/routerD.py
|
from router import Router
from profileManager import ProfileManager
import logging
logging.basicConfig(format='%(asctime)s - Router D:%(message)s', level=logging.INFO)
profile = ProfileManager()
profiles = profile.getAllProfiles()
router = Router(profiles['D']['ip'], profiles['D']['port'], 'D')
router.run()
# router.updateRoutingTable()
|
{"/main.py": ["/router.py", "/profileManager.py", "/helper.py", "/routeTable.py"], "/routerF.py": ["/router.py", "/profileManager.py", "/helper.py", "/routeTable.py"], "/profileManager.py": ["/helper.py"], "/routeTable.py": ["/helper.py"], "/routerB.py": ["/router.py", "/profileManager.py"], "/router.py": ["/profileManager.py", "/routeTable.py", "/helper.py"], "/routerG.py": ["/router.py", "/profileManager.py"], "/routerD.py": ["/router.py", "/profileManager.py"], "/routerC.py": ["/router.py", "/profileManager.py"], "/setting.py": ["/router.py", "/profileManager.py", "/helper.py", "/routeTable.py"]}
|
22,452,997
|
AkarasateH/PyRouterSimulation
|
refs/heads/main
|
/routerC.py
|
from router import Router
from profileManager import ProfileManager
import logging
logging.basicConfig(format='%(asctime)s - Router C:%(message)s', level=logging.INFO)
profile = ProfileManager()
profiles = profile.getAllProfiles()
router = Router(profiles['C']['ip'], profiles['C']['port'], 'C')
router.run()
# router.updateRoutingTable()
|
{"/main.py": ["/router.py", "/profileManager.py", "/helper.py", "/routeTable.py"], "/routerF.py": ["/router.py", "/profileManager.py", "/helper.py", "/routeTable.py"], "/profileManager.py": ["/helper.py"], "/routeTable.py": ["/helper.py"], "/routerB.py": ["/router.py", "/profileManager.py"], "/router.py": ["/profileManager.py", "/routeTable.py", "/helper.py"], "/routerG.py": ["/router.py", "/profileManager.py"], "/routerD.py": ["/router.py", "/profileManager.py"], "/routerC.py": ["/router.py", "/profileManager.py"], "/setting.py": ["/router.py", "/profileManager.py", "/helper.py", "/routeTable.py"]}
|
22,452,998
|
AkarasateH/PyRouterSimulation
|
refs/heads/main
|
/setting.py
|
from router import Router
from profileManager import ProfileManager
from helper import DisplayObjectTable
from routeTable import RoutingTable
import logging
logging.basicConfig(format='%(asctime)s - Main:%(message)s', level=logging.INFO)
def __createProfiles():
profileManager = ProfileManager()
# ------------- Minimal Network -------------
# profileManager.removeProfile('D')
# profileManager.removeProfile('E')
# profileManager.removeProfile('F')
# profileManager.addAndUpdateProfile('A', '127.0.0.1', ['192.168.1.0/24', '192.168.4.0/24'], 4000, ['B'])
# profileManager.addAndUpdateProfile('B', '127.0.0.1', ['192.168.2.0/24'], 4001, ['A', 'C'])
# profileManager.addAndUpdateProfile('C', '127.0.0.1', ['192.168.3.0/24', '192.168.2.0/24'], 4002, ['B'])
# ------------- Large Network -------------
profileManager.removeProfile('A')
profileManager.removeProfile('B')
profileManager.removeProfile('C')
profileManager.removeProfile('D')
profileManager.removeProfile('E')
profileManager.removeProfile('F')
profileManager.addAndUpdateProfile('A', '127.0.0.1', ['192.168.1.0/24', '192.168.4.0/24'], 4000, ['B', 'D'])
profileManager.addAndUpdateProfile('B', '127.0.0.1', ['192.168.2.0/24'], 4001, ['A', 'D'])
profileManager.addAndUpdateProfile('C', '127.0.0.1', ['192.168.3.0/24', '192.168.8.0/24'], 4002, ['D', 'F', 'G'])
profileManager.addAndUpdateProfile('D', '127.0.0.1', ['192.168.4.0/24', '192.168.8.0/24'], 4003, ['A', 'B', 'E'])
profileManager.addAndUpdateProfile('E', '127.0.0.1', ['192.168.6.0/24', '192.168.7.0/24'], 4004, ['D', 'F'])
profileManager.addAndUpdateProfile('F', '127.0.0.1', ['192.168.5.0/24'], 4005, ['C', 'E', 'G'])
profileManager.addAndUpdateProfile('G', '127.0.0.1', [], 4006, ['C', 'F'])
profileManager.getAllProfiles()
__createProfiles()
|
{"/main.py": ["/router.py", "/profileManager.py", "/helper.py", "/routeTable.py"], "/routerF.py": ["/router.py", "/profileManager.py", "/helper.py", "/routeTable.py"], "/profileManager.py": ["/helper.py"], "/routeTable.py": ["/helper.py"], "/routerB.py": ["/router.py", "/profileManager.py"], "/router.py": ["/profileManager.py", "/routeTable.py", "/helper.py"], "/routerG.py": ["/router.py", "/profileManager.py"], "/routerD.py": ["/router.py", "/profileManager.py"], "/routerC.py": ["/router.py", "/profileManager.py"], "/setting.py": ["/router.py", "/profileManager.py", "/helper.py", "/routeTable.py"]}
|
22,456,419
|
JuakoAsdf/JoJu-WebSite-Django
|
refs/heads/main
|
/PetShop/gestorProducto/models.py
|
from django.db import models
# Create your models here.
class Marca(models.Model):
nombre = models.TextField(max_length=50)
def __str__(self):
return self.nombre
class Categoria(models.Model):
nombre = models.TextField(max_length=50)
activo = models.BooleanField()
def __str__(self):
return self.nombre
class Sucursal(models.Model):
nombre = models.TextField(max_length=50)
direccion = models.TextField(max_length=100)
telefono = models.TextField(max_length=9)
encargado = models.TextField(max_length=60)
def __str__(self):
return self.nombre
class Producto(models.Model):
marca = models.ForeignKey(Marca, blank=True, null=True, on_delete=models.SET_NULL)
categoria = models.ForeignKey(Categoria, blank=True, null=True, on_delete=models.SET_NULL)
nombre = models.TextField(max_length=60)
imagen = models.ImageField('Foto', upload_to='producto/', null=True, blank=True)
codigo = models.DecimalField(max_digits=13, decimal_places=0)
descripcion = models.TextField(max_length = 200)
stock = models.IntegerField()
precioCosto = models.IntegerField()
precioVenta = models.IntegerField()
def __str__(self):
return self.nombre
class Adopcion(models.Model):
nombre = models.TextField(max_length=60)
descripcion = models.TextField(max_length = 200)
imagen = models.ImageField('Imagen', upload_to='adopta/', null=True, blank=True)
def __str__(self):
return self.nombre
|
{"/PetShop/gestorProducto/serializers.py": ["/PetShop/gestorProducto/models.py"], "/PetShop/gestorProducto/admin.py": ["/PetShop/gestorProducto/models.py"], "/PetShop/gestorProducto/views.py": ["/PetShop/gestorProducto/serializers.py"], "/PetShop/gestorProducto/urls.py": ["/PetShop/gestorProducto/views.py"]}
|
22,456,420
|
JuakoAsdf/JoJu-WebSite-Django
|
refs/heads/main
|
/PetShop/gestorProducto/serializers.py
|
from rest_framework import serializers
from .models import Producto
class ProductoSerializer(serializers.ModelSerializer):
class Meta:
model = Producto
fields = ['categoria', 'nombre', 'descripcion', 'codigo', 'stock', 'precioCosto', 'precioVenta']
|
{"/PetShop/gestorProducto/serializers.py": ["/PetShop/gestorProducto/models.py"], "/PetShop/gestorProducto/admin.py": ["/PetShop/gestorProducto/models.py"], "/PetShop/gestorProducto/views.py": ["/PetShop/gestorProducto/serializers.py"], "/PetShop/gestorProducto/urls.py": ["/PetShop/gestorProducto/views.py"]}
|
22,456,421
|
JuakoAsdf/JoJu-WebSite-Django
|
refs/heads/main
|
/PetShop/gestorProducto/admin.py
|
from django.contrib import admin
from .models import Marca
from .models import Categoria
from .models import Sucursal
from .models import Producto
from .models import Adopcion
# Register your models here.
class productoAdmin(admin.ModelAdmin):
list_display = ['nombre',
'precioVenta',
'descripcion',
'stock']
list_display_filter = ['categoria',
'marca',
'precioVenta']
search_fields = ['nombre',
'descripcion']
admin.site.register(Producto, productoAdmin)
class marcaAdmin(admin.ModelAdmin):
list_display = ['nombre']
list_display_filter = ['nombre']
admin.site.register(Marca, marcaAdmin)
class categoriaAdmin(admin.ModelAdmin):
list_display = ['nombre','activo']
list_display_filter = ['nombre']
search_fields = ['activo']
admin.site.register(Categoria, categoriaAdmin)
class sucursalAdmin(admin.ModelAdmin):
list_display = ['nombre',
'direccion',
'telefono',
'encargado']
list_display_filter = ['nombre']
search_fields = ['nombre',
'direccion']
admin.site.register(Sucursal, sucursalAdmin)
admin.site.register(Adopcion)
|
{"/PetShop/gestorProducto/serializers.py": ["/PetShop/gestorProducto/models.py"], "/PetShop/gestorProducto/admin.py": ["/PetShop/gestorProducto/models.py"], "/PetShop/gestorProducto/views.py": ["/PetShop/gestorProducto/serializers.py"], "/PetShop/gestorProducto/urls.py": ["/PetShop/gestorProducto/views.py"]}
|
22,456,422
|
JuakoAsdf/JoJu-WebSite-Django
|
refs/heads/main
|
/PetShop/gestorProducto/views.py
|
from django.shortcuts import render
from django.contrib.auth.models import User
from django.contrib.auth.hashers import make_password
from django.shortcuts import redirect
from django.conf import settings
from gestorProducto.models import Adopcion
from gestorProducto.models import Producto
from django.contrib.auth import authenticate
from django.contrib.auth.forms import AuthenticationForm
from django.contrib.auth import login as do_login
from django.contrib.auth import logout as do_logout
#rest_framework
from rest_framework import viewsets
from .serializers import ProductoSerializer
# Create your views here.
def logout(request):
return redirect('')
def inicio(request):
return render(request,'inicio.html', {})
def buscar(request):
item = {}
desc = {}
if request.method == "POST":
buscar = request.POST['txtBuscar']
if 'txtBuscar' in request.POST:
item = Producto.objects.filter(nombre__contains = buscar)
desc = Producto.objects.filter(descripcion__contains = buscar)
return render(request,'buscar.html', {'item': item, 'desc':desc})
def alimentoadultocat(request):
lista = Producto.objects.filter(categoria__nombre = "Comida Gato Adulto")
contexto = {'lista' : lista}
return render(request,'alimentoadultocat.html', contexto)
def alimentogatito(request):
lista = Producto.objects.filter(categoria__nombre = "Comida Gatito")
contexto = {'lista' : lista}
return render(request,'alimentogatito.html', contexto)
def accesoriocat(request):
lista = Producto.objects.filter(categoria__nombre = "Accesorios Gatos")
contexto = {'lista' : lista}
return render(request,'accesoriocat.html', contexto)
def alimentoadultodog(request):
lista = Producto.objects.filter(categoria__nombre = "Comida Perro Adulto")
contexto = {'lista' : lista}
return render(request,'alimentoadultodog.html', contexto)
def alimentocachorro(request):
lista = Producto.objects.filter(categoria__nombre = "Comida Cachorrito")
contexto = {'lista' : lista}
return render(request,'alimentocachorro.html', contexto)
def accesoriodog(request):
lista = Producto.objects.filter(categoria__nombre = "Accesorios Perros")
contexto = {'lista' : lista}
return render(request,'accesoriodog.html', contexto)
def adopcion(request):
lista = Adopcion.objects.all()
contexto = {'lista' : lista}
return render(request,'adopcion.html', contexto)
def nosotros(request):
return render(request,'nosotros.html', {})
def loginPage(request):
form = AuthenticationForm()
if request.method == "POST":
form = AuthenticationForm(data=request.POST)
if form.is_valid():
nombre = form.cleaned_data['username']
clave = form.cleaned_data['password']
user = authenticate(username=nombre, password=clave)
if user is not None:
do_login(request, user)
return redirect('inicio')
return render(request,'loginn.html', {'form':form})
def registerPage(request):
if request.method == "POST":
nombre = request.POST["txtUsuario"]
correo = request.POST["txtCorreo"]
clave = request.POST["txtClave"]
User.objects.create(username=nombre, email=correo, password=make_password(clave))
#return redirect('%s?next=%s' % (settings.LOGIN_URL, request.path))
return render(request,'register.html', {})
#Clases para API
class ProductoViewSet(viewsets.ModelViewSet):
queryset = Producto.objects.all()
serializer_class = ProductoSerializer
|
{"/PetShop/gestorProducto/serializers.py": ["/PetShop/gestorProducto/models.py"], "/PetShop/gestorProducto/admin.py": ["/PetShop/gestorProducto/models.py"], "/PetShop/gestorProducto/views.py": ["/PetShop/gestorProducto/serializers.py"], "/PetShop/gestorProducto/urls.py": ["/PetShop/gestorProducto/views.py"]}
|
22,456,423
|
JuakoAsdf/JoJu-WebSite-Django
|
refs/heads/main
|
/PetShop/gestorProducto/urls.py
|
from django.urls import path, include
from . import views
from django.conf import settings
from django.conf.urls.static import static
from .views import ProductoViewSet
from rest_framework import routers
router = routers.DefaultRouter()
router.register('productos', ProductoViewSet)
urlpatterns = [
path('',views.inicio, name='inicio'),
path('inicio',views.inicio, name='inicio'),
path('adultocat',views.alimentoadultocat, name='adultocat'),
path('gatitocat',views.alimentogatito, name='gatitocat'),
path('accesocat',views.accesoriocat, name='accesocat'),
path('adultodog',views.alimentoadultodog, name='adultodog'),
path('cachorrodog',views.alimentocachorro, name='cachorrodog'),
path('accesodog',views.accesoriodog, name='accesodog'),
path('adopta',views.adopcion, name='adopta'),
path('nosotro',views.nosotros, name='nosotro'),
path('log',views.loginPage, name='log'),
path('buscar',views.buscar, name='buscar'),
path('regis',views.registerPage, name='regis'),
path('logout', views.logout, name='logout'),
path('api/', include(router.urls)),
] + static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT)
|
{"/PetShop/gestorProducto/serializers.py": ["/PetShop/gestorProducto/models.py"], "/PetShop/gestorProducto/admin.py": ["/PetShop/gestorProducto/models.py"], "/PetShop/gestorProducto/views.py": ["/PetShop/gestorProducto/serializers.py"], "/PetShop/gestorProducto/urls.py": ["/PetShop/gestorProducto/views.py"]}
|
22,456,424
|
JuakoAsdf/JoJu-WebSite-Django
|
refs/heads/main
|
/PetShop/gestorProducto/migrations/0001_initial.py
|
# Generated by Django 3.1.2 on 2020-10-28 14:38
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Categoria',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('nombre', models.TextField(max_length=50)),
('activo', models.BooleanField()),
],
),
migrations.CreateModel(
name='Marca',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('nombre', models.TextField(max_length=50)),
],
),
migrations.CreateModel(
name='Sucursal',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('nombre', models.TextField(max_length=50)),
('direccion', models.TextField(max_length=100)),
('telefono', models.TextField(max_length=9)),
('encargado', models.TextField(max_length=60)),
],
),
migrations.CreateModel(
name='Producto',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('nombre', models.TextField(max_length=60)),
('codigo', models.DecimalField(decimal_places=0, max_digits=13)),
('descripcion', models.TextField(max_length=200)),
('stock', models.IntegerField()),
('precioCosto', models.IntegerField()),
('precioVenta', models.IntegerField()),
('categoria', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to='gestorProducto.categoria')),
('marca', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to='gestorProducto.marca')),
],
),
]
|
{"/PetShop/gestorProducto/serializers.py": ["/PetShop/gestorProducto/models.py"], "/PetShop/gestorProducto/admin.py": ["/PetShop/gestorProducto/models.py"], "/PetShop/gestorProducto/views.py": ["/PetShop/gestorProducto/serializers.py"], "/PetShop/gestorProducto/urls.py": ["/PetShop/gestorProducto/views.py"]}
|
22,456,425
|
JuakoAsdf/JoJu-WebSite-Django
|
refs/heads/main
|
/PetShop/gestorProducto/migrations/0004_producto_imagen.py
|
# Generated by Django 3.1.2 on 2020-11-10 23:46
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('gestorProducto', '0003_auto_20201110_1956'),
]
operations = [
migrations.AddField(
model_name='producto',
name='imagen',
field=models.ImageField(blank=True, null=True, upload_to='producto/', verbose_name='Foto'),
),
]
|
{"/PetShop/gestorProducto/serializers.py": ["/PetShop/gestorProducto/models.py"], "/PetShop/gestorProducto/admin.py": ["/PetShop/gestorProducto/models.py"], "/PetShop/gestorProducto/views.py": ["/PetShop/gestorProducto/serializers.py"], "/PetShop/gestorProducto/urls.py": ["/PetShop/gestorProducto/views.py"]}
|
22,456,426
|
JuakoAsdf/JoJu-WebSite-Django
|
refs/heads/main
|
/PetShop/gestorProducto/migrations/0003_auto_20201110_1956.py
|
# Generated by Django 3.1.2 on 2020-11-10 22:56
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('gestorProducto', '0002_adopcion'),
]
operations = [
migrations.RemoveField(
model_name='adopcion',
name='activo',
),
migrations.AddField(
model_name='adopcion',
name='imagen',
field=models.ImageField(blank=True, null=True, upload_to='adopta/', verbose_name='Imagen'),
),
]
|
{"/PetShop/gestorProducto/serializers.py": ["/PetShop/gestorProducto/models.py"], "/PetShop/gestorProducto/admin.py": ["/PetShop/gestorProducto/models.py"], "/PetShop/gestorProducto/views.py": ["/PetShop/gestorProducto/serializers.py"], "/PetShop/gestorProducto/urls.py": ["/PetShop/gestorProducto/views.py"]}
|
22,456,427
|
JuakoAsdf/JoJu-WebSite-Django
|
refs/heads/main
|
/PetShop/gestorProducto/apps.py
|
from django.apps import AppConfig
class GestorproductoConfig(AppConfig):
name = 'gestorProducto'
|
{"/PetShop/gestorProducto/serializers.py": ["/PetShop/gestorProducto/models.py"], "/PetShop/gestorProducto/admin.py": ["/PetShop/gestorProducto/models.py"], "/PetShop/gestorProducto/views.py": ["/PetShop/gestorProducto/serializers.py"], "/PetShop/gestorProducto/urls.py": ["/PetShop/gestorProducto/views.py"]}
|
22,540,763
|
alfonsoamt/Process_Egineering_Simulator
|
refs/heads/main
|
/simulator.py
|
import pandas as pd
class Simulator:
# This class represents the simulator environment
def __init__(self):
self.database = None #This is de database information
self.errors = [] # This is a severe error list
self.warnings = [] # This is a warming error list
# This method loads the Perry's handbook data
def load_perry(self):
self.database = pd.read_csv("./properties/Database.csv",index_col=("Name"))
return self.database
class Variable:
# This class represents a variable. It could be a process variable or parameters from equations
def __init__(self, value, units):
self.value = value # Variable value
self.units = units # Variable units
self.units_c = None # Variable units database for units convertion
self.v_type = "" # Variable type
# This method converts the variable units
def Converter(self):
pass
class Temperature(Variable):
# Variable: Temperature
def __init__(self, value, units):
super().__init__(value, units)
self.v_type = "Temperature"
self.units_c = pd.DataFrame({"K":[lambda T: T , lambda T: T + 273.15, lambda T: (T + 459.67) * 5 / 9, lambda T: T * 5 / 9],
"°C":[lambda T: T - 273.15, lambda T: T, lambda T: (T - 32) * 5 /9, lambda T: (T - 491.67) * 5 / 9],
"°F":[lambda T: (T * 9 / 5) -459.67, lambda T: (T * 9 / 5) + 32, lambda T: T, lambda T: T - 459.67],
"R":[lambda T: T * 9 / 5, lambda T: (T + 273.15) * 9 / 5, lambda T: T + 459.67, lambda T: T]},
index = ["K", "°C", "°F", "R"])
def Converter(self, Tunits):
self.value = round(self.units_c.at[self.units, Tunits](self.value), 2)
self.units = Tunits
class Pressure(Variable):
# Variable: Pressure
def __init__(self, value, units):
super().__init__(value, units)
self.v_type = "Pressure"
self.units_c = pd.read_csv('./units/Pressure.csv', index_col = 0)
def Converter(self, Punits):
self.value = self.value * self.units_c.at[self.units, Punits]
self.units = Punits
class MolarVolume(Variable):
# Variable: Molar volume
def __init__(self, value, units):
super().__init__(value, units)
self.v_type = "MolarVolume"
self.units_c = pd.read_csv('./units/MolarVolume.csv', index_col = 0)
def Converter(self, MVunits):
self.value = self.value * self.units_c.at[self.units, MVunits]
self.units = MVunits
class MolarHeatCapacity(Variable):
def __init__(self, value, units):
super().__init__(value, units)
self.v_type = "Molar heat capacity"
self.units_c = None
def Converter(self, MHCunits):
self.value = self.value * self.units_c.at[self.units, MHCunits]
self.units = MHCunits
class MolarEnthalpy(Variable):
def __init__(self, value, units):
super().__init__(value, units)
self.v_type = "Molar enthalpy"
self.units_c = None
def Converter(self, MHunits):
self.value = self.value * self.units_c.at[self.units, MHunits]
self.units = MHunits
class MolarGibbs(Variable):
def __init__(self, value, units):
super().__init__(value, units)
self.v_type = "Molar Gibbs energy"
self.units_c = None
def Converter(self, MGunits):
self.value = self.value * self.units_c.at[self.units, MGunits]
self.units = MGunits
class MolarEntropy(Variable):
def __init__(self, value, units):
super().__init__(value, units)
self.v_type = "Molar entropy"
self.units_c = None
def Converter(self, MSunits):
self.value = self.value * self.units_c.at[self.units, MSunits]
self.units = MSunits
class MolarWeight(Variable):
def __init__(self, value):
super().__init__(value, "None")
self.v_type = "Molar weight"
self.units_c = None
|
{"/compound.py": ["/simulator.py", "/units.py"], "/main.py": ["/simulator.py", "/compound.py"], "/mixture.py": ["/compound.py", "/simulator.py"]}
|
22,540,764
|
alfonsoamt/Process_Egineering_Simulator
|
refs/heads/main
|
/main.py
|
from simulator import *
from compound import *
S = Simulator()
T1 = Temperature(300, "K")
T2 = Temperature(500, "K")
A = Compound("Air")
A.CP_ig(T1,'K', True)
A.mean_CP(A.CP_ig, T1, T2, "J/kmol*K", 'gas', True)
A.Vapor_pressure(T1, True)
A.Vapor_pressure(T2, True)
|
{"/compound.py": ["/simulator.py", "/units.py"], "/main.py": ["/simulator.py", "/compound.py"], "/mixture.py": ["/compound.py", "/simulator.py"]}
|
22,540,765
|
alfonsoamt/Process_Egineering_Simulator
|
refs/heads/main
|
/equation.py
|
# -*- coding: utf-8 -*-
"""
Created on Sun Apr 18 18:21:17 2021
@author: alfon
"""
# import numpy as np
# class equation:
# def __init__(self):
# self.expression = none
# self.v = []
# self.c = []
# self.p = []
# def variable(self, value, units = none):
# try:
# if isinstance(value,(np.ndarray, list, tuple, dict, set)):
# raise valueerror("input must be a scalar.")
# except valueerror as ve:
# print(ve)
# else:
# self.v.append([value,units])
# return [value,units]
# def parameter(self, value, units = none):
# try:
# if isinstance(value,(np.ndarray, list, tuple, dict, set)):
# raise valueerror("input must be a scalar.")
# except valueerror as ve:
# print(ve)
# else:
# self.p.append([value,units])
# return [value,units]
# def expression()
# if __name__=='__main__':
# eq = equation()
# x = eq.variable(1)
# print(x)
|
{"/compound.py": ["/simulator.py", "/units.py"], "/main.py": ["/simulator.py", "/compound.py"], "/mixture.py": ["/compound.py", "/simulator.py"]}
|
22,540,766
|
alfonsoamt/Process_Egineering_Simulator
|
refs/heads/main
|
/mixture.py
|
from compound import Compound
from simulator import *
class Mixture(Compound):
def __init__(self, composition, basis):
self.composition = composition
if basis == "molar":
self.to_mass()
elif basis == "mass":
self.to_mole()
else:
print('Basis not defined')
# Pure properties
#self.mw = MolarWeight(mw) # molecular weight
self.Hig_f = None # ideal gas enthalpy of formation
self.Gig_f = None # ideal gas Gibbs free energy of formation
self.Sig = None # ideal gas entropy
self.Hstd_c = None # standard heat of combustion
self.acentric = None # acentric factor
self.dipole = None # magnetic dipole
# Critical properties
self.Tc = None # critical temperature
self.Pc = None # critical pressure
self.Vmc = None # critical molar volume
self.Zc = None # critical compressibility factor
# Thermodynamic properties
self.Z = None # compresibility factor
self.Pvap = None # vapor pressure
self.mCPig = None # mean ideas gas heat capacity
self.mCPl = None # mean liquid heat capacity
self.CPig = None # ideal gas heat capacity
self.CPl = None # liquid heat capacity
self.density = None # density
# Transport properties
self.GasVis = None # gas viscosity
self.LiqVis = None # liquid viscosity
self.GasTC = None # gas thermal conductivity
self.LiqTC = None # liquid therml conductivity
def to_mass(self):
#normalize
frac = sum([y.mole_frac for y in self.composition])
if not frac == 1.0:
for y in self.composition:
y.mole_frac = y.mole_frac / frac
total_mass = sum([y.mole_frac * y.mw for y in self.composition])
for x in self.composition:
x.mass_frac = x.mole_frac * x.mw / total_mass
self.mw = sum([y.mw * y.mole_frac for y in self.composition])
def to_mole(self):
frac = sum([x.mass_frac for x in self.composition])
if not frac == 1.0:
for x in self.composition:
x.mass_frac = x.mass_frac / frac
total_mole = sum([x.mass_frac / x.mw for x in self.composition])
for y in self.composition:
y.mole_frac = (y.mass_frac / y.mw) / total_mole
self.mw = pow(sum([x.mass_frac / x.mw for x in self.composition ]), -1)
|
{"/compound.py": ["/simulator.py", "/units.py"], "/main.py": ["/simulator.py", "/compound.py"], "/mixture.py": ["/compound.py", "/simulator.py"]}
|
22,540,767
|
alfonsoamt/Process_Egineering_Simulator
|
refs/heads/main
|
/compound.py
|
import numpy as np
from scipy.integrate import quad
from datetime import datetime
from math import sinh, cosh
import pandas as pd
from simulator import *
S = Simulator()
## This file contains the Compound class
class Compound:
def __init__(self, name, mw = None, Perry = True):
self.name = name # Compound name
# Pure properties
self.mw = MolarWeight(mw) # molecular weight
self.mole_frac = 1.0 # mol fraction
self.mass_frac = 1.0 # mass fraction
self.Hig_f = None # ideal gas enthalpy of formation
self.Gig_f = None # ideal gas Gibbs free energy of formation
self.Sig = None # ideal gas entropy
self.Hstd_c = None # standard heat of combustion
self.acentric = None # acentric factor
self.dipole = None # magnetic dipole
# Critical properties
self.Tc = None # critical temperature
self.Pc = None # critical pressure
self.Vmc = None # critical molar volume
self.Zc = None # critical compressibility factor
# Thermodynamic properties
self.Z = None # compresibility factor
self.Pvap = None # vapor pressure
self.mCPig = None # mean ideas gas heat capacity
self.mCPl = None # mean liquid heat capacity
self.CPig = None # ideal gas heat capacity
self.CPl = None # liquid heat capacity
self.density = None # density
# Transport properties
self.GasVis = None # gas viscosity
self.LiqVis = None # liquid viscosity
self.GasTC = None # gas thermal conductivity
self.LiqTC = None # liquid therml conductivity
if Perry:
# data
self.data = S.load_perry()
# Pure compound proprerties
self.wt = MolarWeight(self.data.at[self.name, "wt"])
self.Hig_f = MolarEnthalpy(self.data.at[self.name, "Hig_f"], "kJ/mol")
self.Gig_f = MolarGibbs(self.data.at[self.name, "Gig_f"], "kJ/mol")
self.Sig = MolarEntropy(self.data.at[self.name, "Sig"], "kJ/mol*K")
self.Hstd_c = MolarEnthalpy(self.data.at[self.name, "Hstd_c"], "kJ/mol")
# Critical properties from Perry's handbook
self.Tc = Temperature(self.data.at[self.name, "Tc"], "K")
self.Pc = Pressure(self.data.at[self.name, "Pc"], "MPa")
self.Vmc = MolarVolume(self.data.at[self.name, "Vc"], "m3/kmol")
self.Zc = self.data.at[self.name, "Zc"]
self.acentric = self.data.at[self.name, "Acentric factor"]
else:
self.data = None
def CP_liquid(self, T, Tunits = "K", Report = False, f_output = False):
# Liquid heat capacity, Perrys' handobook method.
# T is a temperature which LCP will be calculated.
# Tunits is the unints for the temperature. This is used for the mean cp method.
# Report is a boolean, if True, then print the result.
# f_output return the function of CP. This is used for the mean cp method
# Convert temperature units into Kelvin.
if isinstance(T,(int, float)):
T = Temperature(T, Tunits)
else:
T.Converter("K")
self.Tc.Converter("K")
# Equation 2 for calculating LCP
eq2 = ["1,2-Butanediol", "1,3-Butanediol", "Carbon monoxide", \
"1,1-Difluoroethane", "Ethane", "Heptane", "Hydrogen", \
"Hydrogen sulfide", "Methane", "Propane"]
# Read parameters from the database
C1 = self.data.loc[self.name, "CPLC1"]
C2 = self.data.loc[self.name, "CPLC2"]
C3 = self.data.loc[self.name, "CPLC3"]
C4 = self.data.loc[self.name, "CPLC4"]
C5 = self.data.loc[self.name, "CPLC5"]
# Equaion 2
if self.name in eq2:
Tr = T.value / self.Tc.value
t = 1- Tr
CPL = (C1 * C1 / t) + C2 - 2 * C1 * C3 * t - C1 * C4 * t * t \
- ((C3 **2) * (t ** 3) / 3) - ((C3 * C4) * (t ** 4) / 2) \
- ((C4 **2) * (t ** 5) / 5)
else:
# Equation 1
CPL = C1 +( C2 * T.value) +( C3 * (T.value**2)) +( C4 * (T.value ** 3)) + (C5 * (T.value ** 4))
self.CPl = MolarHeatCapacity(CPL, 'J/kmol*K')
if Report:
print('The Liquid Heat Capacity of {} is {:,.2f} {}'.format(self.name, self.CPl.value, self.CPl.units))
if f_output:
return CPL
def CP_ig(self, T, Tunits = "K", Report = False, f_output = False):
# Ideal Gas heat capacity, Perrys' handobook method.
# T is a temperature which IGCP will be calculated.
# Tunits is the unints for the temperature. This is used for the mean cp method.
# Report is a boolean, if True, then print the result.
# f_output return the function of CP. This is used for the mean cp method
# Convert temperature units into Kelvin.
if isinstance(T,(int, float)):
T = Temperature(T, Tunits)
else:
T.Converter("K")
self.Tc.Converter("K")
# Equation 2 for calculating LCP
eq2 = ["Argon", "Helium-4", "Neon", "Nitric oxide"]
# Read parameters from the database
C1 = self.data.loc[self.name, "CPGC1"]
C2 = self.data.loc[self.name, "CPGC2"]
C3 = self.data.loc[self.name, "CPGC3"]
C4 = self.data.loc[self.name, "CPGC4"]
C5 = self.data.loc[self.name, "CPGC5"]
# Equaion 2
if self.name in eq2:
CPIG = C1 + C2 * T.value + C3 * T.value ** 2 + C4 * T.value ** 3 + C5 * T.value ** 4
else:
# Equation 1
CPIG = C1 + C2 * pow((C3 / T.value) / (sinh(C3 / T.value)), 2) + C4 * pow((C5 / T.value) / (cosh(C5 / T.value)), 2)
self.CPig = MolarHeatCapacity(CPIG, 'J/kmol*K')
if Report:
print('The Ideal Gas Heat Capacity of {} is {:,.2f} {}'.format(self.name, self.CPig.value, self.CPig.units))
if f_output:
return CPIG
def mean_CP(self, f_CP, T1, T2, units, phase, Report = False):
# This method calculate de mean heat capacity
T1.Converter("K")
T2.Converter("K")
mCP, err = quad(f_CP, T1.value, T2.value, args = (T1.units, False, True))
if phase == "liquid":
self.mCPl = MolarHeatCapacity(mCP / (T2.value - T1.value), units)
if Report:
print('The Mean Liquid Heat Capacity of {} is {:,.2f} {}'.format(self.name, self.mCPl.value, self.mCPlunits))
elif phase == "gas":
self.mCPig = MolarHeatCapacity(mCP / (T2.value - T1.value), units)
if Report:
print('The Mean Ideal Gas Heat Capacity of {} is {:,.2f} {}'.format(self.name, self.mCPig.value, self.mCPig.units))
def Vapor_pressure(self, T, Report = False):
# This method calculates the vapor pressure of a compound.
# T is the temperature for the calculations.
# Report is a boolean for printing the result.
T.Converter("K")
# Read parameters from the database
C1 = float(self.data.loc[self.name, "VPC1"])
C2 = float(self.data.loc[self.name, "VPC2"])
C3 = float(self.data.loc[self.name, "VPC3"])
C4 = float(self.data.loc[self.name, "VPC4"])
C5 = float(self.data.loc[self.name, "VPC5"])
# Equation
Psat = np.exp(C1 + (C2 / T.value) + (C3 * np.log(T.value)) + C4 * (T.value ** C5))
self.Pvap = Pressure(Psat, 'Pa')
if Report:
print('The Vapor Pressure of {} is {:,.0f} {}'.format(self.name, self.Pvap.value, self.Pvap.units))
|
{"/compound.py": ["/simulator.py", "/units.py"], "/main.py": ["/simulator.py", "/compound.py"], "/mixture.py": ["/compound.py", "/simulator.py"]}
|
22,540,768
|
alfonsoamt/Process_Egineering_Simulator
|
refs/heads/main
|
/reaction.py
|
# -*- coding: utf-8 -*-
"""
Created on Sun Apr 18 18:22:53 2021
@author: alfon
"""
class Chemical_Reaction:
pass
|
{"/compound.py": ["/simulator.py", "/units.py"], "/main.py": ["/simulator.py", "/compound.py"], "/mixture.py": ["/compound.py", "/simulator.py"]}
|
22,585,400
|
thuan20132000/python_vieclam24h_v2
|
refs/heads/main
|
/ecommerce/admin.py
|
from django.contrib import admin
# Register your models here.
from .models import Product,Category
@admin.register(Category)
class CaregoryAdmin(admin.ModelAdmin):
list_display = ['name','slug','status']
list_editable = ['status']
prepopulated_fields = {'slug':('name',)}
@admin.register(Product)
class ProductAdmin(admin.ModelAdmin):
list_display = ['name','slug','price','created_at','updated_at','status']
list_filter = ['created_at','updated_at']
list_editable = ['price','status']
prepopulated_fields = {'slug':('name',)}
|
{"/dictionary/search.py": ["/dictionary/searchbase.py"], "/ecommerce/admin.py": ["/ecommerce/models.py"], "/ecommerce/views.py": ["/ecommerce/models.py"], "/ecommerce/tests.py": ["/ecommerce/models.py"]}
|
22,585,401
|
thuan20132000/python_vieclam24h_v2
|
refs/heads/main
|
/ecommerce/views.py
|
from django.shortcuts import render,get_object_or_404
# Create your views here.
from .models import Category,Product
def product_list(request,category_slug=None):
category = None
categories = Category.objects.all()
products = Product.objects.filter(status='published')
if category_slug:
category = get_object_or_404(Category,slug=category_slug)
products = products.filter(category=category)
return render(request,
'ecommerce/product/list.html',
{
'category':category,
'categories':categories,
'products':products
})
def product_detail(request,id,slug):
product = get_object_or_404(
Product,
id=id,
slug=slug,
status='published'
)
return render(
request,
'ecommerce/product/detail.html',
{'product':product}
)
|
{"/dictionary/search.py": ["/dictionary/searchbase.py"], "/ecommerce/admin.py": ["/ecommerce/models.py"], "/ecommerce/views.py": ["/ecommerce/models.py"], "/ecommerce/tests.py": ["/ecommerce/models.py"]}
|
22,585,402
|
thuan20132000/python_vieclam24h_v2
|
refs/heads/main
|
/ecommerce/tests.py
|
from django.test import TestCase
# Create your tests here.
from .models import Category,Product
class CategoryTest(TestCase):
def setUp(self):
for i in range(10):
self.category = Category.objects.create(
name=f"name {i}",
description=f"description {i}",
is_active=True,
meta_keywords=f"Me ta keyworlds",
meta_description=f"Meta description",
)
|
{"/dictionary/search.py": ["/dictionary/searchbase.py"], "/ecommerce/admin.py": ["/ecommerce/models.py"], "/ecommerce/views.py": ["/ecommerce/models.py"], "/ecommerce/tests.py": ["/ecommerce/models.py"]}
|
22,585,403
|
thuan20132000/python_vieclam24h_v2
|
refs/heads/main
|
/ecommerce/models.py
|
from django.db import models
from django.conf import settings
from django.urls import reverse
# Create your models here.
class Category(models.Model):
STATUS_CHOICE = (
("pending","Pending"),
("draft","Draft"),
("published",'Published')
)
name = models.CharField(max_length=50)
slug = models.SlugField(max_length=50,unique=True)
description = models.TextField()
is_active = models.BooleanField(default=True)
meta_keywords = models.CharField("Meta Keywords",max_length=255,help_text="Comma-delimited set of SEO keywords for meta tag")
meta_description = models.CharField("Meta Description",max_length=255,help_text="Content for description meta tag")
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
status = models.TextField(choices=STATUS_CHOICE,default="pending")
class Meta:
ordering = ['name']
verbose_name_plural = 'Categories'
verbose_name = 'category'
def __str__(self):
return self.name
def get_absolute_url(self):
return reverse('ecommerce:product_list_by_category',args=[self.slug])
class Product(models.Model):
STATUS_CHOICE = (
("pending","Pending"),
("draft","Draft"),
("published",'Published')
)
name = models.CharField(max_length=255,unique=True)
slug = models.SlugField(max_length=255,unique=True,help_text='Unique value for product page URL, create from name')
brand = models.CharField(max_length=50)
price = models.DecimalField(max_digits=9,decimal_places=2)
old_price = models.DecimalField(max_digits=9,decimal_places=2,blank=True,default=0.00)
image = models.ImageField(upload_to='upload/ecommerce')
is_active = models.BooleanField(default=True)
is_bestller = models.BooleanField(default=False)
quantity = models.IntegerField()
description = models.TextField()
meta_keywords = models.CharField("Meta Keywords",max_length=255,help_text="Comma-delimited set of SEO keywords for meta tag")
meta_description = models.CharField("Meta Description",max_length=255,help_text="Content for description meta tag")
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
status = models.TextField(choices=STATUS_CHOICE,default="pending")
categories = models.ForeignKey(
Category,
related_name='products',
on_delete=models.CASCADE
)
class Meta:
ordering = ['-created_at']
index_together = (('id','slug'))
def __str__(self):
return self.name
def get_absolute_url(self):
return reverse('ecommerce:product_detail',args=[self.id,self.slug])
|
{"/dictionary/search.py": ["/dictionary/searchbase.py"], "/ecommerce/admin.py": ["/ecommerce/models.py"], "/ecommerce/views.py": ["/ecommerce/models.py"], "/ecommerce/tests.py": ["/ecommerce/models.py"]}
|
22,585,404
|
thuan20132000/python_vieclam24h_v2
|
refs/heads/main
|
/blog/migrations/0003_auto_20210209_0213.py
|
# Generated by Django 3.1.4 on 2021-02-09 02:13
from django.db import migrations, models
import django_quill.fields
class Migration(migrations.Migration):
dependencies = [
('blog', '0002_categorytype_category'),
]
operations = [
migrations.AddField(
model_name='post',
name='image',
field=models.ImageField(blank=True, upload_to='upload/blog/'),
),
migrations.AlterField(
model_name='post',
name='content',
field=django_quill.fields.QuillField(),
),
]
|
{"/dictionary/search.py": ["/dictionary/searchbase.py"], "/ecommerce/admin.py": ["/ecommerce/models.py"], "/ecommerce/views.py": ["/ecommerce/models.py"], "/ecommerce/tests.py": ["/ecommerce/models.py"]}
|
22,585,405
|
thuan20132000/python_vieclam24h_v2
|
refs/heads/main
|
/blog/migrations/0004_auto_20210212_1658.py
|
# Generated by Django 3.1.4 on 2021-02-12 16:58
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('blog', '0003_auto_20210209_0213'),
]
operations = [
migrations.RemoveField(
model_name='comment',
name='author',
),
migrations.RemoveField(
model_name='comment',
name='title',
),
migrations.AddField(
model_name='comment',
name='email',
field=models.EmailField(default=1, max_length=250),
preserve_default=False,
),
]
|
{"/dictionary/search.py": ["/dictionary/searchbase.py"], "/ecommerce/admin.py": ["/ecommerce/models.py"], "/ecommerce/views.py": ["/ecommerce/models.py"], "/ecommerce/tests.py": ["/ecommerce/models.py"]}
|
22,663,446
|
alanking/python-irodsclient
|
refs/heads/master
|
/irods/pool.py
|
from __future__ import absolute_import
import datetime
import logging
import threading
import os
from irods import DEFAULT_CONNECTION_TIMEOUT
from irods.connection import Connection
logger = logging.getLogger(__name__)
DEFAULT_APPLICATION_NAME = 'python-irodsclient'
class Pool(object):
def __init__(self, account, application_name='', connection_refresh_time=-1):
'''
Pool( account , application_name='' )
Create an iRODS connection pool; 'account' is an irods.account.iRODSAccount instance and
'application_name' specifies the application name as it should appear in an 'ips' listing.
'''
self.account = account
self._lock = threading.RLock()
self.active = set()
self.idle = set()
self.connection_timeout = DEFAULT_CONNECTION_TIMEOUT
self.application_name = ( os.environ.get('spOption','') or
application_name or
DEFAULT_APPLICATION_NAME )
if connection_refresh_time > 0:
self.refresh_connection = True
self.connection_refresh_time = connection_refresh_time
else:
self.refresh_connection = False
self.connection_refresh_time = None
def get_connection(self):
with self._lock:
try:
conn = self.idle.pop()
curr_time = datetime.datetime.now()
# If 'refresh_connection' flag is True and the connection was
# created more than 'connection_refresh_time' seconds ago,
# release the connection (as its stale) and create a new one
if self.refresh_connection and (curr_time - conn.create_time).total_seconds() > self.connection_refresh_time:
logger.debug('Connection with id {} was created more than {} seconds ago. Releasing the connection and creating a new one.'.format(id(conn), self.connection_refresh_time))
self.release_connection(conn, True)
conn = Connection(self, self.account)
logger.debug("Created new connection with id: {}".format(id(conn)))
except KeyError:
conn = Connection(self, self.account)
logger.debug("No connection found in idle set. Created a new connection with id: {}".format(id(conn)))
self.active.add(conn)
logger.debug("Adding connection with id {} to active set".format(id(conn)))
logger.debug('num active: {}'.format(len(self.active)))
logger.debug('num idle: {}'.format(len(self.idle)))
return conn
def release_connection(self, conn, destroy=False):
with self._lock:
if conn in self.active:
self.active.remove(conn)
logger.debug("Removed connection with id: {} from active set".format(id(conn)))
if not destroy:
# If 'refresh_connection' flag is True, update connection's 'last_used_time'
if self.refresh_connection:
conn.last_used_time = datetime.datetime.now()
self.idle.add(conn)
logger.debug("Added connection with id: {} to idle set".format(id(conn)))
elif conn in self.idle and destroy:
logger.debug("Destroyed connection with id: {}".format(id(conn)))
self.idle.remove(conn)
logger.debug('num active: {}'.format(len(self.active)))
logger.debug('num idle: {}'.format(len(self.idle)))
|
{"/irods/test/query_test.py": ["/irods/column.py", "/irods/rule.py", "/irods/test/helpers.py"], "/irods/session.py": ["/irods/pool.py", "/irods/manager/data_object_manager.py", "/irods/manager/user_manager.py"], "/irods/pool.py": ["/irods/connection.py"], "/irods/test/user_group_test.py": ["/irods/test/helpers.py"], "/irods/test/helpers.py": ["/irods/session.py"], "/irods/test/meta_test.py": ["/irods/test/helpers.py"], "/irods/test/pool_test.py": ["/irods/test/helpers.py"], "/irods/test/login_auth_test.py": ["/irods/test/helpers.py", "/irods/connection.py", "/irods/session.py", "/irods/rule.py"], "/irods/test/rule_test.py": ["/irods/test/helpers.py", "/irods/rule.py"], "/irods/manager/user_manager.py": ["/irods/user.py"]}
|
22,663,447
|
alanking/python-irodsclient
|
refs/heads/master
|
/irods/user.py
|
from __future__ import absolute_import
from irods.models import User, UserGroup, UserAuth
from irods.meta import iRODSMetaCollection
from irods.exception import NoResultFound
class iRODSUser(object):
def __init__(self, manager, result=None):
self.manager = manager
if result:
self.id = result[User.id]
self.name = result[User.name]
self.type = result[User.type]
self.zone = result[User.zone]
self._meta = None
@property
def dn(self):
query = self.manager.sess.query(UserAuth.user_dn).filter(UserAuth.user_id == self.id)
return [res[UserAuth.user_dn] for res in query]
@property
def metadata(self):
if not self._meta:
self._meta = iRODSMetaCollection(
self.manager.sess.metadata, User, self.name)
return self._meta
def modify(self, *args, **kwargs):
self.manager.modify(self.name, *args, **kwargs)
def __repr__(self):
return "<iRODSUser {id} {name} {type} {zone}>".format(**vars(self))
def remove(self):
self.manager.remove(self.name, self.zone)
class iRODSUserGroup(object):
def __init__(self, manager, result=None):
self.manager = manager
if result:
self.id = result[UserGroup.id]
self.name = result[UserGroup.name]
self._meta = None
def __repr__(self):
return "<iRODSUserGroup {id} {name}>".format(**vars(self))
def remove(self):
self.manager.remove(self.name)
@property
def members(self):
return self.manager.getmembers(self.name)
@property
def metadata(self):
if not self._meta:
self._meta = iRODSMetaCollection(
self.manager.sess.metadata, User, self.name)
return self._meta
def addmember(self, user_name, user_zone=""):
self.manager.addmember(self.name, user_name, user_zone)
def removemember(self, user_name, user_zone=""):
self.manager.removemember(self.name, user_name, user_zone)
def hasmember(self, user_name):
member_names = [user.name for user in self.members]
return user_name in member_names
|
{"/irods/test/query_test.py": ["/irods/column.py", "/irods/rule.py", "/irods/test/helpers.py"], "/irods/session.py": ["/irods/pool.py", "/irods/manager/data_object_manager.py", "/irods/manager/user_manager.py"], "/irods/pool.py": ["/irods/connection.py"], "/irods/test/user_group_test.py": ["/irods/test/helpers.py"], "/irods/test/helpers.py": ["/irods/session.py"], "/irods/test/meta_test.py": ["/irods/test/helpers.py"], "/irods/test/pool_test.py": ["/irods/test/helpers.py"], "/irods/test/login_auth_test.py": ["/irods/test/helpers.py", "/irods/connection.py", "/irods/session.py", "/irods/rule.py"], "/irods/test/rule_test.py": ["/irods/test/helpers.py", "/irods/rule.py"], "/irods/manager/user_manager.py": ["/irods/user.py"]}
|
22,663,448
|
alanking/python-irodsclient
|
refs/heads/master
|
/irods/test/user_group_test.py
|
#! /usr/bin/env python
from __future__ import absolute_import
import os
import sys
import unittest
from irods.exception import UserGroupDoesNotExist
from irods.meta import iRODSMetaCollection, iRODSMeta
from irods.models import User, UserGroup, UserMeta
import irods.test.helpers as helpers
from six.moves import range
class TestUserGroup(unittest.TestCase):
def setUp(self):
self.sess = helpers.make_session()
def tearDown(self):
'''Close connections
'''
self.sess.cleanup()
def test_create_group(self):
group_name = "test_group"
# group should not be already present
with self.assertRaises(UserGroupDoesNotExist):
self.sess.user_groups.get(group_name)
# create group
group = self.sess.user_groups.create(group_name)
# assertions
self.assertEqual(group.name, group_name)
self.assertEqual(
repr(group), "<iRODSUserGroup {0} {1}>".format(group.id, group_name))
# delete group
group.remove()
# group should be gone
with self.assertRaises(UserGroupDoesNotExist):
self.sess.user_groups.get(group_name)
def test_add_users_to_group(self):
group_name = "test_group"
group_size = 15
base_user_name = "test_user"
# group should not be already present
with self.assertRaises(UserGroupDoesNotExist):
self.sess.user_groups.get(group_name)
# create test group
group = self.sess.user_groups.create(group_name)
# create test users names
test_user_names = []
for i in range(group_size):
test_user_names.append(base_user_name + str(i))
# make test users and add them to test group
for test_user_name in test_user_names:
user = self.sess.users.create(test_user_name, 'rodsuser')
group.addmember(user.name)
# list group members
member_names = [user.name for user in group.members]
# compare lists
self.assertSetEqual(set(member_names), set(test_user_names))
# exercise iRODSUserGroup.hasmember()
for test_user_name in test_user_names:
self.assertTrue(group.hasmember(test_user_name))
# remove test users from group and delete them
for test_user_name in test_user_names:
user = self.sess.users.get(test_user_name)
group.removemember(user.name)
user.remove()
# delete group
group.remove()
# group should be gone
with self.assertRaises(UserGroupDoesNotExist):
self.sess.user_groups.get(group_name)
def test_user_dn(self):
# https://github.com/irods/irods/issues/3620
if self.sess.server_version == (4, 2, 1):
self.skipTest('Broken in 4.2.1')
user_name = "testuser"
user_DNs = ['foo', 'bar']
# create user
user = self.sess.users.create(user_name, 'rodsuser')
# expect no dn
self.assertEqual(user.dn, [])
# add dn
user.modify('addAuth', user_DNs[0])
self.assertEqual(user.dn[0], user_DNs[0])
# add other dn
user.modify('addAuth', user_DNs[1])
self.assertEqual( sorted(user.dn), sorted(user_DNs) )
# remove first dn
user.modify('rmAuth', user_DNs[0])
# confirm removal
self.assertEqual(sorted(user.dn), sorted(user_DNs[1:]))
# delete user
user.remove()
def test_group_metadata(self):
group_name = "test_group"
# group should not be already present
with self.assertRaises(UserGroupDoesNotExist):
self.sess.user_groups.get(group_name)
group = None
try:
# create group
group = self.sess.user_groups.create(group_name)
# add metadata to group
triple = ['key', 'value', 'unit']
group.metadata[triple[0]] = iRODSMeta(*triple)
result = self.sess.query(UserMeta, UserGroup).filter(UserGroup.name == group_name,
UserMeta.name == 'key').one()
self.assertTrue([result[k] for k in (UserMeta.name, UserMeta.value, UserMeta.units)] == triple)
finally:
if group:
group.remove()
helpers.remove_unused_metadata(self.sess)
def test_user_metadata(self):
user_name = "testuser"
user = None
try:
user = self.sess.users.create(user_name, 'rodsuser')
# metadata collection is the right type?
self.assertIsInstance(user.metadata, iRODSMetaCollection)
# add three AVUs, two having the same key
user.metadata['key0'] = iRODSMeta('key0', 'value', 'units')
sorted_triples = sorted( [ ['key1', 'value0', 'units0'],
['key1', 'value1', 'units1'] ] )
for m in sorted_triples:
user.metadata.add(iRODSMeta(*m))
# general query gives the right results?
result_0 = self.sess.query(UserMeta, User)\
.filter( User.name == user_name, UserMeta.name == 'key0').one()
self.assertTrue( [result_0[k] for k in (UserMeta.name, UserMeta.value, UserMeta.units)]
== ['key0', 'value', 'units'] )
results_1 = self.sess.query(UserMeta, User)\
.filter(User.name == user_name, UserMeta.name == 'key1')
retrieved_triples = [ [ res[k] for k in (UserMeta.name, UserMeta.value, UserMeta.units) ]
for res in results_1
]
self.assertTrue( sorted_triples == sorted(retrieved_triples))
finally:
if user:
user.remove()
helpers.remove_unused_metadata(self.sess)
def test_get_user_metadata(self):
user_name = "testuser"
user = None
try:
# create user
user = self.sess.users.create(user_name, 'rodsuser')
meta = user.metadata.get_all('key')
# There should be no metadata
self.assertEqual(len(meta), 0)
finally:
if user: user.remove()
def test_add_user_metadata(self):
user_name = "testuser"
user = None
try:
# create user
user = self.sess.users.create(user_name, 'rodsuser')
user.metadata.add('key0', 'value0')
user.metadata.add('key1', 'value1', 'unit1')
user.metadata.add('key2', 'value2a', 'unit2')
user.metadata.add('key2', 'value2b', 'unit2')
meta0 = user.metadata.get_all('key0')
self.assertEqual(len(meta0),1)
self.assertEqual(meta0[0].name, 'key0')
self.assertEqual(meta0[0].value, 'value0')
meta1 = user.metadata.get_all('key1')
self.assertEqual(len(meta1),1)
self.assertEqual(meta1[0].name, 'key1')
self.assertEqual(meta1[0].value, 'value1')
self.assertEqual(meta1[0].units, 'unit1')
meta2 = sorted(user.metadata.get_all('key2'), key = lambda AVU : AVU.value)
self.assertEqual(len(meta2),2)
self.assertEqual(meta2[0].name, 'key2')
self.assertEqual(meta2[0].value, 'value2a')
self.assertEqual(meta2[0].units, 'unit2')
self.assertEqual(meta2[1].name, 'key2')
self.assertEqual(meta2[1].value, 'value2b')
self.assertEqual(meta2[1].units, 'unit2')
user.metadata.remove('key1', 'value1', 'unit1')
metadata = user.metadata.items()
self.assertEqual(len(metadata), 3)
user.metadata.remove('key2', 'value2a', 'unit2')
metadata = user.metadata.items()
self.assertEqual(len(metadata), 2)
finally:
if user:
user.remove()
helpers.remove_unused_metadata(self.sess)
if __name__ == '__main__':
# let the tests find the parent irods lib
sys.path.insert(0, os.path.abspath('../..'))
unittest.main()
|
{"/irods/test/query_test.py": ["/irods/column.py", "/irods/rule.py", "/irods/test/helpers.py"], "/irods/session.py": ["/irods/pool.py", "/irods/manager/data_object_manager.py", "/irods/manager/user_manager.py"], "/irods/pool.py": ["/irods/connection.py"], "/irods/test/user_group_test.py": ["/irods/test/helpers.py"], "/irods/test/helpers.py": ["/irods/session.py"], "/irods/test/meta_test.py": ["/irods/test/helpers.py"], "/irods/test/pool_test.py": ["/irods/test/helpers.py"], "/irods/test/login_auth_test.py": ["/irods/test/helpers.py", "/irods/connection.py", "/irods/session.py", "/irods/rule.py"], "/irods/test/rule_test.py": ["/irods/test/helpers.py", "/irods/rule.py"], "/irods/manager/user_manager.py": ["/irods/user.py"]}
|
22,663,449
|
alanking/python-irodsclient
|
refs/heads/master
|
/irods/test/helpers.py
|
from __future__ import absolute_import
import os
import io
import tempfile
import contextlib
import shutil
import hashlib
import base64
import math
from pwd import getpwnam
from irods.session import iRODSSession
from irods.message import iRODSMessage
from six.moves import range
def make_session(**kwargs):
try:
env_file = kwargs['irods_env_file']
except KeyError:
try:
env_file = os.environ['IRODS_ENVIRONMENT_FILE']
except KeyError:
env_file = os.path.expanduser('~/.irods/irods_environment.json')
try:
os.environ['IRODS_CI_TEST_RUN']
uid = getpwnam('irods').pw_uid
except KeyError:
uid = None
return iRODSSession(irods_authentication_uid=uid, irods_env_file=env_file)
def make_object(session, path, content=None, **options):
if content is None:
content = u'blah'
content = iRODSMessage.encode_unicode(content)
# 2 step open-create necessary for iRODS 4.1.4 or older
obj = session.data_objects.create(path)
with obj.open('w', **options) as obj_desc:
obj_desc.write(content)
# refresh object after write
return session.data_objects.get(path)
def make_collection(session, path, object_names=None, object_content=None):
# create collection
coll = session.collections.create(path)
# create objects
if object_names:
for name in object_names:
obj_path = os.path.join(path, name)
make_object(session, obj_path, content=object_content)
return coll
def make_test_collection(session, path, obj_count):
coll = session.collections.create(path)
for n in range(obj_count):
obj_path = path + "/test" + str(n).zfill(6) + ".txt"
make_object(session, obj_path)
return coll
def make_deep_collection(session, root_path, depth=10, objects_per_level=50, object_content=None):
# start at root path
current_coll_path = root_path
# make collections recursively
for d in range(depth):
# make list of object names
obj_names = ['obj' + str(i).zfill(len(str(objects_per_level)))
for i in range(objects_per_level)]
# make subcollection and objects
if d == 0:
root_coll = make_collection(
session, current_coll_path, obj_names, object_content)
else:
make_collection(
session, current_coll_path, obj_names, object_content)
# next level down
current_coll_path = os.path.join(
current_coll_path, 'subcoll' + str(d).zfill(len(str(d))))
return root_coll
def make_flat_test_dir(dir_path, file_count=10, file_size=1024):
if file_count < 1:
raise ValueError
os.mkdir(dir_path)
for i in range(file_count):
# pad file name suffix with zeroes
suffix_width = int(math.log10(file_count))+1
file_path = '{dir_path}/test_{i:0>{suffix_width}}.txt'.format(**locals())
# make random binary file
with open(file_path, 'wb') as f:
f.write(os.urandom(file_size))
def chunks(f, chunksize=io.DEFAULT_BUFFER_SIZE):
return iter(lambda: f.read(chunksize), b'')
def compute_sha256_digest(file_path):
hasher = hashlib.sha256()
with open(file_path, 'rb') as f:
for chunk in chunks(f):
hasher.update(chunk)
return base64.b64encode(hasher.digest()).decode()
def remove_unused_metadata(session):
from irods.message import GeneralAdminRequest
from irods.api_number import api_number
message_body = GeneralAdminRequest( 'rm', 'unusedAVUs', '','','','')
req = iRODSMessage("RODS_API_REQ", msg = message_body,int_info=api_number['GENERAL_ADMIN_AN'])
with session.pool.get_connection() as conn:
conn.send(req)
response=conn.recv()
if (response.int_info != 0): raise RuntimeError("Error removing unused AVUs")
@contextlib.contextmanager
def file_backed_up(filename):
with tempfile.NamedTemporaryFile(prefix=os.path.basename(filename)) as f:
shutil.copyfile(filename, f.name)
try:
yield filename
finally:
shutil.copyfile(f.name, filename)
|
{"/irods/test/query_test.py": ["/irods/column.py", "/irods/rule.py", "/irods/test/helpers.py"], "/irods/session.py": ["/irods/pool.py", "/irods/manager/data_object_manager.py", "/irods/manager/user_manager.py"], "/irods/pool.py": ["/irods/connection.py"], "/irods/test/user_group_test.py": ["/irods/test/helpers.py"], "/irods/test/helpers.py": ["/irods/session.py"], "/irods/test/meta_test.py": ["/irods/test/helpers.py"], "/irods/test/pool_test.py": ["/irods/test/helpers.py"], "/irods/test/login_auth_test.py": ["/irods/test/helpers.py", "/irods/connection.py", "/irods/session.py", "/irods/rule.py"], "/irods/test/rule_test.py": ["/irods/test/helpers.py", "/irods/rule.py"], "/irods/manager/user_manager.py": ["/irods/user.py"]}
|
22,663,450
|
alanking/python-irodsclient
|
refs/heads/master
|
/irods/test/meta_test.py
|
#! /usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import absolute_import
import os
import sys
import unittest
from irods.meta import iRODSMeta
from irods.models import DataObject, Collection, Resource
import irods.test.helpers as helpers
from six.moves import range
class TestMeta(unittest.TestCase):
'''Suite of tests on metadata operations
'''
# test metadata
attr0, value0, unit0 = 'attr0', 'value0', 'unit0'
attr1, value1, unit1 = 'attr1', 'value1', 'unit1'
def setUp(self):
self.sess = helpers.make_session()
# test data
self.coll_path = '/{}/home/{}/test_dir'.format(self.sess.zone, self.sess.username)
self.obj_name = 'test1'
self.obj_path = '{coll_path}/{obj_name}'.format(**vars(self))
# Create test collection and (empty) test object
self.coll = self.sess.collections.create(self.coll_path)
self.obj = self.sess.data_objects.create(self.obj_path)
def tearDown(self):
'''Remove test data and close connections
'''
self.coll.remove(recurse=True, force=True)
self.sess.cleanup()
def test_get_obj_meta(self):
# get object metadata
meta = self.sess.metadata.get(DataObject, self.obj_path)
# there should be no metadata at this point
assert len(meta) == 0
def test_resc_meta(self):
rescname = 'demoResc'
self.sess.resources.get(rescname).metadata.remove_all()
self.sess.metadata.set(Resource, rescname, iRODSMeta('zero','marginal','cost'))
self.sess.metadata.add(Resource, rescname, iRODSMeta('zero','marginal'))
self.sess.metadata.set(Resource, rescname, iRODSMeta('for','ever','after'))
meta = self.sess.resources.get(rescname).metadata
self.assertTrue( len(meta) == 3 )
resource = self.sess.resources.get(rescname)
all_AVUs= resource.metadata.items()
for avu in all_AVUs:
resource.metadata.remove(avu)
self.assertTrue(0 == len(self.sess.resources.get(rescname).metadata))
def test_add_obj_meta(self):
# add metadata to test object
self.sess.metadata.add(DataObject, self.obj_path,
iRODSMeta(self.attr0, self.value0))
self.sess.metadata.add(DataObject, self.obj_path,
iRODSMeta(self.attr1, self.value1, self.unit1))
# Throw in some unicode for good measure
attribute, value = 'attr2', u'☭⛷★⚽'
self.sess.metadata.add(DataObject, self.obj_path,
iRODSMeta(attribute, value))
# get object metadata
meta = self.sess.metadata.get(DataObject, self.obj_path)
# sort results by metadata id
def getKey(AVU):
return AVU.avu_id
meta = sorted(meta, key=getKey)
# assertions
assert meta[0].name == self.attr0
assert meta[0].value == self.value0
assert meta[1].name == self.attr1
assert meta[1].value == self.value1
assert meta[1].units == self.unit1
assert meta[2].name == attribute
assert meta[2].value == value
def test_add_obj_meta_empty(self):
'''Should raise exception
'''
# try to add metadata with empty value
with self.assertRaises(ValueError):
self.sess.metadata.add(DataObject, self.obj_path,
iRODSMeta('attr_with_empty_value', ''))
def test_copy_obj_meta(self):
# test destination object for copy
dest_obj_path = self.coll_path + '/test2'
self.sess.data_objects.create(dest_obj_path)
# add metadata to test object
self.sess.metadata.add(DataObject, self.obj_path,
iRODSMeta(self.attr0, self.value0))
# copy metadata
self.sess.metadata.copy(
DataObject, DataObject, self.obj_path, dest_obj_path)
# get destination object metadata
dest_meta = self.sess.metadata.get(DataObject, dest_obj_path)
# check metadata
assert dest_meta[0].name == self.attr0
def test_remove_obj_meta(self):
# add metadata to test object
self.sess.metadata.add(DataObject, self.obj_path,
iRODSMeta(self.attr0, self.value0))
# check that metadata is there
meta = self.sess.metadata.get(DataObject, self.obj_path)
assert meta[0].name == self.attr0
# remove metadata from object
self.sess.metadata.remove(DataObject, self.obj_path,
iRODSMeta(self.attr0, self.value0))
# check that metadata is gone
meta = self.sess.metadata.get(DataObject, self.obj_path)
assert len(meta) == 0
def test_add_coll_meta(self):
# add metadata to test collection
self.sess.metadata.add(Collection, self.coll_path,
iRODSMeta(self.attr0, self.value0))
# get collection metadata
meta = self.sess.metadata.get(Collection, self.coll_path)
# assertions
assert meta[0].name == self.attr0
assert meta[0].value == self.value0
# remove collection metadata
self.sess.metadata.remove(Collection, self.coll_path,
iRODSMeta(self.attr0, self.value0))
# check that metadata is gone
meta = self.sess.metadata.get(Collection, self.coll_path)
assert len(meta) == 0
def test_meta_repr(self):
# test obj
collection = self.coll_path
filename = 'test_meta_repr.txt'
test_obj_path = '{collection}/{filename}'.format(**locals())
# make object
obj = helpers.make_object(self.sess, test_obj_path)
# test AVU
attribute, value, units = ('test_attr', 'test_value', 'test_units')
# add metadata to test object
meta = self.sess.metadata.add(DataObject, test_obj_path,
iRODSMeta(attribute, value, units))
# get metadata
meta = self.sess.metadata.get(DataObject, test_obj_path)
avu_id = meta[0].avu_id
# assert
self.assertEqual(
repr(meta[0]), "<iRODSMeta {avu_id} {attribute} {value} {units}>".format(**locals()))
# remove test object
obj.unlink(force=True)
def test_irodsmetacollection_data_obj(self):
'''
Tested as data_object metadata
'''
# test settings
avu_count = 5
# make test object
test_obj_path = self.coll_path + '/test_irodsmetacollection'
test_obj = helpers.make_object(self.sess, test_obj_path)
# test AVUs
triplets = [('test_attr' + str(i), 'test_value', 'test_units')
for i in range(avu_count)]
# get coll meta
imc = test_obj.metadata
# try invalid key
with self.assertRaises(KeyError):
imc.get_one('bad_key')
# invalid key type
with self.assertRaises(TypeError):
imc.get_one(list())
# try empty update values
with self.assertRaises(ValueError):
imc.add()
# add AVUs
for triplet in triplets:
imc.add(*triplet)
# add another AVU with existing attribute name
attr_name = triplets[0][0]
duplicate_triplet = (attr_name, 'other_value', 'test_units')
imc.add(*duplicate_triplet)
# get_one should fail
with self.assertRaises(KeyError):
imc.get_one(attr_name)
# remove triplet
imc.remove(*duplicate_triplet)
imc.get_one(attr_name)
# get keys
for key in imc.keys():
self.assertIn(key, [triplet[0] for triplet in triplets])
# get items
for avu in imc.items():
self.assertIsInstance(avu, iRODSMeta)
self.assertIn(avu.name, [triplet[0] for triplet in triplets])
self.assertIn(avu.value, [triplet[1] for triplet in triplets])
self.assertIn(avu.units, [triplet[2] for triplet in triplets])
# try contains
self.assertIn(triplets[0][0], imc)
# try contains with bad key type
with self.assertRaises(TypeError):
_ = (int() in imc)
# set item
imc[attr_name] = iRODSMeta(attr_name, 'boo')
# get item
_ = imc[attr_name]
# del item with bad key type
with self.assertRaises(TypeError):
del imc[int()]
# del item
del imc[attr_name]
with self.assertRaises(KeyError):
_ = imc[attr_name]
# remove all metadta
imc.remove_all()
self.assertEqual(len(imc), 0)
# remove test collection
test_obj.unlink(force=True)
if __name__ == '__main__':
# let the tests find the parent irods lib
sys.path.insert(0, os.path.abspath('../..'))
unittest.main()
|
{"/irods/test/query_test.py": ["/irods/column.py", "/irods/rule.py", "/irods/test/helpers.py"], "/irods/session.py": ["/irods/pool.py", "/irods/manager/data_object_manager.py", "/irods/manager/user_manager.py"], "/irods/pool.py": ["/irods/connection.py"], "/irods/test/user_group_test.py": ["/irods/test/helpers.py"], "/irods/test/helpers.py": ["/irods/session.py"], "/irods/test/meta_test.py": ["/irods/test/helpers.py"], "/irods/test/pool_test.py": ["/irods/test/helpers.py"], "/irods/test/login_auth_test.py": ["/irods/test/helpers.py", "/irods/connection.py", "/irods/session.py", "/irods/rule.py"], "/irods/test/rule_test.py": ["/irods/test/helpers.py", "/irods/rule.py"], "/irods/manager/user_manager.py": ["/irods/user.py"]}
|
22,663,451
|
alanking/python-irodsclient
|
refs/heads/master
|
/setup.py
|
from setuptools import setup, find_packages
import codecs
import os
# Get package version
version = {}
here = os.path.abspath(os.path.dirname(__file__))
with open(os.path.join(here, 'irods/version.py')) as file:
exec(file.read(), version)
# Get description
with codecs.open('README.rst', 'r', 'utf-8') as file:
long_description = file.read()
setup(name='python-irodsclient',
version=version['__version__'],
author='iRODS Consortium',
author_email='support@irods.org',
description='A python API for iRODS',
long_description=long_description,
long_description_content_type='text/x-rst',
license='BSD',
url='https://github.com/irods/python-irodsclient',
keywords='irods',
classifiers=[
'License :: OSI Approved :: BSD License',
'Development Status :: 4 - Beta',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Operating System :: POSIX :: Linux',
],
packages=find_packages(),
include_package_data=True,
install_requires=[
'six>=1.10.0',
'PrettyTable>=0.7.2',
'xmlrunner>=1.7.7'
]
)
|
{"/irods/test/query_test.py": ["/irods/column.py", "/irods/rule.py", "/irods/test/helpers.py"], "/irods/session.py": ["/irods/pool.py", "/irods/manager/data_object_manager.py", "/irods/manager/user_manager.py"], "/irods/pool.py": ["/irods/connection.py"], "/irods/test/user_group_test.py": ["/irods/test/helpers.py"], "/irods/test/helpers.py": ["/irods/session.py"], "/irods/test/meta_test.py": ["/irods/test/helpers.py"], "/irods/test/pool_test.py": ["/irods/test/helpers.py"], "/irods/test/login_auth_test.py": ["/irods/test/helpers.py", "/irods/connection.py", "/irods/session.py", "/irods/rule.py"], "/irods/test/rule_test.py": ["/irods/test/helpers.py", "/irods/rule.py"], "/irods/manager/user_manager.py": ["/irods/user.py"]}
|
22,663,452
|
alanking/python-irodsclient
|
refs/heads/master
|
/irods/test/pool_test.py
|
#! /usr/bin/env python
from __future__ import absolute_import
import datetime
import os
import sys
import time
import unittest
import irods.test.helpers as helpers
class TestPool(unittest.TestCase):
def setUp(self):
self.sess = helpers.make_session(irods_env_file="./test-data/irods_environment.json")
def tearDown(self):
'''Close connections
'''
self.sess.cleanup()
def test_release_connection(self):
with self.sess.pool.get_connection():
self.assertEqual(1, len(self.sess.pool.active))
self.assertEqual(0, len(self.sess.pool.idle))
self.assertEqual(0, len(self.sess.pool.active))
self.assertEqual(1, len(self.sess.pool.idle))
def test_destroy_active(self):
with self.sess.pool.get_connection() as conn:
self.assertEqual(1, len(self.sess.pool.active))
self.assertEqual(0, len(self.sess.pool.idle))
conn.release(destroy=True)
self.assertEqual(0, len(self.sess.pool.active))
self.assertEqual(0, len(self.sess.pool.idle))
def test_destroy_idle(self):
with self.sess.pool.get_connection():
self.assertEqual(1, len(self.sess.pool.active))
self.assertEqual(0, len(self.sess.pool.idle))
# cleanup all connections
self.sess.cleanup()
self.assertEqual(0, len(self.sess.pool.active))
self.assertEqual(0, len(self.sess.pool.idle))
def test_release_disconnected(self):
with self.sess.pool.get_connection() as conn:
self.assertEqual(1, len(self.sess.pool.active))
self.assertEqual(0, len(self.sess.pool.idle))
conn.disconnect()
# even though disconnected, gets put into idle
self.assertEqual(0, len(self.sess.pool.active))
self.assertEqual(1, len(self.sess.pool.idle))
# should remove all connections
self.sess.cleanup()
self.assertEqual(0, len(self.sess.pool.active))
self.assertEqual(0, len(self.sess.pool.idle))
def test_connection_create_time(self):
# Get a connection and record its object ID and create_time
# Release the connection (goes from active to idle queue)
# Again, get a connection. Should get the same connection back.
# I.e., the object IDs should match. However, the new connection
# should have a more recent 'last_used_time'
conn_obj_id_1 = None
conn_obj_id_2 = None
create_time_1 = None
create_time_2 = None
last_used_time_1 = None
last_used_time_2 = None
with self.sess.pool.get_connection() as conn:
conn_obj_id_1 = id(conn)
curr_time = datetime.datetime.now()
create_time_1 = conn.create_time
last_used_time_1 = conn.last_used_time
self.assertTrue(curr_time >= create_time_1)
self.assertTrue(curr_time >= last_used_time_1)
self.assertEqual(1, len(self.sess.pool.active))
self.assertEqual(0, len(self.sess.pool.idle))
self.sess.pool.release_connection(conn)
self.assertEqual(0, len(self.sess.pool.active))
self.assertEqual(1, len(self.sess.pool.idle))
with self.sess.pool.get_connection() as conn:
conn_obj_id_2 = id(conn)
curr_time = datetime.datetime.now()
create_time_2 = conn.create_time
last_used_time_2 = conn.last_used_time
self.assertEqual(conn_obj_id_1, conn_obj_id_2)
self.assertTrue(curr_time >= create_time_2)
self.assertTrue(curr_time >= last_used_time_2)
self.assertTrue(last_used_time_2 >= last_used_time_1)
self.assertEqual(1, len(self.sess.pool.active))
self.assertEqual(0, len(self.sess.pool.idle))
self.sess.pool.release_connection(conn)
self.assertEqual(0, len(self.sess.pool.active))
self.assertEqual(1, len(self.sess.pool.idle))
self.sess.pool.release_connection(conn, True)
self.assertEqual(0, len(self.sess.pool.active))
self.assertEqual(0, len(self.sess.pool.idle))
def test_refresh_connection(self):
# Set 'irods_connection_refresh_time' to '3' (in seconds) in
# ~/.irods/irods_environment.json file. This means any connection
# that was created more than 3 seconds ago will be dropped and
# a new connection is created/returned. This is to avoid
# issue with idle connections that are dropped.
conn_obj_id_1 = None
conn_obj_id_2 = None
create_time_1 = None
create_time_2 = None
last_used_time_1 = None
last_used_time_2 = None
with self.sess.pool.get_connection() as conn:
conn_obj_id_1 = id(conn)
curr_time = datetime.datetime.now()
create_time_1 = conn.create_time
last_used_time_1 = conn.last_used_time
self.assertTrue(curr_time >= create_time_1)
self.assertTrue(curr_time >= last_used_time_1)
self.assertEqual(1, len(self.sess.pool.active))
self.assertEqual(0, len(self.sess.pool.idle))
self.sess.pool.release_connection(conn)
self.assertEqual(0, len(self.sess.pool.active))
self.assertEqual(1, len(self.sess.pool.idle))
# Wait more than 'irods_connection_refresh_time' seconds,
# which is set to 3. Connection object should have a different
# object ID (as a new connection is created)
time.sleep(5)
with self.sess.pool.get_connection() as conn:
conn_obj_id_2 = id(conn)
curr_time = datetime.datetime.now()
create_time_2 = conn.create_time
last_used_time_2 = conn.last_used_time
self.assertTrue(curr_time >= create_time_2)
self.assertTrue(curr_time >= last_used_time_2)
self.assertNotEqual(conn_obj_id_1, conn_obj_id_2)
self.assertTrue(create_time_2 > create_time_1)
self.assertEqual(1, len(self.sess.pool.active))
self.assertEqual(0, len(self.sess.pool.idle))
self.sess.pool.release_connection(conn, True)
self.assertEqual(0, len(self.sess.pool.active))
self.assertEqual(0, len(self.sess.pool.idle))
def test_no_refresh_connection(self):
# Set 'irods_connection_refresh_time' to '3' (in seconds) in
# ~/.irods/irods_environment.json file. This means any connection
# created more than 3 seconds ago will be dropped and
# a new connection is created/returned. This is to avoid
# issue with idle connections that are dropped.
conn_obj_id_1 = None
conn_obj_id_2 = None
create_time_1 = None
create_time_2 = None
last_used_time_1 = None
last_used_time_2 = None
with self.sess.pool.get_connection() as conn:
conn_obj_id_1 = id(conn)
curr_time = datetime.datetime.now()
create_time_1 = conn.create_time
last_used_time_1 = conn.last_used_time
self.assertTrue(curr_time >= create_time_1)
self.assertTrue(curr_time >= last_used_time_1)
self.assertEqual(1, len(self.sess.pool.active))
self.assertEqual(0, len(self.sess.pool.idle))
self.sess.pool.release_connection(conn)
self.assertEqual(0, len(self.sess.pool.active))
self.assertEqual(1, len(self.sess.pool.idle))
# Wait less than 'irods_connection_refresh_time' seconds,
# which is set to 3. Connection object should have the same
# object ID (as idle time is less than 'irods_connection_refresh_time')
time.sleep(1)
with self.sess.pool.get_connection() as conn:
conn_obj_id_2 = id(conn)
curr_time = datetime.datetime.now()
create_time_2 = conn.create_time
last_used_time_2 = conn.last_used_time
self.assertTrue(curr_time >= create_time_2)
self.assertTrue(curr_time >= last_used_time_2)
self.assertEqual(conn_obj_id_1, conn_obj_id_2)
self.assertTrue(create_time_2 >= create_time_1)
self.assertEqual(1, len(self.sess.pool.active))
self.assertEqual(0, len(self.sess.pool.idle))
self.sess.pool.release_connection(conn, True)
self.assertEqual(0, len(self.sess.pool.active))
self.assertEqual(0, len(self.sess.pool.idle))
def test_get_connection_refresh_time_no_env_file_input_param(self):
connection_refresh_time = self.sess.get_connection_refresh_time(first_name="Magic", last_name="Johnson")
self.assertEqual(connection_refresh_time, -1)
def test_get_connection_refresh_time_none_existant_env_file(self):
connection_refresh_time = self.sess.get_connection_refresh_time(irods_env_file="./test-data/irods_environment_non_existant.json")
self.assertEqual(connection_refresh_time, -1)
def test_get_connection_refresh_time_no_connection_refresh_field(self):
connection_refresh_time = self.sess.get_connection_refresh_time(irods_env_file="./test-data/irods_environment_no_refresh_field.json")
self.assertEqual(connection_refresh_time, -1)
def test_get_connection_refresh_time_negative_connection_refresh_field(self):
connection_refresh_time = self.sess.get_connection_refresh_time(irods_env_file="./test-data/irods_environment_negative_refresh_field.json")
self.assertEqual(connection_refresh_time, -1)
def test_get_connection_refresh_time(self):
connection_refresh_time = self.sess.get_connection_refresh_time(irods_env_file="./test-data/irods_environment.json")
self.assertEqual(connection_refresh_time, 3)
if __name__ == '__main__':
# let the tests find the parent irods lib
sys.path.insert(0, os.path.abspath('../..'))
unittest.main()
|
{"/irods/test/query_test.py": ["/irods/column.py", "/irods/rule.py", "/irods/test/helpers.py"], "/irods/session.py": ["/irods/pool.py", "/irods/manager/data_object_manager.py", "/irods/manager/user_manager.py"], "/irods/pool.py": ["/irods/connection.py"], "/irods/test/user_group_test.py": ["/irods/test/helpers.py"], "/irods/test/helpers.py": ["/irods/session.py"], "/irods/test/meta_test.py": ["/irods/test/helpers.py"], "/irods/test/pool_test.py": ["/irods/test/helpers.py"], "/irods/test/login_auth_test.py": ["/irods/test/helpers.py", "/irods/connection.py", "/irods/session.py", "/irods/rule.py"], "/irods/test/rule_test.py": ["/irods/test/helpers.py", "/irods/rule.py"], "/irods/manager/user_manager.py": ["/irods/user.py"]}
|
22,663,453
|
alanking/python-irodsclient
|
refs/heads/master
|
/irods/test/login_auth_test.py
|
#! /usr/bin/env python
from __future__ import print_function
from __future__ import absolute_import
import os
import sys
import unittest
import textwrap
import json
import shutil
import ssl
import irods.test.helpers as helpers
from irods.connection import Connection
from irods.session import iRODSSession
from irods.rule import Rule
from irods.models import User
from socket import gethostname
from irods.password_obfuscation import (encode as pw_encode)
from irods.connection import PlainTextPAMPasswordError
import contextlib
from re import compile as regex
try:
from re import _pattern_type as regex_type
except ImportError:
from re import Pattern as regex_type # Python 3.7+
def json_file_update(fname,keys_to_delete=(),**kw):
j = json.load(open(fname,'r'))
j.update(**kw)
for k in keys_to_delete:
if k in j: del j [k]
elif isinstance(k,regex_type):
jk = [i for i in j.keys() if k.search(i)]
for ky in jk: del j[ky]
with open(fname,'w') as out:
json.dump(j, out, indent=4)
def env_dir_fullpath(authtype): return os.path.join( os.environ['HOME'] , '.irods.' + authtype)
def json_env_fullpath(authtype): return os.path.join( env_dir_fullpath(authtype), 'irods_environment.json')
def secrets_fullpath(authtype): return os.path.join( env_dir_fullpath(authtype), '.irodsA')
SERVER_ENV_PATH = os.path.expanduser('~irods/.irods/irods_environment.json')
SERVER_ENV_SSL_SETTINGS = {
"irods_ssl_certificate_chain_file": "/etc/irods/ssl/irods.crt",
"irods_ssl_certificate_key_file": "/etc/irods/ssl/irods.key",
"irods_ssl_dh_params_file": "/etc/irods/ssl/dhparams.pem",
"irods_ssl_ca_certificate_file": "/etc/irods/ssl/irods.crt",
"irods_ssl_verify_server": "cert"
}
def update_service_account_for_SSL():
json_file_update( SERVER_ENV_PATH, **SERVER_ENV_SSL_SETTINGS )
CLIENT_OPTIONS_FOR_SSL = {
"irods_client_server_policy": "CS_NEG_REQUIRE",
"irods_client_server_negotiation": "request_server_negotiation",
"irods_ssl_ca_certificate_file": "/etc/irods/ssl/irods.crt",
"irods_ssl_verify_server": "cert",
"irods_encryption_key_size": 16,
"irods_encryption_salt_size": 8,
"irods_encryption_num_hash_rounds": 16,
"irods_encryption_algorithm": "AES-256-CBC"
}
def client_env_from_server_env(user_name, auth_scheme=""):
cli_env = {}
with open(SERVER_ENV_PATH) as f:
srv_env = json.load(f)
for k in [ "irods_host", "irods_zone_name", "irods_port" ]:
cli_env [k] = srv_env[k]
cli_env["irods_user_name"] = user_name
if auth_scheme:
cli_env["irods_authentication_scheme"] = auth_scheme
return cli_env
@contextlib.contextmanager
def pam_password_in_plaintext(allow=True):
saved = bool(Connection.DISALLOWING_PAM_PLAINTEXT)
try:
Connection.DISALLOWING_PAM_PLAINTEXT = not(allow)
yield
finally:
Connection.DISALLOWING_PAM_PLAINTEXT = saved
class TestLogins(unittest.TestCase):
'''
This is due to be moved into Jenkins CI along core and other iRODS tests.
Until then, for these tests to run successfully, we require:
1. First run ./setupssl.py (sets up SSL keys etc. in /etc/irods/ssl)
2. Add & override configuration entries in /var/lib/irods/irods_environment
Per https://slides.com/irods/ugm2018-ssl-and-pam-configuration#/3/7
3. Create rodsuser alissa and corresponding unix user with the appropriate
passwords as below.
'''
test_rods_user = 'alissa'
user_auth_envs = {
'.irods.pam': {
'USER': test_rods_user,
'PASSWORD': 'test123', # UNIX pw
'AUTH': 'pam'
},
'.irods.native': {
'USER': test_rods_user,
'PASSWORD': 'apass', # iRODS pw
'AUTH': 'native'
}
}
env_save = {}
@contextlib.contextmanager
def setenv(self,var,newvalue):
try:
self.env_save[var] = os.environ.get(var,None)
os.environ[var] = newvalue
yield newvalue
finally:
oldvalue = self.env_save[var]
if oldvalue is None:
del os.environ[var]
else:
os.environ[var]=oldvalue
@classmethod
def create_env_dirs(cls):
dirs = {}
retval = []
# -- create environment configurations and secrets
with pam_password_in_plaintext():
for dirname,lookup in cls.user_auth_envs.items():
if lookup['AUTH'] == 'pam':
ses = iRODSSession( host=gethostname(),
user=lookup['USER'],
zone='tempZone',
authentication_scheme=lookup['AUTH'],
password=lookup['PASSWORD'],
port= 1247 )
try:
pam_hashes = ses.pam_pw_negotiated
except AttributeError:
pam_hashes = []
if not pam_hashes: print('Warning ** PAM pw couldnt be generated' ); break
scrambled_pw = pw_encode( pam_hashes[0] )
#elif lookup['AUTH'] == 'XXXXXX': # TODO: insert other authentication schemes here
elif lookup['AUTH'] in ('native', '',None):
scrambled_pw = pw_encode( lookup['PASSWORD'] )
cl_env = client_env_from_server_env(cls.test_rods_user)
if lookup.get('AUTH',None) is not None: # - specify auth scheme only if given
cl_env['irods_authentication_scheme'] = lookup['AUTH']
dirbase = os.path.join(os.environ['HOME'],dirname)
dirs[dirbase] = { 'secrets':scrambled_pw , 'client_environment':cl_env }
# -- create the environment directories and write into them the configurations just created
for absdir in dirs.keys():
shutil.rmtree(absdir,ignore_errors=True)
os.mkdir(absdir)
with open(os.path.join(absdir,'irods_environment.json'),'w') as envfile:
envfile.write('{}')
json_file_update(envfile.name, **dirs[absdir]['client_environment'])
with open(os.path.join(absdir,'.irodsA'),'wb') as secrets_file:
secrets_file.write(dirs[absdir]['secrets'])
os.chmod(secrets_file.name,0o600)
retval = dirs.keys()
return retval
@staticmethod
def get_server_ssl_negotiation( session ):
rule_body = textwrap.dedent('''
test { *out=""; acPreConnect(*out);
writeLine("stdout", "*out");
}
''')
myrule = Rule(session, body=rule_body, params={}, output='ruleExecOut')
out_array = myrule.execute()
buf = out_array.MsParam_PI[0].inOutStruct.stdoutBuf.buf.decode('utf-8')
eol_offset = buf.find('\n')
return buf[:eol_offset] if eol_offset >= 0 else None
@classmethod
def setUpClass(cls):
cls.admin = helpers.make_session()
if cls.test_rods_user in (row[User.name] for row in cls.admin.query(User.name)):
cls.server_ssl_setting = cls.get_server_ssl_negotiation( cls.admin )
cls.envdirs = cls.create_env_dirs()
if not cls.envdirs:
raise RuntimeError('Could not create one or more client environments')
@classmethod
def tearDownClass(cls):
for envdir in getattr(cls, 'envdirs', []):
shutil.rmtree(envdir, ignore_errors=True)
cls.admin.cleanup()
def setUp(self):
if not getattr(self, 'envdirs', []):
self.skipTest('The test_rods_user "{}" does not exist'.format(self.test_rods_user))
super(TestLogins,self).setUp()
def tearDown(self):
super(TestLogins,self).tearDown()
def validate_session(self, session, verbose=False, **options):
# - try to get the home collection
home_coll = '/{0.zone}/home/{0.username}'.format(session)
self.assertTrue(session.collections.get(home_coll).path == home_coll)
if verbose: print(home_coll)
# - check user is as expected
self.assertEqual( session.username, self.test_rods_user )
# - check socket type (normal vs SSL) against whether ssl requested
use_ssl = options.pop('ssl',None)
if use_ssl is not None:
my_connect = [s for s in (session.pool.active|session.pool.idle)] [0]
self.assertEqual( bool( use_ssl ), my_connect.socket.__class__ is ssl.SSLSocket )
# def test_demo(self): self.demo()
# def demo(self): # for future reference - skipping based on CS_NEG_DONT_CARE setting
# if self.server_ssl_setting == 'CS_NEG_DONT_CARE':
# self.skipTest('skipping b/c setting is DONT_CARE')
# self.assertTrue (False)
def tst0(self, ssl_opt, auth_opt, env_opt ):
auth_opt_explicit = 'native' if auth_opt=='' else auth_opt
verbosity=False
#verbosity='' # -- debug - sanity check by printing out options applied
out = {'':''}
if env_opt:
with self.setenv('IRODS_ENVIRONMENT_FILE', json_env_fullpath(auth_opt_explicit)) as env_file,\
self.setenv('IRODS_AUTHENTICATION_FILE', secrets_fullpath(auth_opt_explicit)):
cli_env_extras = {} if not(ssl_opt) else dict( CLIENT_OPTIONS_FOR_SSL )
if auth_opt:
cli_env_extras.update( irods_authentication_scheme = auth_opt )
remove=[]
else:
remove=[regex('authentication_')]
with helpers.file_backed_up(env_file):
json_file_update( env_file, keys_to_delete=remove, **cli_env_extras )
session = iRODSSession(irods_env_file=env_file)
out = json.load(open(env_file))
self.validate_session( session, verbose = verbosity, ssl = ssl_opt )
session.cleanup()
out['ARGS']='no'
else:
session_options = {}
if auth_opt:
session_options.update (authentication_scheme = auth_opt)
if ssl_opt:
SSL_cert = CLIENT_OPTIONS_FOR_SSL["irods_ssl_ca_certificate_file"]
session_options.update(
ssl_context = ssl.create_default_context ( purpose = ssl.Purpose.SERVER_AUTH,
capath = None,
cadata = None,
cafile = SSL_cert),
**CLIENT_OPTIONS_FOR_SSL )
lookup = self.user_auth_envs ['.irods.'+('native' if not(auth_opt) else auth_opt)]
session = iRODSSession ( host=gethostname(),
user=lookup['USER'],
zone='tempZone',
password=lookup['PASSWORD'],
port= 1247,
**session_options )
out = session_options
self.validate_session( session, verbose = verbosity, ssl = ssl_opt )
session.cleanup()
out['ARGS']='yes'
if verbosity == '':
print ('--- ssl:',ssl_opt,'/ auth:',repr(auth_opt),'/ env:',env_opt)
print ('--- > ',json.dumps({k:v for k,v in out.items() if k != 'ssl_context'},indent=4))
print ('---')
# == test defaulting to 'native'
def test_01(self):
self.tst0 ( ssl_opt = True , auth_opt = '' , env_opt = False )
def test_02(self):
self.tst0 ( ssl_opt = False, auth_opt = '' , env_opt = False )
def test_03(self):
self.tst0 ( ssl_opt = True , auth_opt = '' , env_opt = True )
def test_04(self):
self.tst0 ( ssl_opt = False, auth_opt = '' , env_opt = True )
# == test explicit scheme 'native'
def test_1(self):
self.tst0 ( ssl_opt = True , auth_opt = 'native' , env_opt = False )
def test_2(self):
self.tst0 ( ssl_opt = False, auth_opt = 'native' , env_opt = False )
def test_3(self):
self.tst0 ( ssl_opt = True , auth_opt = 'native' , env_opt = True )
def test_4(self):
self.tst0 ( ssl_opt = False, auth_opt = 'native' , env_opt = True )
# == test explicit scheme 'pam'
def test_5(self):
self.tst0 ( ssl_opt = True, auth_opt = 'pam' , env_opt = False )
def test_6(self):
try:
self.tst0 ( ssl_opt = False, auth_opt = 'pam' , env_opt = False )
except PlainTextPAMPasswordError:
pass
else:
# -- no exception raised
self.fail("PlainTextPAMPasswordError should have been raised")
def test_7(self):
self.tst0 ( ssl_opt = True , auth_opt = 'pam' , env_opt = True )
def test_8(self):
self.tst0 ( ssl_opt = False, auth_opt = 'pam' , env_opt = True )
if __name__ == '__main__':
# let the tests find the parent irods lib
sys.path.insert(0, os.path.abspath('../..'))
unittest.main()
|
{"/irods/test/query_test.py": ["/irods/column.py", "/irods/rule.py", "/irods/test/helpers.py"], "/irods/session.py": ["/irods/pool.py", "/irods/manager/data_object_manager.py", "/irods/manager/user_manager.py"], "/irods/pool.py": ["/irods/connection.py"], "/irods/test/user_group_test.py": ["/irods/test/helpers.py"], "/irods/test/helpers.py": ["/irods/session.py"], "/irods/test/meta_test.py": ["/irods/test/helpers.py"], "/irods/test/pool_test.py": ["/irods/test/helpers.py"], "/irods/test/login_auth_test.py": ["/irods/test/helpers.py", "/irods/connection.py", "/irods/session.py", "/irods/rule.py"], "/irods/test/rule_test.py": ["/irods/test/helpers.py", "/irods/rule.py"], "/irods/manager/user_manager.py": ["/irods/user.py"]}
|
22,663,454
|
alanking/python-irodsclient
|
refs/heads/master
|
/irods/connection.py
|
from __future__ import absolute_import
import socket
import logging
import struct
import hashlib
import six
import os
import ssl
import datetime
from irods.message import (
iRODSMessage, StartupPack, AuthResponse, AuthChallenge, AuthPluginOut,
OpenedDataObjRequest, FileSeekResponse, StringStringMap, VersionResponse,
PluginAuthMessage, ClientServerNegotiation, Error)
from irods.exception import get_exception_by_code, NetworkException
from irods import (
MAX_PASSWORD_LENGTH, RESPONSE_LEN,
AUTH_SCHEME_KEY, AUTH_USER_KEY, AUTH_PWD_KEY, AUTH_TTL_KEY,
NATIVE_AUTH_SCHEME,
GSI_AUTH_PLUGIN, GSI_AUTH_SCHEME, GSI_OID,
PAM_AUTH_SCHEME)
from irods.client_server_negotiation import (
perform_negotiation,
validate_policy,
REQUEST_NEGOTIATION,
REQUIRE_TCP,
FAILURE,
USE_SSL,
CS_NEG_RESULT_KW)
from irods.api_number import api_number
logger = logging.getLogger(__name__)
class PlainTextPAMPasswordError(Exception): pass
class Connection(object):
DISALLOWING_PAM_PLAINTEXT = True
def __init__(self, pool, account):
self.pool = pool
self.socket = None
self.account = account
self._client_signature = None
self._server_version = self._connect()
scheme = self.account.authentication_scheme
if scheme == NATIVE_AUTH_SCHEME:
self._login_native()
elif scheme == GSI_AUTH_SCHEME:
self.client_ctx = None
self._login_gsi()
elif scheme == PAM_AUTH_SCHEME:
self._login_pam()
else:
raise ValueError("Unknown authentication scheme %s" % scheme)
self.create_time = datetime.datetime.now()
self.last_used_time = self.create_time
@property
def server_version(self):
return tuple(int(x) for x in self._server_version.relVersion.replace('rods', '').split('.'))
@property
def client_signature(self):
return self._client_signature
def __del__(self):
if self.socket:
self.disconnect()
def send(self, message):
string = message.pack()
logger.debug(string)
try:
self.socket.sendall(string)
except:
logger.error(
"Unable to send message. " +
"Connection to remote host may have closed. " +
"Releasing connection from pool."
)
self.release(True)
raise NetworkException("Unable to send message")
def recv(self):
try:
msg = iRODSMessage.recv(self.socket)
except socket.error:
logger.error("Could not receive server response")
self.release(True)
raise NetworkException("Could not receive server response")
if msg.int_info < 0:
try:
err_msg = iRODSMessage(msg=msg.error).get_main_message(Error).RErrMsg_PI[0].msg
except TypeError:
raise get_exception_by_code(msg.int_info)
raise get_exception_by_code(msg.int_info, err_msg)
return msg
def recv_into(self, buffer):
try:
msg = iRODSMessage.recv_into(self.socket, buffer)
except socket.error:
logger.error("Could not receive server response")
self.release(True)
raise NetworkException("Could not receive server response")
if msg.int_info < 0:
try:
err_msg = iRODSMessage(msg=msg.error).get_main_message(Error).RErrMsg_PI[0].msg
except TypeError:
raise get_exception_by_code(msg.int_info)
raise get_exception_by_code(msg.int_info, err_msg)
return msg
def __enter__(self):
return self
def __exit__(self, exc_type, exc_value, traceback):
self.release()
def release(self, destroy=False):
self.pool.release_connection(self, destroy)
def reply(self, api_reply_index):
value = socket.htonl(api_reply_index)
try:
self.socket.sendall(struct.pack('I', value))
except:
self.release(True)
raise NetworkException("Unable to send API reply")
def requires_cs_negotiation(self):
try:
if self.account.client_server_negotiation == REQUEST_NEGOTIATION:
return True
except AttributeError:
return False
return False
def ssl_startup(self):
# Get encryption settings from client environment
host = self.account.host
algo = self.account.encryption_algorithm
key_size = self.account.encryption_key_size
hash_rounds = self.account.encryption_num_hash_rounds
salt_size = self.account.encryption_salt_size
# Get or create SSL context
try:
context = self.account.ssl_context
except AttributeError:
CA_file = getattr(self.account, 'ssl_ca_certificate_file', None)
context = ssl.create_default_context(ssl.Purpose.SERVER_AUTH, cafile=CA_file)
# Wrap socket with context
wrapped_socket = context.wrap_socket(self.socket, server_hostname=host)
# Initial SSL handshake
wrapped_socket.do_handshake()
# Generate key (shared secret)
key = os.urandom(self.account.encryption_key_size)
# Send header-only message with client side encryption settings
packed_header = iRODSMessage.pack_header(algo,
key_size,
salt_size,
hash_rounds,
0)
wrapped_socket.sendall(packed_header)
# Send shared secret
packed_header = iRODSMessage.pack_header('SHARED_SECRET',
key_size,
0,
0,
0)
wrapped_socket.sendall(packed_header + key)
# Use SSL socket from now on
self.socket = wrapped_socket
def _connect(self):
address = (self.account.host, self.account.port)
timeout = self.pool.connection_timeout
try:
s = socket.create_connection(address, timeout)
except socket.error:
raise NetworkException(
"Could not connect to specified host and port: " +
"{}:{}".format(*address))
self.socket = s
main_message = StartupPack(
(self.account.proxy_user, self.account.proxy_zone),
(self.account.client_user, self.account.client_zone),
self.pool.application_name
)
# No client-server negotiation
if not self.requires_cs_negotiation():
# Send startup pack without negotiation request
msg = iRODSMessage(msg_type='RODS_CONNECT', msg=main_message)
self.send(msg)
# Server responds with version
version_msg = self.recv()
# Done
return version_msg.get_main_message(VersionResponse)
# Get client negotiation policy
client_policy = getattr(self.account, 'client_server_policy', REQUIRE_TCP)
# Sanity check
validate_policy(client_policy)
# Send startup pack with negotiation request
main_message.option = '{};{}'.format(main_message.option, REQUEST_NEGOTIATION)
msg = iRODSMessage(msg_type='RODS_CONNECT', msg=main_message)
self.send(msg)
# Server responds with its own negotiation policy
cs_neg_msg = self.recv()
response = cs_neg_msg.get_main_message(ClientServerNegotiation)
server_policy = response.result
# Perform the negotiation
neg_result, status = perform_negotiation(client_policy=client_policy,
server_policy=server_policy)
# Send negotiation result to server
client_neg_response = ClientServerNegotiation(
status=status,
result='{}={};'.format(CS_NEG_RESULT_KW, neg_result)
)
msg = iRODSMessage(msg_type='RODS_CS_NEG_T', msg=client_neg_response)
self.send(msg)
# If negotiation failed we're done
if neg_result == FAILURE:
self.disconnect()
raise NetworkException("Client-Server negotiation failure: {},{}".format(client_policy, server_policy))
# Server responds with version
version_msg = self.recv()
if neg_result == USE_SSL:
self.ssl_startup()
return version_msg.get_main_message(VersionResponse)
def disconnect(self):
disconnect_msg = iRODSMessage(msg_type='RODS_DISCONNECT')
self.send(disconnect_msg)
try:
# SSL shutdown handshake
self.socket = self.socket.unwrap()
except AttributeError:
pass
self.socket.shutdown(socket.SHUT_RDWR)
self.socket.close()
self.socket = None
def recvall(self, n):
# Helper function to recv n bytes or return None if EOF is hit
data = b''
while len(data) < n:
packet = self.socket.recv(n - len(data))
if not packet:
return None
data += packet
return data
def init_sec_context(self):
import gssapi
# AUTHORIZATION MECHANISM
gsi_mech = gssapi.raw.OID.from_int_seq(GSI_OID)
# SERVER NAME
server_name = gssapi.Name(self.account.server_dn)
server_name.canonicalize(gsi_mech)
# CLIENT CONTEXT
self.client_ctx = gssapi.SecurityContext(
name=server_name,
mech=gsi_mech,
flags=[2, 4],
usage='initiate')
def send_gsi_token(self, server_token=None):
# CLIENT TOKEN
if server_token is None:
client_token = self.client_ctx.step()
else:
client_token = self.client_ctx.step(server_token)
logger.debug("[GSI handshake] Client: sent a new token")
# SEND IT TO SERVER
self.reply(len(client_token))
self.socket.sendall(client_token)
def receive_gsi_token(self):
# Receive client token from iRODS
data = self.socket.recv(4)
value = struct.unpack("I", bytearray(data))
token_len = socket.ntohl(value[0])
server_token = self.recvall(token_len)
logger.debug("[GSI handshake] Server: received a new token")
return server_token
def handshake(self, target):
"""
This GSS API context based on GSI was obtained combining 2 sources:
https://pythonhosted.org/gssapi/basic-tutorial.html
https://github.com/irods/irods_auth_plugin_gsi/blob/master/gsi/libgsi.cpp
"""
self.init_sec_context()
# Go, into the loop
self.send_gsi_token()
while not (self.client_ctx.complete):
server_token = self.receive_gsi_token()
self.send_gsi_token(server_token)
logger.debug("[GSI Handshake] completed")
def gsi_client_auth_request(self):
# Request for authentication with GSI on current user
message_body = PluginAuthMessage(
auth_scheme_=GSI_AUTH_PLUGIN,
context_='%s=%s' % (AUTH_USER_KEY, self.account.client_user)
)
# GSI = 1201
# https://github.com/irods/irods/blob/master/lib/api/include/apiNumber.h#L158
auth_req = iRODSMessage(
msg_type='RODS_API_REQ', msg=message_body, int_info=1201)
self.send(auth_req)
# Getting the challenge message
self.recv()
# This receive an empty message for confirmation... To check:
# challenge_msg = self.recv()
def gsi_client_auth_response(self):
message = '%s=%s' % (AUTH_SCHEME_KEY, GSI_AUTH_SCHEME)
# IMPORTANT! padding
len_diff = RESPONSE_LEN - len(message)
message += "\0" * len_diff
# mimic gsi_auth_client_response
gsi_msg = AuthResponse(
response=message,
username=self.account.proxy_user + '#' + self.account.proxy_zone
)
gsi_request = iRODSMessage(
msg_type='RODS_API_REQ', int_info=704, msg=gsi_msg)
self.send(gsi_request)
self.recv()
# auth_response = self.recv()
def _login_gsi(self):
# Send iRODS server a message to request GSI authentication
self.gsi_client_auth_request()
# Create a context handshaking GSI credentials
# Note: this can work only if you export GSI certificates
# as shell environment variables (X509_etc.)
self.handshake(self.account.host)
# Complete the protocol
self.gsi_client_auth_response()
logger.info("GSI authorization validated")
def _login_pam(self):
ctx_user = '%s=%s' % (AUTH_USER_KEY, self.account.client_user)
ctx_pwd = '%s=%s' % (AUTH_PWD_KEY, self.account.password)
ctx_ttl = '%s=%s' % (AUTH_TTL_KEY, "60")
ctx = ";".join([ctx_user, ctx_pwd, ctx_ttl])
if type(self.socket) is socket.socket:
if getattr(self,'DISALLOWING_PAM_PLAINTEXT',True):
raise PlainTextPAMPasswordError
message_body = PluginAuthMessage(
auth_scheme_=PAM_AUTH_SCHEME,
context_=ctx
)
auth_req = iRODSMessage(
msg_type='RODS_API_REQ',
msg=message_body,
# int_info=725
int_info=1201
)
self.send(auth_req)
# Getting the new password
output_message = self.recv()
auth_out = output_message.get_main_message(AuthPluginOut)
self.disconnect()
self._connect()
if hasattr(self.account,'store_pw'):
drop = self.account.store_pw
if type(drop) is list:
drop[:] = [ auth_out.result_ ]
self._login_native(password=auth_out.result_)
logger.info("PAM authorization validated")
def read_file(self, desc, size=-1, buffer=None):
if size < 0:
size = len(buffer)
elif buffer is not None:
size = min(size, len(buffer))
message_body = OpenedDataObjRequest(
l1descInx=desc,
len=size,
whence=0,
oprType=0,
offset=0,
bytesWritten=0,
KeyValPair_PI=StringStringMap()
)
message = iRODSMessage('RODS_API_REQ', msg=message_body,
int_info=api_number['DATA_OBJ_READ_AN'])
logger.debug(desc)
self.send(message)
if buffer is None:
response = self.recv()
else:
response = self.recv_into(buffer)
return response.bs
def _login_native(self, password=None):
# Default case, PAM login will send a new password
if password is None:
password = self.account.password
# authenticate
auth_req = iRODSMessage(msg_type='RODS_API_REQ', int_info=703)
self.send(auth_req)
# challenge
challenge_msg = self.recv()
logger.debug(challenge_msg.msg)
challenge = challenge_msg.get_main_message(AuthChallenge).challenge
# one "session" signature per connection
# see https://github.com/irods/irods/blob/4.2.1/plugins/auth/native/libnative.cpp#L137
# and https://github.com/irods/irods/blob/4.2.1/lib/core/src/clientLogin.cpp#L38-L60
if six.PY2:
self._client_signature = "".join("{:02x}".format(ord(c)) for c in challenge[:16])
else:
self._client_signature = "".join("{:02x}".format(c) for c in challenge[:16])
if six.PY3:
challenge = challenge.strip()
padded_pwd = struct.pack(
"%ds" % MAX_PASSWORD_LENGTH, password.encode(
'utf-8').strip())
else:
padded_pwd = struct.pack(
"%ds" % MAX_PASSWORD_LENGTH, password)
m = hashlib.md5()
m.update(challenge)
m.update(padded_pwd)
encoded_pwd = m.digest()
if six.PY2:
encoded_pwd = encoded_pwd.replace('\x00', '\x01')
elif b'\x00' in encoded_pwd:
encoded_pwd_array = bytearray(encoded_pwd)
encoded_pwd = bytes(encoded_pwd_array.replace(b'\x00', b'\x01'))
pwd_msg = AuthResponse(
response=encoded_pwd, username=self.account.proxy_user)
pwd_request = iRODSMessage(
msg_type='RODS_API_REQ', int_info=704, msg=pwd_msg)
self.send(pwd_request)
self.recv()
def write_file(self, desc, string):
message_body = OpenedDataObjRequest(
l1descInx=desc,
len=len(string),
whence=0,
oprType=0,
offset=0,
bytesWritten=0,
KeyValPair_PI=StringStringMap()
)
message = iRODSMessage('RODS_API_REQ', msg=message_body,
bs=string,
int_info=api_number['DATA_OBJ_WRITE_AN'])
self.send(message)
response = self.recv()
return response.int_info
def seek_file(self, desc, offset, whence):
message_body = OpenedDataObjRequest(
l1descInx=desc,
len=0,
whence=whence,
oprType=0,
offset=offset,
bytesWritten=0,
KeyValPair_PI=StringStringMap()
)
message = iRODSMessage('RODS_API_REQ', msg=message_body,
int_info=api_number['DATA_OBJ_LSEEK_AN'])
self.send(message)
response = self.recv()
offset = response.get_main_message(FileSeekResponse).offset
return offset
def close_file(self, desc, **options):
message_body = OpenedDataObjRequest(
l1descInx=desc,
len=0,
whence=0,
oprType=0,
offset=0,
bytesWritten=0,
KeyValPair_PI=StringStringMap(options)
)
message = iRODSMessage('RODS_API_REQ', msg=message_body,
int_info=api_number['DATA_OBJ_CLOSE_AN'])
self.send(message)
self.recv()
|
{"/irods/test/query_test.py": ["/irods/column.py", "/irods/rule.py", "/irods/test/helpers.py"], "/irods/session.py": ["/irods/pool.py", "/irods/manager/data_object_manager.py", "/irods/manager/user_manager.py"], "/irods/pool.py": ["/irods/connection.py"], "/irods/test/user_group_test.py": ["/irods/test/helpers.py"], "/irods/test/helpers.py": ["/irods/session.py"], "/irods/test/meta_test.py": ["/irods/test/helpers.py"], "/irods/test/pool_test.py": ["/irods/test/helpers.py"], "/irods/test/login_auth_test.py": ["/irods/test/helpers.py", "/irods/connection.py", "/irods/session.py", "/irods/rule.py"], "/irods/test/rule_test.py": ["/irods/test/helpers.py", "/irods/rule.py"], "/irods/manager/user_manager.py": ["/irods/user.py"]}
|
22,663,455
|
alanking/python-irodsclient
|
refs/heads/master
|
/irods/test/rule_test.py
|
#! /usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import absolute_import
import os
import sys
import time
import textwrap
import unittest
from irods.models import DataObject
import irods.test.helpers as helpers
from irods.rule import Rule
import six
from io import open as io_open
class TestRule(unittest.TestCase):
'''Suite of tests on rule operations
'''
def setUp(self):
self.sess = helpers.make_session()
def tearDown(self):
# close connections
self.sess.cleanup()
def test_add_metadata_from_rule_file(self):
'''
Tests running a rule from a client-side .r file.
The rule adds metadata attributes to an iRODS object
and we check for the presence of said attributes.
'''
session = self.sess
# test metadata
attr_name = "test_attr"
attr_value = "test_value"
# make test object
ts = time.time()
zone = session.zone
username = session.username
object_name = 'foo_{ts}.txt'.format(**locals())
object_path = "/{zone}/home/{username}/{object_name}".format(
**locals())
obj = helpers.make_object(session, object_path)
# make rule file
rule_file_path = "/tmp/test_{ts}.r".format(**locals())
rule = textwrap.dedent('''\
test {{
# add metadata
*attribute.*name = *value;
msiAssociateKeyValuePairsToObj(*attribute, *object, "-d")
}}
INPUT *object="{object_path}",*name="{attr_name}",*value="{attr_value}"
OUTPUT ruleExecOut'''.format(**locals()))
with open(rule_file_path, "w") as rule_file:
rule_file.write(rule)
# run test rule
myrule = Rule(session, rule_file_path)
myrule.execute()
# check that metadata is there
meta = session.metadata.get(DataObject, object_path)
assert meta[0].name == attr_name
assert meta[0].value == attr_value
# remove test object
obj.unlink(force=True)
# remove rule file
os.remove(rule_file_path)
def test_add_metadata_from_rule(self):
'''
Runs a rule whose body and input parameters are created in our script.
The rule adds metadata attributes to an iRODS object
and we check for the presence of said attributes.
'''
session = self.sess
# test metadata
attr_name = "test_attr"
attr_value = "test_value"
# make test object
ts = time.time()
zone = session.zone
username = session.username
object_name = 'foo_{ts}.txt'.format(**locals())
object_path = "/{zone}/home/{username}/{object_name}".format(
**locals())
obj = helpers.make_object(session, object_path)
# rule body
rule_body = textwrap.dedent('''\
test {{
# add metadata
*attribute.*name = *value;
msiAssociateKeyValuePairsToObj(*attribute, *object, "-d")
}}''')
# rule parameters
input_params = { # extra quotes for string literals
'*object': '"{object_path}"'.format(**locals()),
'*name': '"{attr_name}"'.format(**locals()),
'*value': '"{attr_value}"'.format(**locals())
}
output = 'ruleExecOut'
# run test rule
myrule = Rule(session, body=rule_body,
params=input_params, output=output)
myrule.execute()
# check that metadata is there
meta = session.metadata.get(DataObject, object_path)
assert meta[0].name == attr_name
assert meta[0].value == attr_value
# remove test object
obj.unlink(force=True)
def test_retrieve_std_streams_from_rule(self):
'''
Tests running a rule from a client-side .r file.
The rule writes things to its stdout that we
get back on the client side
'''
# Wrong buffer length on older versions
if self.sess.server_version < (4, 1, 7):
self.skipTest('For iRODS 4.1.7 and newer')
session = self.sess
# test metadata
some_string = u'foo'
some_other_string = u'我喜欢麦当劳'
err_string = u'⛔'
# make rule file
ts = time.time()
rule_file_path = "/tmp/test_{ts}.r".format(**locals())
rule = textwrap.dedent(u'''\
test {{
# write stuff
writeLine("stdout", *some_string);
writeLine("stdout", *some_other_string);
writeLine("stderr", *err_string);
}}
INPUT *some_string="{some_string}",*some_other_string="{some_other_string}",*err_string="{err_string}"
OUTPUT ruleExecOut'''.format(**locals()))
with io_open(rule_file_path, "w", encoding='utf-8') as rule_file:
rule_file.write(rule)
# run test rule
myrule = Rule(session, rule_file_path)
out_array = myrule.execute()
# retrieve out buffer
buf = out_array.MsParam_PI[0].inOutStruct.stdoutBuf.buf
# it's binary data (BinBytesBuf) so must be decoded
buf = buf.decode('utf-8')
# check that we get our strings back
self.assertIn(some_string, buf)
self.assertIn(some_other_string, buf)
# same thing stderr buffer
buf = out_array.MsParam_PI[0].inOutStruct.stderrBuf.buf
# decode and check
buf = buf.decode('utf-8')
self.assertIn(err_string, buf)
# remove rule file
os.remove(rule_file_path)
if __name__ == '__main__':
# let the tests find the parent irods lib
sys.path.insert(0, os.path.abspath('../..'))
unittest.main()
|
{"/irods/test/query_test.py": ["/irods/column.py", "/irods/rule.py", "/irods/test/helpers.py"], "/irods/session.py": ["/irods/pool.py", "/irods/manager/data_object_manager.py", "/irods/manager/user_manager.py"], "/irods/pool.py": ["/irods/connection.py"], "/irods/test/user_group_test.py": ["/irods/test/helpers.py"], "/irods/test/helpers.py": ["/irods/session.py"], "/irods/test/meta_test.py": ["/irods/test/helpers.py"], "/irods/test/pool_test.py": ["/irods/test/helpers.py"], "/irods/test/login_auth_test.py": ["/irods/test/helpers.py", "/irods/connection.py", "/irods/session.py", "/irods/rule.py"], "/irods/test/rule_test.py": ["/irods/test/helpers.py", "/irods/rule.py"], "/irods/manager/user_manager.py": ["/irods/user.py"]}
|
22,663,456
|
alanking/python-irodsclient
|
refs/heads/master
|
/irods/manager/user_manager.py
|
from __future__ import absolute_import
import logging
from irods.models import User, UserGroup
from irods.manager import Manager
from irods.message import GeneralAdminRequest, iRODSMessage
from irods.exception import UserDoesNotExist, UserGroupDoesNotExist, NoResultFound
from irods.api_number import api_number
from irods.user import iRODSUser, iRODSUserGroup
import irods.password_obfuscation as obf
logger = logging.getLogger(__name__)
class UserManager(Manager):
def get(self, user_name, user_zone=""):
query = self.sess.query(User).filter(User.name == user_name)
if len(user_zone) > 0:
query = query.filter(User.zone == user_zone)
try:
result = query.one()
except NoResultFound:
raise UserDoesNotExist()
return iRODSUser(self, result)
def create(self, user_name, user_type, user_zone="", auth_str=""):
message_body = GeneralAdminRequest(
"add",
"user",
user_name if not user_zone or user_zone == self.sess.zone \
else "{}#{}".format(user_name,user_zone),
user_type,
user_zone,
auth_str
)
request = iRODSMessage("RODS_API_REQ", msg=message_body,
int_info=api_number['GENERAL_ADMIN_AN'])
with self.sess.pool.get_connection() as conn:
conn.send(request)
response = conn.recv()
logger.debug(response.int_info)
return self.get(user_name, user_zone)
def remove(self, user_name, user_zone=""):
message_body = GeneralAdminRequest(
"rm",
"user",
user_name,
user_zone
)
request = iRODSMessage("RODS_API_REQ", msg=message_body,
int_info=api_number['GENERAL_ADMIN_AN'])
with self.sess.pool.get_connection() as conn:
conn.send(request)
response = conn.recv()
logger.debug(response.int_info)
def modify(self, user_name, option, new_value, user_zone=""):
# must append zone to username for this API call
if len(user_zone) > 0:
user_name += "#" + user_zone
with self.sess.pool.get_connection() as conn:
# if modifying password, new value needs obfuscating
if option == 'password':
current_password = self.sess.pool.account.password
new_value = obf.obfuscate_new_password(new_value, current_password, conn.client_signature)
message_body = GeneralAdminRequest(
"modify",
"user",
user_name,
option,
new_value,
user_zone,
)
request = iRODSMessage("RODS_API_REQ", msg=message_body,
int_info=api_number['GENERAL_ADMIN_AN'])
conn.send(request)
response = conn.recv()
logger.debug(response.int_info)
class UserGroupManager(UserManager):
def get(self, name, user_zone=""):
query = self.sess.query(UserGroup).filter(UserGroup.name == name)
try:
result = query.one()
except NoResultFound:
raise UserGroupDoesNotExist()
return iRODSUserGroup(self, result)
def create(self, name, user_type='rodsgroup', user_zone="", auth_str=""):
message_body = GeneralAdminRequest(
"add",
"user",
name,
user_type,
"",
""
)
request = iRODSMessage("RODS_API_REQ", msg=message_body,
int_info=api_number['GENERAL_ADMIN_AN'])
with self.sess.pool.get_connection() as conn:
conn.send(request)
response = conn.recv()
logger.debug(response.int_info)
return self.get(name)
def getmembers(self, name):
results = self.sess.query(User).filter(
User.type != 'rodsgroup', UserGroup.name == name)
return [iRODSUser(self, row) for row in results]
def addmember(self, group_name, user_name, user_zone=""):
message_body = GeneralAdminRequest(
"modify",
"group",
group_name,
"add",
user_name,
user_zone
)
request = iRODSMessage("RODS_API_REQ", msg=message_body,
int_info=api_number['GENERAL_ADMIN_AN'])
with self.sess.pool.get_connection() as conn:
conn.send(request)
response = conn.recv()
logger.debug(response.int_info)
def removemember(self, group_name, user_name, user_zone=""):
message_body = GeneralAdminRequest(
"modify",
"group",
group_name,
"remove",
user_name,
user_zone
)
request = iRODSMessage("RODS_API_REQ", msg=message_body,
int_info=api_number['GENERAL_ADMIN_AN'])
with self.sess.pool.get_connection() as conn:
conn.send(request)
response = conn.recv()
logger.debug(response.int_info)
|
{"/irods/test/query_test.py": ["/irods/column.py", "/irods/rule.py", "/irods/test/helpers.py"], "/irods/session.py": ["/irods/pool.py", "/irods/manager/data_object_manager.py", "/irods/manager/user_manager.py"], "/irods/pool.py": ["/irods/connection.py"], "/irods/test/user_group_test.py": ["/irods/test/helpers.py"], "/irods/test/helpers.py": ["/irods/session.py"], "/irods/test/meta_test.py": ["/irods/test/helpers.py"], "/irods/test/pool_test.py": ["/irods/test/helpers.py"], "/irods/test/login_auth_test.py": ["/irods/test/helpers.py", "/irods/connection.py", "/irods/session.py", "/irods/rule.py"], "/irods/test/rule_test.py": ["/irods/test/helpers.py", "/irods/rule.py"], "/irods/manager/user_manager.py": ["/irods/user.py"]}
|
22,663,457
|
alanking/python-irodsclient
|
refs/heads/master
|
/irods/session.py
|
from __future__ import absolute_import
import os
import json
import logging
from irods.query import Query
from irods.pool import Pool
from irods.account import iRODSAccount
from irods.manager.collection_manager import CollectionManager
from irods.manager.data_object_manager import DataObjectManager
from irods.manager.metadata_manager import MetadataManager
from irods.manager.access_manager import AccessManager
from irods.manager.user_manager import UserManager, UserGroupManager
from irods.manager.resource_manager import ResourceManager
from irods.manager.zone_manager import ZoneManager
from irods.exception import NetworkException
from irods.password_obfuscation import decode
from irods import NATIVE_AUTH_SCHEME, PAM_AUTH_SCHEME
logger = logging.getLogger(__name__)
class iRODSSession(object):
def __init__(self, configure=True, **kwargs):
self.pool = None
self.numThreads = 0
if configure:
self.configure(**kwargs)
self.collections = CollectionManager(self)
self.data_objects = DataObjectManager(self)
self.metadata = MetadataManager(self)
self.permissions = AccessManager(self)
self.users = UserManager(self)
self.user_groups = UserGroupManager(self)
self.resources = ResourceManager(self)
self.zones = ZoneManager(self)
def __enter__(self):
return self
def __exit__(self, exc_type, exc_value, traceback):
self.cleanup()
def cleanup(self):
for conn in self.pool.active | self.pool.idle:
try:
conn.disconnect()
except NetworkException:
pass
conn.release(True)
def _configure_account(self, **kwargs):
try:
env_file = kwargs['irods_env_file']
except KeyError:
# For backward compatibility
for key in ['host', 'port', 'authentication_scheme']:
if key in kwargs:
kwargs['irods_{}'.format(key)] = kwargs.pop(key)
for key in ['user', 'zone']:
if key in kwargs:
kwargs['irods_{}_name'.format(key)] = kwargs.pop(key)
return iRODSAccount(**kwargs)
# Get credentials from irods environment file
creds = self.get_irods_env(env_file)
# Update with new keywords arguments only
creds.update((key, value) for key, value in kwargs.items() if key not in creds)
# Get auth scheme
try:
auth_scheme = creds['irods_authentication_scheme']
except KeyError:
# default
auth_scheme = 'native'
if auth_scheme.lower() == PAM_AUTH_SCHEME:
if 'password' in creds:
return iRODSAccount(**creds)
else:
# password will be from irodsA file therefore use native login
creds['irods_authentication_scheme'] = NATIVE_AUTH_SCHEME
elif auth_scheme != 'native':
return iRODSAccount(**creds)
# Native auth, try to unscramble password
try:
creds['irods_authentication_uid'] = kwargs['irods_authentication_uid']
except KeyError:
pass
creds['password'] = self.get_irods_password(**creds)
return iRODSAccount(**creds)
def configure(self, **kwargs):
account = self._configure_account(**kwargs)
connection_refresh_time = self.get_connection_refresh_time(**kwargs)
logger.debug("In iRODSSession's configure(). connection_refresh_time set to {}".format(connection_refresh_time))
self.pool = Pool(account, application_name=kwargs.pop('application_name',''), connection_refresh_time=connection_refresh_time)
def query(self, *args):
return Query(self, *args)
@property
def username(self):
return self.pool.account.client_user
@property
def zone(self):
return self.pool.account.client_zone
@property
def host(self):
return self.pool.account.host
@property
def port(self):
return self.pool.account.port
@property
def server_version(self):
try:
conn = next(iter(self.pool.active))
return conn.server_version
except StopIteration:
conn = self.pool.get_connection()
version = conn.server_version
conn.release()
return version
@property
def pam_pw_negotiated(self):
self.pool.account.store_pw = []
conn = self.pool.get_connection()
pw = getattr(self.pool.account,'store_pw',[])
delattr( self.pool.account, 'store_pw')
conn.release()
return pw
@property
def default_resource(self):
return self.pool.account.default_resource
@default_resource.setter
def default_resource(self, name):
self.pool.account.default_resource = name
@property
def connection_timeout(self):
return self.pool.connection_timeout
@connection_timeout.setter
def connection_timeout(self, seconds):
self.pool.connection_timeout = seconds
@staticmethod
def get_irods_password_file():
try:
return os.environ['IRODS_AUTHENTICATION_FILE']
except KeyError:
return os.path.expanduser('~/.irods/.irodsA')
@staticmethod
def get_irods_env(env_file):
try:
with open(env_file, 'rt') as f:
return json.load(f)
except IOError:
logger.debug("Could not open file {}".format(env_file))
return {}
@staticmethod
def get_irods_password(**kwargs):
try:
irods_auth_file = kwargs['irods_authentication_file']
except KeyError:
irods_auth_file = iRODSSession.get_irods_password_file()
try:
uid = kwargs['irods_authentication_uid']
except KeyError:
uid = None
with open(irods_auth_file, 'r') as f:
return decode(f.read().rstrip('\n'), uid)
def get_connection_refresh_time(self, **kwargs):
connection_refresh_time = -1
connection_refresh_time = int(kwargs.get('refresh_time', -1))
if connection_refresh_time != -1:
return connection_refresh_time
try:
env_file = kwargs['irods_env_file']
except KeyError:
return connection_refresh_time
if env_file is not None:
env_file_map = self.get_irods_env(env_file)
connection_refresh_time = int(env_file_map.get('irods_connection_refresh_time', -1))
if connection_refresh_time < 1:
# Negative values are not allowed.
logger.debug('connection_refresh_time in {} file has value of {}. Only values greater than 1 are allowed.'.format(env_file, connection_refresh_time))
connection_refresh_time = -1
return connection_refresh_time
|
{"/irods/test/query_test.py": ["/irods/column.py", "/irods/rule.py", "/irods/test/helpers.py"], "/irods/session.py": ["/irods/pool.py", "/irods/manager/data_object_manager.py", "/irods/manager/user_manager.py"], "/irods/pool.py": ["/irods/connection.py"], "/irods/test/user_group_test.py": ["/irods/test/helpers.py"], "/irods/test/helpers.py": ["/irods/session.py"], "/irods/test/meta_test.py": ["/irods/test/helpers.py"], "/irods/test/pool_test.py": ["/irods/test/helpers.py"], "/irods/test/login_auth_test.py": ["/irods/test/helpers.py", "/irods/connection.py", "/irods/session.py", "/irods/rule.py"], "/irods/test/rule_test.py": ["/irods/test/helpers.py", "/irods/rule.py"], "/irods/manager/user_manager.py": ["/irods/user.py"]}
|
22,663,458
|
alanking/python-irodsclient
|
refs/heads/master
|
/irods/rule.py
|
from __future__ import absolute_import
from irods.message import iRODSMessage, StringStringMap, RodsHostAddress, STR_PI, MsParam, MsParamArray, RuleExecutionRequest
from irods.api_number import api_number
from io import open as io_open
class Rule(object):
def __init__(self, session, rule_file=None, body='', params=None, output=''):
self.session = session
self.params = {}
self.output = ''
if rule_file:
self.load(rule_file)
else:
self.body = '@external\n' + body
# overwrite params and output if received arguments
if params is not None:
self.params = params
if output != '':
self.output = output
def load(self, rule_file, encoding = 'utf-8'):
self.body = '@external\n'
# parse rule file
with io_open(rule_file, encoding = encoding) as f:
for line in f:
# parse input line
if line.strip().lower().startswith('input'):
input_header, input_line = line.split(None, 1)
# sanity check
if input_header.lower() != 'input':
raise ValueError
# parse *param0="value0",*param1="value1",...
for pair in input_line.split(','):
label, value = pair.split('=')
self.params[label.strip()] = value.strip()
# parse output line
elif line.strip().lower().startswith('output'):
output_header, output_line = line.split(None, 1)
# sanity check
if output_header.lower() != 'output':
raise ValueError
# use line as is
self.output = output_line.strip()
# parse rule
else:
self.body += line
def execute(self):
# rule input
param_array = []
for label, value in self.params.items():
inOutStruct = STR_PI(myStr=value)
param_array.append(MsParam(label=label, type='STR_PI', inOutStruct=inOutStruct))
inpParamArray = MsParamArray(paramLen=len(param_array), oprType=0, MsParam_PI=param_array)
# rule body
addr = RodsHostAddress(hostAddr='', rodsZone='', port=0, dummyInt=0)
condInput = StringStringMap({})
message_body = RuleExecutionRequest(myRule=self.body, addr=addr, condInput=condInput, outParamDesc=self.output, inpParamArray=inpParamArray)
request = iRODSMessage("RODS_API_REQ", msg=message_body, int_info=api_number['EXEC_MY_RULE_AN'])
with self.session.pool.get_connection() as conn:
conn.send(request)
response = conn.recv()
out_param_array = response.get_main_message(MsParamArray)
self.session.cleanup()
return out_param_array
|
{"/irods/test/query_test.py": ["/irods/column.py", "/irods/rule.py", "/irods/test/helpers.py"], "/irods/session.py": ["/irods/pool.py", "/irods/manager/data_object_manager.py", "/irods/manager/user_manager.py"], "/irods/pool.py": ["/irods/connection.py"], "/irods/test/user_group_test.py": ["/irods/test/helpers.py"], "/irods/test/helpers.py": ["/irods/session.py"], "/irods/test/meta_test.py": ["/irods/test/helpers.py"], "/irods/test/pool_test.py": ["/irods/test/helpers.py"], "/irods/test/login_auth_test.py": ["/irods/test/helpers.py", "/irods/connection.py", "/irods/session.py", "/irods/rule.py"], "/irods/test/rule_test.py": ["/irods/test/helpers.py", "/irods/rule.py"], "/irods/manager/user_manager.py": ["/irods/user.py"]}
|
22,663,459
|
alanking/python-irodsclient
|
refs/heads/master
|
/irods/manager/data_object_manager.py
|
from __future__ import absolute_import
import os
import io
from irods.models import DataObject
from irods.manager import Manager
from irods.message import (
iRODSMessage, FileOpenRequest, ObjCopyRequest, StringStringMap, DataObjInfo, ModDataObjMeta)
import irods.exception as ex
from irods.api_number import api_number
from irods.data_object import (
iRODSDataObject, iRODSDataObjectFileRaw, chunks, irods_dirname, irods_basename)
import irods.keywords as kw
class DataObjectManager(Manager):
READ_BUFFER_SIZE = 1024 * io.DEFAULT_BUFFER_SIZE
WRITE_BUFFER_SIZE = 1024 * io.DEFAULT_BUFFER_SIZE
# Data object open flags (independent of client os)
O_RDONLY = 0
O_WRONLY = 1
O_RDWR = 2
O_APPEND = 1024
O_CREAT = 64
O_EXCL = 128
O_TRUNC = 512
def _download(self, obj, local_path, **options):
if os.path.isdir(local_path):
file = os.path.join(local_path, irods_basename(obj))
else:
file = local_path
# Check for force flag if file exists
if os.path.exists(file) and kw.FORCE_FLAG_KW not in options:
raise ex.OVERWRITE_WITHOUT_FORCE_FLAG
with open(file, 'wb') as f, self.open(obj, 'r', **options) as o:
for chunk in chunks(o, self.READ_BUFFER_SIZE):
f.write(chunk)
def get(self, path, file=None, **options):
parent = self.sess.collections.get(irods_dirname(path))
# TODO: optimize
if file:
self._download(path, file, **options)
query = self.sess.query(DataObject)\
.filter(DataObject.name == irods_basename(path))\
.filter(DataObject.collection_id == parent.id)\
.add_keyword(kw.ZONE_KW, path.split('/')[1])
results = query.all() # get up to max_rows replicas
if len(results) <= 0:
raise ex.DataObjectDoesNotExist()
return iRODSDataObject(self, parent, results)
def put(self, file, irods_path, return_data_object=False, **options):
if irods_path.endswith('/'):
obj = irods_path + os.path.basename(file)
else:
obj = irods_path
# Set operation type to trigger acPostProcForPut
if kw.OPR_TYPE_KW not in options:
options[kw.OPR_TYPE_KW] = 1 # PUT_OPR
with open(file, 'rb') as f, self.open(obj, 'w', **options) as o:
for chunk in chunks(f, self.WRITE_BUFFER_SIZE):
o.write(chunk)
if kw.ALL_KW in options:
options[kw.UPDATE_REPL_KW] = ''
self.replicate(obj, **options)
if return_data_object:
return self.get(obj)
def create(self, path, resource=None, **options):
options[kw.DATA_TYPE_KW] = 'generic'
if resource:
options[kw.DEST_RESC_NAME_KW] = resource
else:
# Use client-side default resource if available
try:
options[kw.DEST_RESC_NAME_KW] = self.sess.default_resource
except AttributeError:
pass
message_body = FileOpenRequest(
objPath=path,
createMode=0o644,
openFlags=0,
offset=0,
dataSize=-1,
numThreads=self.sess.numThreads,
oprType=0,
KeyValPair_PI=StringStringMap(options),
)
message = iRODSMessage('RODS_API_REQ', msg=message_body,
int_info=api_number['DATA_OBJ_CREATE_AN'])
with self.sess.pool.get_connection() as conn:
conn.send(message)
response = conn.recv()
desc = response.int_info
conn.close_file(desc)
return self.get(path)
def open(self, path, mode, **options):
if kw.DEST_RESC_NAME_KW not in options:
# Use client-side default resource if available
try:
options[kw.DEST_RESC_NAME_KW] = self.sess.default_resource
except AttributeError:
pass
flags, seek_to_end = {
'r': (self.O_RDONLY, False),
'r+': (self.O_RDWR, False),
'w': (self.O_WRONLY | self.O_CREAT | self.O_TRUNC, False),
'w+': (self.O_RDWR | self.O_CREAT | self.O_TRUNC, False),
'a': (self.O_WRONLY | self.O_CREAT, True),
'a+': (self.O_RDWR | self.O_CREAT, True),
}[mode]
# TODO: Use seek_to_end
try:
oprType = options[kw.OPR_TYPE_KW]
except KeyError:
oprType = 0
message_body = FileOpenRequest(
objPath=path,
createMode=0,
openFlags=flags,
offset=0,
dataSize=-1,
numThreads=self.sess.numThreads,
oprType=oprType,
KeyValPair_PI=StringStringMap(options),
)
message = iRODSMessage('RODS_API_REQ', msg=message_body,
int_info=api_number['DATA_OBJ_OPEN_AN'])
conn = self.sess.pool.get_connection()
conn.send(message)
desc = conn.recv().int_info
return io.BufferedRandom(iRODSDataObjectFileRaw(conn, desc, **options))
def unlink(self, path, force=False, **options):
if force:
options[kw.FORCE_FLAG_KW] = ''
try:
oprType = options[kw.OPR_TYPE_KW]
except KeyError:
oprType = 0
message_body = FileOpenRequest(
objPath=path,
createMode=0,
openFlags=0,
offset=0,
dataSize=-1,
numThreads=self.sess.numThreads,
oprType=oprType,
KeyValPair_PI=StringStringMap(options),
)
message = iRODSMessage('RODS_API_REQ', msg=message_body,
int_info=api_number['DATA_OBJ_UNLINK_AN'])
with self.sess.pool.get_connection() as conn:
conn.send(message)
response = conn.recv()
def unregister(self, path, **options):
# https://github.com/irods/irods/blob/4.2.1/lib/api/include/dataObjInpOut.h#L190
options[kw.OPR_TYPE_KW] = 26
self.unlink(path, **options)
def exists(self, path):
try:
self.get(path)
except ex.DoesNotExist:
return False
return True
def move(self, src_path, dest_path):
# check if dest is a collection
# if so append filename to it
if self.sess.collections.exists(dest_path):
filename = src_path.rsplit('/', 1)[1]
target_path = dest_path + '/' + filename
else:
target_path = dest_path
src = FileOpenRequest(
objPath=src_path,
createMode=0,
openFlags=0,
offset=0,
dataSize=0,
numThreads=self.sess.numThreads,
oprType=11, # RENAME_DATA_OBJ
KeyValPair_PI=StringStringMap(),
)
dest = FileOpenRequest(
objPath=target_path,
createMode=0,
openFlags=0,
offset=0,
dataSize=0,
numThreads=self.sess.numThreads,
oprType=11, # RENAME_DATA_OBJ
KeyValPair_PI=StringStringMap(),
)
message_body = ObjCopyRequest(
srcDataObjInp_PI=src,
destDataObjInp_PI=dest
)
message = iRODSMessage('RODS_API_REQ', msg=message_body,
int_info=api_number['DATA_OBJ_RENAME_AN'])
with self.sess.pool.get_connection() as conn:
conn.send(message)
response = conn.recv()
def copy(self, src_path, dest_path, **options):
# check if dest is a collection
# if so append filename to it
if self.sess.collections.exists(dest_path):
filename = src_path.rsplit('/', 1)[1]
target_path = dest_path + '/' + filename
else:
target_path = dest_path
src = FileOpenRequest(
objPath=src_path,
createMode=0,
openFlags=0,
offset=0,
dataSize=0,
numThreads=self.sess.numThreads,
oprType=10, # COPY_SRC
KeyValPair_PI=StringStringMap(),
)
dest = FileOpenRequest(
objPath=target_path,
createMode=0,
openFlags=0,
offset=0,
dataSize=0,
numThreads=self.sess.numThreads,
oprType=9, # COPY_DEST
KeyValPair_PI=StringStringMap(options),
)
message_body = ObjCopyRequest(
srcDataObjInp_PI=src,
destDataObjInp_PI=dest
)
message = iRODSMessage('RODS_API_REQ', msg=message_body,
int_info=api_number['DATA_OBJ_COPY_AN'])
with self.sess.pool.get_connection() as conn:
conn.send(message)
response = conn.recv()
def truncate(self, path, size, **options):
message_body = FileOpenRequest(
objPath=path,
createMode=0,
openFlags=0,
offset=0,
dataSize=size,
numThreads=self.sess.numThreads,
oprType=0,
KeyValPair_PI=StringStringMap(options),
)
message = iRODSMessage('RODS_API_REQ', msg=message_body,
int_info=api_number['DATA_OBJ_TRUNCATE_AN'])
with self.sess.pool.get_connection() as conn:
conn.send(message)
response = conn.recv()
def replicate(self, path, resource=None, **options):
if resource:
options[kw.DEST_RESC_NAME_KW] = resource
message_body = FileOpenRequest(
objPath=path,
createMode=0,
openFlags=0,
offset=0,
dataSize=-1,
numThreads=self.sess.numThreads,
oprType=6,
KeyValPair_PI=StringStringMap(options),
)
message = iRODSMessage('RODS_API_REQ', msg=message_body,
int_info=api_number['DATA_OBJ_REPL_AN'])
with self.sess.pool.get_connection() as conn:
conn.send(message)
response = conn.recv()
def register(self, file_path, obj_path, **options):
options[kw.FILE_PATH_KW] = file_path
message_body = FileOpenRequest(
objPath=obj_path,
createMode=0,
openFlags=0,
offset=0,
dataSize=0,
numThreads=self.sess.numThreads,
oprType=0,
KeyValPair_PI=StringStringMap(options),
)
message = iRODSMessage('RODS_API_REQ', msg=message_body,
int_info=api_number['PHY_PATH_REG_AN'])
with self.sess.pool.get_connection() as conn:
conn.send(message)
response = conn.recv()
def modDataObjMeta(self, data_obj_info, meta_dict, **options):
if "rescHier" not in data_obj_info and "rescName" not in data_obj_info and "replNum" not in data_obj_info:
meta_dict["all"] = ""
message_body = ModDataObjMeta(
dataObjInfo=DataObjInfo(
objPath=data_obj_info["objPath"],
rescName=data_obj_info.get("rescName", ""),
rescHier=data_obj_info.get("rescHier", ""),
dataType="",
dataSize=0,
chksum="",
version="",
filePath="",
dataOwnerName="",
dataOwnerZone="",
replNum=data_obj_info.get("replNum", 0),
replStatus=0,
statusString="",
dataId=0,
collId=0,
dataMapId=0,
flags=0,
dataComments="",
dataMode="",
dataExpiry="",
dataCreate="",
dataModify="",
dataAccess="",
dataAccessInx=0,
writeFlag=0,
destRescName="",
backupRescName="",
subPath="",
specColl=0,
regUid=0,
otherFlags=0,
KeyValPair_PI=StringStringMap(options),
in_pdmo="",
next=0,
rescId=0
),
regParam=StringStringMap(meta_dict)
)
message = iRODSMessage('RODS_API_REQ', msg=message_body,
int_info=api_number['MOD_DATA_OBJ_META_AN'])
with self.sess.pool.get_connection() as conn:
conn.send(message)
response = conn.recv()
|
{"/irods/test/query_test.py": ["/irods/column.py", "/irods/rule.py", "/irods/test/helpers.py"], "/irods/session.py": ["/irods/pool.py", "/irods/manager/data_object_manager.py", "/irods/manager/user_manager.py"], "/irods/pool.py": ["/irods/connection.py"], "/irods/test/user_group_test.py": ["/irods/test/helpers.py"], "/irods/test/helpers.py": ["/irods/session.py"], "/irods/test/meta_test.py": ["/irods/test/helpers.py"], "/irods/test/pool_test.py": ["/irods/test/helpers.py"], "/irods/test/login_auth_test.py": ["/irods/test/helpers.py", "/irods/connection.py", "/irods/session.py", "/irods/rule.py"], "/irods/test/rule_test.py": ["/irods/test/helpers.py", "/irods/rule.py"], "/irods/manager/user_manager.py": ["/irods/user.py"]}
|
22,786,540
|
xinruoyusixian/bemfa_light
|
refs/heads/master
|
/main.py
|
import time
import bafa
led_Red=15
led_Green=12 #绿灯引脚
led_Blue=13 #蓝灯引脚
led_Green=lib.flashLed(12)#绿灯引脚
led_Red=lib.flashLed(15)#红灯引脚
led_Blue=lib.flashLed(13)#蓝灯引脚
led_Green.sw(0)
led_Red.sw(0)
led_Blue.sw(0)
try:
import cfg
ssd=cfg.ssd
pwd=cfg.pwd
Prav_key=cfg.key
except:
ssd="wifi"
pwd="1234567788"
Prav_keykey=''
#发送消息到串口
def p_data(topic,msg):
print(topic,msg)
#订阅灯 TOPIC
t=0
c=bafa.bfMqtt(Prav_key,"light002",p_data)
c.connect()
#订阅空调 TOPIC
light=bafa.bfMqtt(Prav_key,"ac005",p_data)
light.connect()
led_Blue.sw(0)
try:
while 1:
if not wifi.isconnected():
led_Green.sw(0)
led_Blue.sw(0)
led_Red.sw(delay=500)
continue
led_Blue.sw(2)
if c.online:
delay_time=40
led_Red.sw(0)
led_Green.sw(delay=1000)
else:
delay_time=2
led_Green.sw(0)
led_Red.sw(delay=1000)
if time.time()%delay_time==0:
c.ping()
time.sleep(1)
c.check_msg()
light.check_msg()
except Exception as e:
machine.reset()
|
{"/main-1.py": ["/lib.py", "/IR_Model.py"], "/boot.py": ["/lib.py"]}
|
22,786,541
|
xinruoyusixian/bemfa_light
|
refs/heads/master
|
/lib.py
|
import network
from machine import Pin, PWM ,RTC,Timer
import time,machine,ntptime,sys
def ap(ssd,pwd=''):
AP= network.WLAN(network.AP_IF)
if ssd=='':
AP.active(0)
return (AP,True)
try:
AP.active(1)
AP.config(essid=ssd, authmode=network.AUTH_WPA_WPA2_PSK, password=pwd) if pwd != '' else AP.config(essid=ssd, authmode=network.AUTH_OPEN)
return (AP,True)
except Exception as e:
print (e)
return (AP,False)
def file(file,c=''):
if c=='':
try:
f=open(file,"r")
return f.read()
except Exception as e:
print(e,"文件不存在")
return False
else:
f=open(file,"w")
f.write(c)
f.flush()
f.close()
class flashLed:
def __init__(self,pin):
self.pin=Pin(pin,Pin.OUT)
self.delay=500
self._time1=time.ticks_ms()
self.period=1
self.freq=100
self.max=1022
self.duty=self.max
def timer(self,cb):
self.tim=Timer(-1)
self.tim.init(period=self.period, mode=Timer.PERIODIC, callback=cb)
def sw(self,s=2,delay=0):
if type(s).__name__=="Timer" or s==2:
self.delay= self.delay if delay==0 else delay
if (time.ticks_ms()- self._time1)>self.delay:
self.pin.value(0) if self.pin.value() else self.pin.value(1)
self._time1=time.ticks_ms()
return
if s==1:
self.pin.value(1)
return
if s==0:
self.pin.value(0)
return
if s=="":
return self.pin.value()
def flash(self,delay=250):
self.delay=delay
self.timer(self.sw)
return
def stop(self):
try:
self.tim.deinit()
del self.tim
except:
pass
try:
time.sleep_ms(50)
self.pwm.deinit()
except:
pass
self.pin.init(Pin.OUT)
return
def bre(self,loop=1,step=1):
self.step=step
if loop==1:
self.stop()
self.timer(self.repat)
if loop==0:
self.repat()
return
def repat(self,s=1):
self.step=s if type(s).__name__!="Timer" else self.step
self.pwm = PWM(self.pin)
self.duty=self.duty-self.step
if self.duty< -self.max:
self.duty=self.max
self.pwm.init(freq=self.freq, duty=abs(self.duty))
return
def update_time():
ntptime.host='ntp1.aliyun.com'
try:
ntptime.settime()
except:
print("TIME UPGRADE FAILED")
return
list=time.localtime(time.time()+8*60*60)
rtc = RTC()
rtc.datetime((list[0], list[1], list[2] ,None,list[3], list[4], list[5] ,0))
print (rtc.datetime())
def wifi(ssd='',pwd='',hostname="MicroPython"):
wifi0 = network.WLAN(network.STA_IF)
wifi0.active(1)
if ssd=='':
return (wifi0,'')
wifi0.active(True) #激活WIFI
# 启用mdns
wifi0.config(dhcp_hostname=hostname,mac=wifi0.config('mac'))
wifi0.disconnect()
_s_time=time.time()
if not wifi0.isconnected(): #判断WIFI连接状态
print('[WIFI]:Connect to',ssd)
wifi0.connect(ssd, pwd) #essid为WIFI名称,password为WIFI密码
while not wifi0.isconnected():
if (time.time()- _s_time)>5:
print('[WIFI]:Connect Faied')
return (wifi0,False)
print('[WIFI]:', wifi0.ifconfig())
return (wifi0,True)
class btn:
def __init__(self,p):
self.time_ms=time.ticks_ms
self._btn=Pin(p,Pin.IN)
self._btn.irq(handler=self.FALLING,trigger=(Pin.IRQ_FALLING))
self.tim=Timer(-999)
self.pressTime=500
self.clickTimeMin=80#单机最小时间
self.timeRising=0
self.cb_press=None
self.cb_click=None
self.cb_click2=None
self.diffTime1=999
self.timeArr=[0,0]
def FALLING(self,_e=0):
self.timeFalling=self.time_ms()
self.timeArr.append(self.timeFalling)
self.timeRising=0
self.tim.init(period=1, mode=Timer.PERIODIC, callback=self.check)
self._btn.irq(handler=self.RISING,trigger=(Pin.IRQ_RISING))
def clickDely(self,_e=0):
self.diffTime1=self.time_ms()-self.clickRuntime
if self.diffTime1>300:
self.tim1.deinit()
print("click")
self.cb(self.cb_click)
def RISING(self,_e=0):
self.timeRising=self.time_ms()
self.tim.deinit()
self._btn.irq(handler=self.FALLING,trigger=(Pin.IRQ_FALLING))
diffTime=self.timeRising-self.timeFalling
if diffTime > self.clickTimeMin and diffTime <self.pressTime :
#click event delay, if you don't want to use doubleClick you can delete it,put click code at here
if self.diffTime1<300 and (self.time_ms()-self.timeArr[-2])<500:
self.tim1.deinit()
print("doubleClick")
self.cb(self.cb_click2)
return
self.clickRuntime=self.time_ms()
self.tim1=Timer(-998)
self.tim1.init(period=1, mode=Timer.PERIODIC, callback=self.clickDely)
def press(self,cb,s=0):
self.cb_press=cb
self.pressTime= self.pressTime if s==0 else s
def click(self,cb):
self.cb_click=cb
def cb(self,cb):
if cb.__class__.__name__ != 'NoneType':
cb()
def doubleClick(self,cb):
self.cb_click2=cb
def check(self,_e=0):
diffTime=self.time_ms()-self.timeFalling
if diffTime >= self.pressTime:
print("press",diffTime)
self.tim.deinit()
self.cb(self.cb_press)
|
{"/main-1.py": ["/lib.py", "/IR_Model.py"], "/boot.py": ["/lib.py"]}
|
22,786,542
|
xinruoyusixian/bemfa_light
|
refs/heads/master
|
/main-1.py
|
from machine import Pin,UART
from urequests import get
import time ,lib,_thread,machine,ujson,os
from IR_Model import IR
_ir= IR(23,5)
send=_ir.uartSend
read=_ir.read
def ir():
while 1:
d=_ir.main()
if d!= None :
print(d)
_thread.start_new_thread(ir, ())
class btn:
def __init__(self,cb):
self.debug=0
#cb:需要触发的函数
self.start=0
self.cb=cb
def click(self,_0=4):
#按键消抖
#_0:为无效参数,防止出错
t=time.ticks_ms()-self.start
if t<100:
return
if self.debug:
print("Click",time.ticks_ms(),t)
self.start=time.ticks_ms()
self.cb()
class acTurn:
def __init__(self):
self.state=0
self.dir="ir_Data"
try:
self.list=os.listdir(self.dir)
except:
print ("遥控错误")
return
def run(self):
list_len=len(self.list)
print(self.list[self.state])
send(read(self.dir+self.list[self.state]))
if self.state>=(list_len-1):
self.state=0
self.state=self.state+1
def off(self):
print("click")
if self.list[self.state]!='Ac_btn-off':
self.state=self.list.index("Ac_btn-off")
send(read(self.dir+"/Ac_btn-off"))
else:
self.state=0
send(read(self.dir+"/"+self.list[self.state]))
ac= acTurn()
#按键循环切换
#_26=btn(ac.run)
#_26_btn=Pin(26,Pin.IN)
#_26_btn.irq(handler=_26.click,trigger=(Pin.IRQ_FALLING))
#按键控制开关
_25=btn(ac.off)
_25_btn=Pin(32,Pin.IN)
_25_btn.irq(handler=_25.click,trigger=(Pin.IRQ_FALLING))
uart = UART(2, baudrate=115200, rx=26,tx=33,timeout=10)
def resp(topic,msg):
try:
if topic=="light002":
if msg=="on":
lib.pin(16,1)
print("lighton")
return
if msg=="off":
print("lightoff")
lib.pin(16,0)
return
return
if topic=="ac005":
msg_ac=msg.split("#")
print(msg_ac )
if msg_ac[0]=="on":
send(read(ac.dir+"/Ac_btn-"+msg_ac[2]))
print(ac.dir+"/Ac_btn-"+msg_ac[2])
if msg_ac[0]=="off":
send(read(ac.dir+"/Ac_btn-off"))
print(ac.dir+"/Ac_btn-off")
return
except :
print("err")
def loop():
while 1 :
if uart.any():
a=uart.read()
try:
res=a[2:2-5].decode().replace("b'",'').replace("'",'').split(" ")
print(res)
if len(res)==2:
resp(res[0],res[1])
except:
print("解析失败")
_thread.start_new_thread(loop, ())
|
{"/main-1.py": ["/lib.py", "/IR_Model.py"], "/boot.py": ["/lib.py"]}
|
22,786,543
|
xinruoyusixian/bemfa_light
|
refs/heads/master
|
/IR_Model.py
|
## IR MODE
from machine import UART
import time,os
class IR:
def __init__(self,rx,tx):
self.uart = UART(1, baudrate=115200, rx=rx,tx=tx,timeout=10)
self._write_flag=0
self.dir="ir_Data"
self.ac_state=0
def exsit_dir(self):
try:
os.chdir(self.dir)
os.chdir("../")
except:
os.mkdir(self.dir)
def uartSend(self,t):
self.uart.write(t)
def write(self,name,str):
self.exsit_dir()
f=open(name,"wb")
f.write(str)
f.close()
def read(self,name):
self.exsit_dir()
f=open(name,"rb")
data=f.read()
f.close()
return data
def main(self):
if self.uart.any():
a=self.uart.read()
print(a)
if a!=b'\xfe\xfc\xcf':
if self._write_flag:
file_name=self.dir+"/Ac_"+ self._write_flag
self.write(file_name,a)
print (self._write_flag,":已写入。")
self._write_flag=0
return a
|
{"/main-1.py": ["/lib.py", "/IR_Model.py"], "/boot.py": ["/lib.py"]}
|
22,786,544
|
xinruoyusixian/bemfa_light
|
refs/heads/master
|
/boot.py
|
import uos, machine,gc
gc.enable()
try:
import lib
except:
pass
device="Light"
power=lib.flashLed(0)#开关控制引脚
led=lib.flashLed(2)
_cfg="cfg.py"
_Stat="stat"
power.sw( 1 if lib.file(_Stat)=="1" else 0 )
def setFile(s=1):
file="isRset.py"
num=lib.file(file)
if type(s).__name__=="Timer" or s==1 or s=='r':
if num:
if s=='r':
return int(num)
num=int(num)
lib.file(file,str(num+1))
return num+1
else:
if s=='r':
return False
lib.file(file,"0")
if s==0:
lib.file(file,"0")
return 1
if s==4:
lib.file(file,"4")
return 4
def _reset(s=1):
lib.file("isRset.py","4")
machine.reset()
led.flash(50)
print("\n========:",lib.file("isRset.py"))
machine.Timer(-1).init(period=5000, mode=machine.Timer.ONE_SHOT, callback=lambda t:print(setFile(0))) #1次
if int(lib.file("isRset.py")) >=3:
import webrepl,time
webrepl.start()
led.flash(1000)
from httpServer import http
def wifi_setup(url):
if url =="/":
serv.sendall('<form action="wifi">SSD:<br><input type="text" name="ssd" value=""><br>PASSWORD<br><input type="text" name="pwd" value=""><hr>KEY<br><input type="text" name="key" value=""><input type="submit" value="Submit"></form> ')
serv.sendall('<hr/>')
ap_list=lib.wifi()[0].scan()
for i in ap_list:
serv.sendall("%s ,%d<br/>"%(i[0].decode(),i[3]))
if url.find("/wifi")!=-1:
d=(serv.get_Args(url))
print(d)
if d.get("ssd") !=None and d.get("pwd")!=None:
conf="ssd='%s'\r\npwd='%s' \r\nkey='%s'"%(d.get("ssd"),d.get("pwd"),d.get("key"))
lib.file(_cfg,conf)
serv.send("\r\n")
serv.send("设置成功,即将重启。")
machine.sleep(3000)
machine.reset()
else:
serv.send("666 \r\n")
lib.ap(device)
serv=http("0.0.0.0",80)
while 1:
if time.ticks_ms()==180000:
machine.reset()
serv.http(wifi_setup)
raise
try:
import cfg
ssd=cfg.ssd
pwd=cfg.pwd
key=cfg.key
except Exception as e:
print(e)
#_reset()
wifi=lib.wifi(ssd,pwd,device)[0]
led.stop()
led.sw(1)
print("=======boot.py========")
del setFile
gc.collect()
|
{"/main-1.py": ["/lib.py", "/IR_Model.py"], "/boot.py": ["/lib.py"]}
|
22,827,681
|
ricci5791/Automotive_delivery_system
|
refs/heads/master
|
/backend_api/databaseadapter.py
|
from django.db.models import QuerySet
from backend_api import models as api_models
class DatabaseAdapter:
@staticmethod
def get_arrival(delivery_id: int) -> tuple[float, ...]:
return tuple([float(x) for x in api_models.Order.objects.get(id=delivery_id).arrival_point.split(";")])
@staticmethod
def get_departure(delivery_id: int) -> tuple[float, ...]:
return tuple([float(x) for x in api_models.Order.objects.get(id=delivery_id).departure_point.split(";")])
@staticmethod
def get_user_orders(recipient_token: int) -> QuerySet:
return api_models.Order.objects.get(recipient_token=recipient_token)
@staticmethod
def get_order_info(order_id: int) -> QuerySet:
return api_models.Order.objects.get(id=order_id)
|
{"/backend_api/pathfinder.py": ["/backend_api/databaseadapter.py"], "/backend_api/views.py": ["/backend_api/databaseadapter.py", "/backend_api/pathfinder.py"], "/Backend/urls.py": ["/backend_api/views.py"]}
|
22,831,055
|
brauden/car-project
|
refs/heads/main
|
/crglst/crglst/spiders/cars.py
|
import scrapy
from ..items import CrglstItem
import os
from os.path import dirname
from urllib.parse import urljoin
current_dir = os.path.dirname(__file__)
top_dir = dirname(dirname(dirname(current_dir)))
csv_file = os.path.join(top_dir, 'csv_files/data.csv')
class ExploitSpider(scrapy.Spider):
name = 'crglst'
allowed_domains = ['https://www.craigslist.org/about/sites#US']
start_urls = []
handle_httpstatus_list = [403]
def __init__(self):
page_number = 120
urls = ['https://raleigh.craigslist.org/d/cars-trucks-by-owner/search/cto?hasPic=1',
'https://NewYork.craigslist.org/d/cars-trucks-by-owner/search/cto?hasPic=1',
'https://LosAngeles.craigslist.org/d/cars-trucks-by-owner/search/cto?hasPic=1',
'https://LosAngeles.craigslist.org/d/cars-trucks-by-owner/search/cto?hasPic=1',
'https://Chicago.craigslist.org/d/cars-trucks-by-owner/search/cto?hasPic=1',
'https://Houston.craigslist.org/d/cars-trucks-by-owner/search/cto?hasPic=1',
'https://Phoenix.craigslist.org/d/cars-trucks-by-owner/search/cto?hasPic=1',
'https://Philadelphia.craigslist.org/d/cars-trucks-by-owner/search/cto?hasPic=1',
'https://SanAntonio.craigslist.org/d/cars-trucks-by-owner/search/cto?hasPic=1',
'https://SanDiego.craigslist.org/d/cars-trucks-by-owner/search/cto?hasPic=1',
'https://Dallas.craigslist.org/d/cars-trucks-by-owner/search/cto?hasPic=1',
'https://Austin.craigslist.org/d/cars-trucks-by-owner/search/cto?hasPic=1',
'https://Jacksonville.craigslist.org/d/cars-trucks-by-owner/search/cto?hasPic=1',
'https://Columbus.craigslist.org/d/cars-trucks-by-owner/search/cto?hasPic=1',
'https://Charlotte.craigslist.org/d/cars-trucks-by-owner/search/cto?hasPic=1',
'https://SanFrancisco.craigslist.org/d/cars-trucks-by-owner/search/cto?hasPic=1',
'https://Indianapolis.craigslist.org/d/cars-trucks-by-owner/search/cto?hasPic=1',
'https://Seattle.craigslist.org/d/cars-trucks-by-owner/search/cto?hasPic=1',
'https://Denver.craigslist.org/d/cars-trucks-by-owner/search/cto?hasPic=1'
]
for url in urls:
self.start_urls.append(url)
for i in range(1,25):
next_page = url + '&s=' + str(i*page_number)
self.start_urls.append(next_page)
# def start_requests(self):
# for url in self.start_urls:
# yield Request(url, callback=self.parse)
def parse(self, response):
items = CrglstItem()
car_year_name = response.css('.hdrlnk::text').extract()
car_price = response.css('.result-meta .result-price').css('::text').extract()
car_urls = response.xpath('//a/@data-ids').extract()
# make each one into a full URL and add to item[]
# d_car_urls = response.selector.xpath('//img/@src').extract() #('img::attr("src")').extract()
# img_urls = [urljoin(response.url, src)
# for src in d_car_urls]
# items['image_urls'] = img_urls
#car_total = response.css('.totalcount::text').extract()
#car_info = response.css('.result-meta .result-price , .hdrlnk').css('::text').extract()
# for i in range(len(car_price)):
# append_csv_file(car_year_name[i],car_price[i])
for i in range(len(car_price)):
items['car_year_name'] = car_year_name[i]
items['car_price'] = car_price[i]
if ',' in car_urls[i]:
lst = ["https://images.craigslist.org/{}_300x300.jpg".format(i[2:]) for i in car_urls[i].split(',')]
items['file_urls'] = lst
else:
items['file_urls'] = "https://images.craigslist.org/" + car_urls[i][2:] + "_300x300.jpg"
yield items
#print('{} - {}'. format(car_year_name,car_price))
# for url in self.start_urls:
# next_page = url + '?s=' + str(ExploitSpider.page_number)
# if ExploitSpider.page_number < 3000:
# ExploitSpider.page_number = ExploitSpider.page_number + 120
# yield response.follow(next_page, callback = self.parse,dont_filter=True)
# def append_csv_file(car_year_name,car_price):
# line = f"{car_year_name} - {car_price}\n"
# if not os.path.exists(csv_file):
# with open(csv_file, 'w') as _f:
# _f.write(line)
# return
# with open(csv_file, 'a') as _f:
# _f.write(line)
|
{"/servers/similarity_app.py": ["/models/feature_vectors_model.py"]}
|
22,845,934
|
rodrigoneal/desafio-digistarts
|
refs/heads/master
|
/resources/conjunto.py
|
from typing import Any
from flask_restful import Resource, reqparse
numeros = (
[]
) # variavel que armazena os dicionarios contento os valores numericos -1000<=K<=1000
limite = 0 # variavel de controle 1<=N<=1000
req = reqparse.RequestParser()
req.add_argument(
"number", type=int, required=True, help="number only accepts integer value"
), 400
def verifica_numeros():
"""
Verifica se o tamanho de numeros é igual valor limite
:return: lista com os numeros unicos e ordenados
"""
global id
resultado = list()
if len(numeros) == limite:
for num in numeros:
n = int(num["number"])
if n not in resultado:
resultado.append(n)
resultado.sort()
numeros.clear()
id = 0
return resultado
def limit_not_defined(func):
"""
Decorador que verifica se o valor de limite foi passado e quebra a função se não tiver
:param func: função decorada
:return: None ou quebra a função com um status_code 400
"""
global limite
def deco_function(*args, **kwargs):
if limite <= 0:
return {"message": "the limit value must be passed before"}, 400
return func(*args, **kwargs)
return deco_function
class ListaConjuntos(Resource):
global limite
"""
A classe é usada pela biblioteca flask_restful trabalhar os verbos http
Não tem repr pois não é usada fora do contexto do flask, nem instanciada no flask shell
"""
def get(self):
"""
Mostra todos os arquivos dentro da lista de numeros no endpoit /
:return: Uma lista com dicionarios [{id:valor, number:valor}]
:rtype: JSON
"""
return numeros
@limit_not_defined
def post(self):
"""
Cria um dicionario e appenda(armazena) dentro da variavel numeros
:return:Um Json com o valor com o id e valor recebido
:rtype: JSON
"""
# ID: usada como identificar para facilita o acessos e modificações
global id
numero = req.parse_args()
number = {"id": id, **numero}
numeros.append(number)
id += 1
resultado = verifica_numeros()
if resultado: return resultado
return number, 201
class Limite(Resource):
"""
A classe é usada pela biblioteca flask_restful trabalhar os verbos http
"""
def post(self, limit):
"""
Recebe o valor por endpoint e define o limite de valores aceitos antes de retorna uma lista unica e ordenada
:return: JSON informado o valor de limite passado
:rtype: JSON
"""
limit = int(limit)
global limite, id
limite = limit
numeros.clear()
id = 0
return {"message": f"limit {limit}"}, 201
class ListaConjunto(Resource):
@staticmethod
def id_not_found(numeros: list[dict], id: int) -> Any:
"""
Procura o id passdo dentro da lista numeros
:param numeros: lista que armazena o dicionario
:param id: id recebido por endpoint
:return: 404 se não encotrar o id ou dicionario com o id pesquisado
"""
for num in numeros:
if num["id"] == id:
return num
return {"message": "id not found"}, 404
"""
A classe é usada pela biblioteca flask_restful trabalhar os verbos http
"""
def get(self, num_id):
"""
Procura dentro da varialvel numeros se há o id passado por endpoint
:return:Se Encontrar: Json com a id passada
:return:Se Não Encontrar: Uma mensagem com o status_code 404
"""
num_id = int(num_id)
resultado = self.id_not_found(numeros, num_id)
return resultado
@limit_not_defined
def put(self, num_id):
"""
Procura dentro da varialvel numeros se há o id passado por endpoint
:return: Se Encontrar: Cria um novo dicionario com o valor de id passado por endpoint com o valor number passado por
requests
:return Se encontrar modifica o dicionario com o valor number passado por request
"""
numero = req.parse_args()
global id, limite
num_id = int(num_id)
if numeros:
for num in numeros:
if num["id"] == num_id:
num["number"] = numero["number"]
return {"message": f"id {num_id} has been modified"}
number = {"id": num_id, **numero}
numeros.append(number)
id = num_id + 1
resultado = verifica_numeros()
if resultado: return verifica_numeros()
return {"message": f"id '{num_id}' successfully added"}, 201
@limit_not_defined
def delete(self, num_id):
"""
Deleta o dicionario com o id passado por endpoint
:return: Mensagem informado se o valor foi deletado
:rtype: JSON
"""
num_id = int(num_id)
global numeros
if numeros:
for n in range(len(numeros)):
if numeros[n]["id"] == num_id:
del numeros[n]
return {"message": f"The id {num_id} has been deleted"}
return {"message": f" id '{num_id}' not found"}, 404
|
{"/desafio_binario/test/test_calculator_bin.py": ["/desafio_binario/binary_calculator.py"], "/desafio_conjunto/test/test_set_unique.py": ["/desafio_conjunto/return_unique.py"], "/app.py": ["/resources/conjunto.py"]}
|
22,845,935
|
rodrigoneal/desafio-digistarts
|
refs/heads/master
|
/app.py
|
from flask import Flask
from flask_restful import Api
from resources.conjunto import ListaConjuntos, ListaConjunto, Limite
def create_app():
app = Flask(__name__)
api = Api(app)
api.add_resource(ListaConjuntos, "/")
api.add_resource(ListaConjunto, "/id/<num_id>")
api.add_resource(Limite, "/limit/<limit>")
return app
if __name__ == "__main__":
app = create_app()
app.run(debug=True)
|
{"/desafio_binario/test/test_calculator_bin.py": ["/desafio_binario/binary_calculator.py"], "/desafio_conjunto/test/test_set_unique.py": ["/desafio_conjunto/return_unique.py"], "/app.py": ["/resources/conjunto.py"]}
|
22,845,936
|
rodrigoneal/desafio-digistarts
|
refs/heads/master
|
/test/test_app.py
|
import requests
import pytest
from random import randint
def test_app_is_alive():
response = requests.get('http://127.0.0.1:5000/')
assert response.status_code == 200
def test_get():
response = requests.get('http://127.0.0.1:5000/')
assert response.status_code == 200
def test_post_without_passing_limit():
response = requests.post('http://127.0.0.1:5000/', json={'number': 5})
assert response.status_code == 201
def test_status_code_404_not_defined_limit():
response = requests.post('http://127.0.0.1:5000/limit/')
assert response.status_code == 404
def test_status_code_201_defined_limit():
response = requests.post('http://127.0.0.1:5000/limit/4')
assert response.status_code == 201
def test_return_json_post_passed_value_number():
numero = randint(-1000, 1000)
response = requests.post('http://127.0.0.1:5000/', json={"number": numero})
assert response.json() == {'id': 0, 'number': numero}
def test_status_code_200_put_passed_id():
response = requests.put('http://127.0.0.1:5000/id/0', json={"number": 8})
assert response.status_code == 200
def test_return_json_value_change_with_put():
post = requests.post('http://127.0.0.1:5000/', json={"number": 15})
assert post.json() == {'id': 1, 'number': 15}
requests.put('http://127.0.0.1:5000/id/1', json={"number": 10})
response = requests.get('http://127.0.0.1:5000/id/1')
assert response.json() == {'id': 1, 'number': 10}
|
{"/desafio_binario/test/test_calculator_bin.py": ["/desafio_binario/binary_calculator.py"], "/desafio_conjunto/test/test_set_unique.py": ["/desafio_conjunto/return_unique.py"], "/app.py": ["/resources/conjunto.py"]}
|
22,901,611
|
whitercactus/zombies
|
refs/heads/main
|
/spritesheet.py
|
from settings import *
class SpriteSheet(object):
def __init__(self,filename):
image = pg.image.load(filename).convert_alpha()
self.image = pg.Surface([64,64],pg.SRCALPHA)
|
{"/main.py": ["/settings.py"], "/spritesheet.py": ["/settings.py"]}
|
22,913,416
|
bevzzz/bouncer
|
refs/heads/master
|
/main.py
|
#!/home/dmytro/pycharm/bouncer/bouncerenv/bin/python3
from lib.utils.startup_manager import manager
if __name__ == "__main__":
while True:
manager.talk()
|
{"/lib/chatbot/reaction/reactionTrainModel.py": ["/lib/chatbot/reaction/reactionBase.py"], "/lib/chatbot/reaction/reactionCommandUnknown.py": ["/lib/chatbot/reaction/reactionBase.py"], "/lib/chatbot/reaction/reactionEnd.py": ["/lib/chatbot/reaction/reactionBase.py"], "/lib/facerec/recognition.py": ["/lib/utils/helpers.py", "/lib/facerec/model.py", "/lib/storage/localStorage.py"], "/lib/manager.py": ["/lib/chatbot/reaction/reactionFactory.py", "/lib/chatbot/conversation.py", "/lib/chatbot/state/conversationContext.py", "/lib/chatbot/state/UpdateParser.py"], "/lib/chatbot/reaction/reactionDefault.py": ["/lib/chatbot/reaction/reactionBase.py"], "/lib/chatbot/reaction/reactionBase.py": ["/lib/chatbot/telegramObject.py"], "/lib/chatbot/reaction/reactionFactory.py": ["/lib/chatbot/conversation.py", "/lib/chatbot/reaction/reactionDefault.py", "/lib/chatbot/reaction/reactionStart.py", "/lib/chatbot/reaction/reactionAuthorize.py", "/lib/chatbot/reaction/reactionDownloadPhoto.py", "/lib/chatbot/reaction/reactionEnd.py", "/lib/chatbot/reaction/reactionCommandUnknown.py", "/lib/chatbot/reaction/reactionRecognize.py", "/lib/chatbot/reaction/reactionTrainModel.py"], "/lib/camera/camera_test.py": ["/lib/camera/drawer.py"], "/lib/chatbot/reaction/reactionRecognize.py": ["/lib/chatbot/reaction/reactionBase.py"], "/lib/chatbot/reaction/reactionAuthorize.py": ["/lib/chatbot/reaction/reactionBase.py"], "/lib/chatbot/reaction/reactionStart.py": ["/lib/chatbot/reaction/reactionBase.py"], "/lib/chatbot/reaction/reactionDownloadPhoto.py": ["/lib/chatbot/reaction/reactionBase.py", "/lib/utils/helpers.py"], "/main.py": ["/lib/utils/startup_manager.py"], "/lib/utils/startup_manager.py": ["/lib/manager.py", "/lib/chatbot/telegramBot.py", "/lib/storage/localStorage.py"], "/lib/chatbot/state/conversationState.py": ["/lib/chatbot/telegramObject.py", "/lib/utils/helpers.py"], "/lib/chatbot/state/stateAwait.py": ["/lib/chatbot/state/conversationState.py", "/lib/chatbot/state/stateRecognize.py", "/lib/chatbot/state/stateAddPhoto.py"], "/lib/facerec/recognize.py": ["/lib/facerec/encode.py"], "/tests/testReactionFactory.py": ["/lib/utils/startup_manager.py", "/lib/chatbot/reaction/reactionFactory.py", "/lib/chatbot/reaction/reactionDefault.py", "/lib/chatbot/reaction/reactionStart.py", "/lib/chatbot/reaction/reactionAuthorize.py", "/lib/chatbot/reaction/reactionDownloadPhoto.py", "/lib/chatbot/reaction/reactionEnd.py", "/lib/chatbot/reaction/reactionCommandUnknown.py", "/lib/chatbot/reaction/reactionRecognize.py", "/lib/chatbot/reaction/reactionTrainModel.py"], "/lib/chatbot/state/stateUnknownInput.py": ["/lib/chatbot/state/conversationState.py"], "/lib/chatbot/state/UpdateParser.py": ["/lib/utils/user.py"], "/lib/chatbot/state/conversationContext.py": ["/lib/chatbot/state/stateAwait.py", "/lib/chatbot/state/stateRecognize.py", "/lib/chatbot/state/stateAddPhoto.py"], "/lib/storage/localStorage.py": ["/lib/storage/interface.py"], "/lib/chatbot/state/stateRecognize.py": ["/lib/chatbot/state/conversationState.py"], "/lib/chatbot/state/stateAddPhoto.py": ["/lib/chatbot/state/conversationState.py"], "/lib/facerec/tests/testEncoder.py": ["/lib/facerec/encode.py"], "/lib/chatbot/telegramBot.py": ["/lib/chatbot/interface.py", "/lib/chatbot/state/UpdateParser.py"], "/tests/testUpdatesHandler.py": ["/lib/utils/user.py"], "/lib/facerec/api.py": ["/lib/facerec/recognize.py"], "/lib/facerec/tests/testRecognizer.py": ["/lib/facerec/recognize.py", "/lib/facerec/encode.py"]}
|
22,913,417
|
bevzzz/bouncer
|
refs/heads/master
|
/lib/utils/startup_manager.py
|
#!/home/dmytro/pycharm/bouncer/bouncerenv/bin/python3
import logging
from lib.manager import Manager
from lib.chatbot.telegramBot import TelegramBot
from lib.storage.localStorage import LocalStorage
# setup logger
logging.basicConfig(
format='[%(levelname)s] %(asctime)s: %(message)s',
datefmt='%d-%m-%Y %H:%M:%S',
level=logging.INFO
)
# setup storage
storage = LocalStorage()
# setup chatbot
storage.set_root_path('')
token_file = storage.read_json('config', 'tokens.json')
chatbot = TelegramBot(token_file['bot_token'])
# setup manager
storage.set_root_path('images')
manager = Manager(chatbot, storage)
|
{"/lib/chatbot/reaction/reactionTrainModel.py": ["/lib/chatbot/reaction/reactionBase.py"], "/lib/chatbot/reaction/reactionCommandUnknown.py": ["/lib/chatbot/reaction/reactionBase.py"], "/lib/chatbot/reaction/reactionEnd.py": ["/lib/chatbot/reaction/reactionBase.py"], "/lib/facerec/recognition.py": ["/lib/utils/helpers.py", "/lib/facerec/model.py", "/lib/storage/localStorage.py"], "/lib/manager.py": ["/lib/chatbot/reaction/reactionFactory.py", "/lib/chatbot/conversation.py", "/lib/chatbot/state/conversationContext.py", "/lib/chatbot/state/UpdateParser.py"], "/lib/chatbot/reaction/reactionDefault.py": ["/lib/chatbot/reaction/reactionBase.py"], "/lib/chatbot/reaction/reactionBase.py": ["/lib/chatbot/telegramObject.py"], "/lib/chatbot/reaction/reactionFactory.py": ["/lib/chatbot/conversation.py", "/lib/chatbot/reaction/reactionDefault.py", "/lib/chatbot/reaction/reactionStart.py", "/lib/chatbot/reaction/reactionAuthorize.py", "/lib/chatbot/reaction/reactionDownloadPhoto.py", "/lib/chatbot/reaction/reactionEnd.py", "/lib/chatbot/reaction/reactionCommandUnknown.py", "/lib/chatbot/reaction/reactionRecognize.py", "/lib/chatbot/reaction/reactionTrainModel.py"], "/lib/camera/camera_test.py": ["/lib/camera/drawer.py"], "/lib/chatbot/reaction/reactionRecognize.py": ["/lib/chatbot/reaction/reactionBase.py"], "/lib/chatbot/reaction/reactionAuthorize.py": ["/lib/chatbot/reaction/reactionBase.py"], "/lib/chatbot/reaction/reactionStart.py": ["/lib/chatbot/reaction/reactionBase.py"], "/lib/chatbot/reaction/reactionDownloadPhoto.py": ["/lib/chatbot/reaction/reactionBase.py", "/lib/utils/helpers.py"], "/main.py": ["/lib/utils/startup_manager.py"], "/lib/utils/startup_manager.py": ["/lib/manager.py", "/lib/chatbot/telegramBot.py", "/lib/storage/localStorage.py"], "/lib/chatbot/state/conversationState.py": ["/lib/chatbot/telegramObject.py", "/lib/utils/helpers.py"], "/lib/chatbot/state/stateAwait.py": ["/lib/chatbot/state/conversationState.py", "/lib/chatbot/state/stateRecognize.py", "/lib/chatbot/state/stateAddPhoto.py"], "/lib/facerec/recognize.py": ["/lib/facerec/encode.py"], "/tests/testReactionFactory.py": ["/lib/utils/startup_manager.py", "/lib/chatbot/reaction/reactionFactory.py", "/lib/chatbot/reaction/reactionDefault.py", "/lib/chatbot/reaction/reactionStart.py", "/lib/chatbot/reaction/reactionAuthorize.py", "/lib/chatbot/reaction/reactionDownloadPhoto.py", "/lib/chatbot/reaction/reactionEnd.py", "/lib/chatbot/reaction/reactionCommandUnknown.py", "/lib/chatbot/reaction/reactionRecognize.py", "/lib/chatbot/reaction/reactionTrainModel.py"], "/lib/chatbot/state/stateUnknownInput.py": ["/lib/chatbot/state/conversationState.py"], "/lib/chatbot/state/UpdateParser.py": ["/lib/utils/user.py"], "/lib/chatbot/state/conversationContext.py": ["/lib/chatbot/state/stateAwait.py", "/lib/chatbot/state/stateRecognize.py", "/lib/chatbot/state/stateAddPhoto.py"], "/lib/storage/localStorage.py": ["/lib/storage/interface.py"], "/lib/chatbot/state/stateRecognize.py": ["/lib/chatbot/state/conversationState.py"], "/lib/chatbot/state/stateAddPhoto.py": ["/lib/chatbot/state/conversationState.py"], "/lib/facerec/tests/testEncoder.py": ["/lib/facerec/encode.py"], "/lib/chatbot/telegramBot.py": ["/lib/chatbot/interface.py", "/lib/chatbot/state/UpdateParser.py"], "/tests/testUpdatesHandler.py": ["/lib/utils/user.py"], "/lib/facerec/api.py": ["/lib/facerec/recognize.py"], "/lib/facerec/tests/testRecognizer.py": ["/lib/facerec/recognize.py", "/lib/facerec/encode.py"]}
|
22,913,418
|
bevzzz/bouncer
|
refs/heads/master
|
/lib/chatbot/state/conversationState.py
|
import abc
import collections
import logging
# message elements
from lib.chatbot.telegramObject import TextMessage, InlineKeyboardButton, InlineKeyboardMarkup
from lib.utils.helpers import get_timestamp
class ConversationState(metaclass=abc.ABCMeta):
buttons = None
def __init__(self, context):
self.log = logging.getLogger()
if context is None:
self.log.error(f"No context provided for {self}")
raise RuntimeError
else:
self._context = context
@abc.abstractmethod
def invoke(self, params):
pass
@abc.abstractmethod
def act(self):
pass
@abc.abstractmethod
def get_response(self):
pass
@abc.abstractmethod
def set_next_state(self):
msg = self._context.update.get_phrase()
n = self.buttons[msg]['next']
if n is None:
state = self
elif n == 'last_state':
state = self._context.last_state
else:
# add error handling
state = self._context.states.get(n, self._context.last_state)
state = state(self._context)
self._context.change_state(state)
def build_message(self, text):
chat_id = self._context.update.get_chat_id()
reply_markup = self.add_keyboard(self.buttons)
message_out = TextMessage(
text=text,
chat_id=chat_id,
reply_markup=reply_markup
)
return message_out.to_dict()
@staticmethod
def add_keyboard(buttons):
if buttons is None:
return None
keyboard = collections.defaultdict(list)
for key_id in buttons:
key = buttons[key_id]
row = str(key["row"])
keyboard[row].append(
InlineKeyboardButton(
text=key["label"],
callback_data=key_id
)
)
keyboard = [i[1] for i in sorted(keyboard.items())]
return InlineKeyboardMarkup(keyboard)
def download_photo(self):
return self._context.download_photo()
def store_photo(self, photo):
username = self._context.update.get_author().get_username()
name = f"{username}_{get_timestamp()}"
self._context.store_photo(
photo=photo,
name=name,
to_dir=username
)
|
{"/lib/chatbot/reaction/reactionTrainModel.py": ["/lib/chatbot/reaction/reactionBase.py"], "/lib/chatbot/reaction/reactionCommandUnknown.py": ["/lib/chatbot/reaction/reactionBase.py"], "/lib/chatbot/reaction/reactionEnd.py": ["/lib/chatbot/reaction/reactionBase.py"], "/lib/facerec/recognition.py": ["/lib/utils/helpers.py", "/lib/facerec/model.py", "/lib/storage/localStorage.py"], "/lib/manager.py": ["/lib/chatbot/reaction/reactionFactory.py", "/lib/chatbot/conversation.py", "/lib/chatbot/state/conversationContext.py", "/lib/chatbot/state/UpdateParser.py"], "/lib/chatbot/reaction/reactionDefault.py": ["/lib/chatbot/reaction/reactionBase.py"], "/lib/chatbot/reaction/reactionBase.py": ["/lib/chatbot/telegramObject.py"], "/lib/chatbot/reaction/reactionFactory.py": ["/lib/chatbot/conversation.py", "/lib/chatbot/reaction/reactionDefault.py", "/lib/chatbot/reaction/reactionStart.py", "/lib/chatbot/reaction/reactionAuthorize.py", "/lib/chatbot/reaction/reactionDownloadPhoto.py", "/lib/chatbot/reaction/reactionEnd.py", "/lib/chatbot/reaction/reactionCommandUnknown.py", "/lib/chatbot/reaction/reactionRecognize.py", "/lib/chatbot/reaction/reactionTrainModel.py"], "/lib/camera/camera_test.py": ["/lib/camera/drawer.py"], "/lib/chatbot/reaction/reactionRecognize.py": ["/lib/chatbot/reaction/reactionBase.py"], "/lib/chatbot/reaction/reactionAuthorize.py": ["/lib/chatbot/reaction/reactionBase.py"], "/lib/chatbot/reaction/reactionStart.py": ["/lib/chatbot/reaction/reactionBase.py"], "/lib/chatbot/reaction/reactionDownloadPhoto.py": ["/lib/chatbot/reaction/reactionBase.py", "/lib/utils/helpers.py"], "/main.py": ["/lib/utils/startup_manager.py"], "/lib/utils/startup_manager.py": ["/lib/manager.py", "/lib/chatbot/telegramBot.py", "/lib/storage/localStorage.py"], "/lib/chatbot/state/conversationState.py": ["/lib/chatbot/telegramObject.py", "/lib/utils/helpers.py"], "/lib/chatbot/state/stateAwait.py": ["/lib/chatbot/state/conversationState.py", "/lib/chatbot/state/stateRecognize.py", "/lib/chatbot/state/stateAddPhoto.py"], "/lib/facerec/recognize.py": ["/lib/facerec/encode.py"], "/tests/testReactionFactory.py": ["/lib/utils/startup_manager.py", "/lib/chatbot/reaction/reactionFactory.py", "/lib/chatbot/reaction/reactionDefault.py", "/lib/chatbot/reaction/reactionStart.py", "/lib/chatbot/reaction/reactionAuthorize.py", "/lib/chatbot/reaction/reactionDownloadPhoto.py", "/lib/chatbot/reaction/reactionEnd.py", "/lib/chatbot/reaction/reactionCommandUnknown.py", "/lib/chatbot/reaction/reactionRecognize.py", "/lib/chatbot/reaction/reactionTrainModel.py"], "/lib/chatbot/state/stateUnknownInput.py": ["/lib/chatbot/state/conversationState.py"], "/lib/chatbot/state/UpdateParser.py": ["/lib/utils/user.py"], "/lib/chatbot/state/conversationContext.py": ["/lib/chatbot/state/stateAwait.py", "/lib/chatbot/state/stateRecognize.py", "/lib/chatbot/state/stateAddPhoto.py"], "/lib/storage/localStorage.py": ["/lib/storage/interface.py"], "/lib/chatbot/state/stateRecognize.py": ["/lib/chatbot/state/conversationState.py"], "/lib/chatbot/state/stateAddPhoto.py": ["/lib/chatbot/state/conversationState.py"], "/lib/facerec/tests/testEncoder.py": ["/lib/facerec/encode.py"], "/lib/chatbot/telegramBot.py": ["/lib/chatbot/interface.py", "/lib/chatbot/state/UpdateParser.py"], "/tests/testUpdatesHandler.py": ["/lib/utils/user.py"], "/lib/facerec/api.py": ["/lib/facerec/recognize.py"], "/lib/facerec/tests/testRecognizer.py": ["/lib/facerec/recognize.py", "/lib/facerec/encode.py"]}
|
22,913,419
|
bevzzz/bouncer
|
refs/heads/master
|
/lib/chatbot/state/stateAwait.py
|
from lib.chatbot.state.conversationState import ConversationState
from lib.chatbot.state.stateRecognize import StateRecognize
from lib.chatbot.state.stateAddPhoto import StateAddPhoto
class StateAwait(ConversationState):
buttons = {
"back": {
"label": "Back",
"row": 1,
"next": 'last_state'
}
}
def __init__(self, context):
self.msg = None
super().__init__(context)
def invoke(self, params):
self.msg = self._context.update.get_phrase()
def act(self):
pass
def get_response(self):
return self.build_message(text="waiting...")
def set_next_state(self):
if self._context.update.get_phrase() in self.buttons:
super().set_next_state()
else:
self._set_next_state()
def _set_next_state(self):
if self.msg == "recognize":
state = StateRecognize(self._context)
elif self.msg == "add_photo":
state = StateAddPhoto(self._context)
else:
state = self
self._context.change_state(state)
|
{"/lib/chatbot/reaction/reactionTrainModel.py": ["/lib/chatbot/reaction/reactionBase.py"], "/lib/chatbot/reaction/reactionCommandUnknown.py": ["/lib/chatbot/reaction/reactionBase.py"], "/lib/chatbot/reaction/reactionEnd.py": ["/lib/chatbot/reaction/reactionBase.py"], "/lib/facerec/recognition.py": ["/lib/utils/helpers.py", "/lib/facerec/model.py", "/lib/storage/localStorage.py"], "/lib/manager.py": ["/lib/chatbot/reaction/reactionFactory.py", "/lib/chatbot/conversation.py", "/lib/chatbot/state/conversationContext.py", "/lib/chatbot/state/UpdateParser.py"], "/lib/chatbot/reaction/reactionDefault.py": ["/lib/chatbot/reaction/reactionBase.py"], "/lib/chatbot/reaction/reactionBase.py": ["/lib/chatbot/telegramObject.py"], "/lib/chatbot/reaction/reactionFactory.py": ["/lib/chatbot/conversation.py", "/lib/chatbot/reaction/reactionDefault.py", "/lib/chatbot/reaction/reactionStart.py", "/lib/chatbot/reaction/reactionAuthorize.py", "/lib/chatbot/reaction/reactionDownloadPhoto.py", "/lib/chatbot/reaction/reactionEnd.py", "/lib/chatbot/reaction/reactionCommandUnknown.py", "/lib/chatbot/reaction/reactionRecognize.py", "/lib/chatbot/reaction/reactionTrainModel.py"], "/lib/camera/camera_test.py": ["/lib/camera/drawer.py"], "/lib/chatbot/reaction/reactionRecognize.py": ["/lib/chatbot/reaction/reactionBase.py"], "/lib/chatbot/reaction/reactionAuthorize.py": ["/lib/chatbot/reaction/reactionBase.py"], "/lib/chatbot/reaction/reactionStart.py": ["/lib/chatbot/reaction/reactionBase.py"], "/lib/chatbot/reaction/reactionDownloadPhoto.py": ["/lib/chatbot/reaction/reactionBase.py", "/lib/utils/helpers.py"], "/main.py": ["/lib/utils/startup_manager.py"], "/lib/utils/startup_manager.py": ["/lib/manager.py", "/lib/chatbot/telegramBot.py", "/lib/storage/localStorage.py"], "/lib/chatbot/state/conversationState.py": ["/lib/chatbot/telegramObject.py", "/lib/utils/helpers.py"], "/lib/chatbot/state/stateAwait.py": ["/lib/chatbot/state/conversationState.py", "/lib/chatbot/state/stateRecognize.py", "/lib/chatbot/state/stateAddPhoto.py"], "/lib/facerec/recognize.py": ["/lib/facerec/encode.py"], "/tests/testReactionFactory.py": ["/lib/utils/startup_manager.py", "/lib/chatbot/reaction/reactionFactory.py", "/lib/chatbot/reaction/reactionDefault.py", "/lib/chatbot/reaction/reactionStart.py", "/lib/chatbot/reaction/reactionAuthorize.py", "/lib/chatbot/reaction/reactionDownloadPhoto.py", "/lib/chatbot/reaction/reactionEnd.py", "/lib/chatbot/reaction/reactionCommandUnknown.py", "/lib/chatbot/reaction/reactionRecognize.py", "/lib/chatbot/reaction/reactionTrainModel.py"], "/lib/chatbot/state/stateUnknownInput.py": ["/lib/chatbot/state/conversationState.py"], "/lib/chatbot/state/UpdateParser.py": ["/lib/utils/user.py"], "/lib/chatbot/state/conversationContext.py": ["/lib/chatbot/state/stateAwait.py", "/lib/chatbot/state/stateRecognize.py", "/lib/chatbot/state/stateAddPhoto.py"], "/lib/storage/localStorage.py": ["/lib/storage/interface.py"], "/lib/chatbot/state/stateRecognize.py": ["/lib/chatbot/state/conversationState.py"], "/lib/chatbot/state/stateAddPhoto.py": ["/lib/chatbot/state/conversationState.py"], "/lib/facerec/tests/testEncoder.py": ["/lib/facerec/encode.py"], "/lib/chatbot/telegramBot.py": ["/lib/chatbot/interface.py", "/lib/chatbot/state/UpdateParser.py"], "/tests/testUpdatesHandler.py": ["/lib/utils/user.py"], "/lib/facerec/api.py": ["/lib/facerec/recognize.py"], "/lib/facerec/tests/testRecognizer.py": ["/lib/facerec/recognize.py", "/lib/facerec/encode.py"]}
|
22,913,420
|
bevzzz/bouncer
|
refs/heads/master
|
/lib/facerec/recognize.py
|
import io
import face_recognition
import numpy as np
from PIL import Image
from lib.facerec.encode import Encoder
RGB = "RGB"
class Recognizer:
def __init__(self, known=None, method='hog', tolerance=0.6):
self._names = None
self._encodings = None
if known is not None:
self.set_known(known)
self.method = method
self.tolerance = tolerance
self.encoder = Encoder(self.method)
def set_known(self, known):
self._names = known["names"]
self._encodings = known["encodings"]
def clear_known(self):
self._names = None
self._encodings = None
@staticmethod
def _convert_pil_to_array(img):
return np.array(img)
@staticmethod
def _convert_bytes_to_pil(img_bytes):
b = io.BytesIO(img_bytes)
return Image.open(b)
@staticmethod
def _is_rgb(img):
return img.mode == RGB
@staticmethod
def _convert_to_rgb(img):
return img.convert(RGB)
def _prepare_for_encoding(self, img_bytes):
img = self._convert_bytes_to_pil(img_bytes)
if not self._is_rgb(img):
img = self._convert_to_rgb(img)
return self._convert_pil_to_array(img)
def _find_matches(self, encoded_img):
return face_recognition.compare_faces(
known_face_encodings=self._encodings,
face_encoding_to_check=encoded_img,
tolerance=self.tolerance
)
def _determine_the_match(self, matches):
name_out = ""
if True in matches:
matched_idx = [i for (i, match) in enumerate(matches) if match]
counts = {}
for i in matched_idx:
name = self._names[i]
counts[name] = counts.get(name, 0) + 1
name_out = max(counts, key=counts.get)
return name_out, ""
def recognize(self, img_bytes):
if self._encodings is None or self._names is None:
return None
arr = self._prepare_for_encoding(img_bytes)
encoded_img = self.encoder.encode(arr)
matches = self._find_matches(encoded_img)
name, reason = self._determine_the_match(matches)
# return person
|
{"/lib/chatbot/reaction/reactionTrainModel.py": ["/lib/chatbot/reaction/reactionBase.py"], "/lib/chatbot/reaction/reactionCommandUnknown.py": ["/lib/chatbot/reaction/reactionBase.py"], "/lib/chatbot/reaction/reactionEnd.py": ["/lib/chatbot/reaction/reactionBase.py"], "/lib/facerec/recognition.py": ["/lib/utils/helpers.py", "/lib/facerec/model.py", "/lib/storage/localStorage.py"], "/lib/manager.py": ["/lib/chatbot/reaction/reactionFactory.py", "/lib/chatbot/conversation.py", "/lib/chatbot/state/conversationContext.py", "/lib/chatbot/state/UpdateParser.py"], "/lib/chatbot/reaction/reactionDefault.py": ["/lib/chatbot/reaction/reactionBase.py"], "/lib/chatbot/reaction/reactionBase.py": ["/lib/chatbot/telegramObject.py"], "/lib/chatbot/reaction/reactionFactory.py": ["/lib/chatbot/conversation.py", "/lib/chatbot/reaction/reactionDefault.py", "/lib/chatbot/reaction/reactionStart.py", "/lib/chatbot/reaction/reactionAuthorize.py", "/lib/chatbot/reaction/reactionDownloadPhoto.py", "/lib/chatbot/reaction/reactionEnd.py", "/lib/chatbot/reaction/reactionCommandUnknown.py", "/lib/chatbot/reaction/reactionRecognize.py", "/lib/chatbot/reaction/reactionTrainModel.py"], "/lib/camera/camera_test.py": ["/lib/camera/drawer.py"], "/lib/chatbot/reaction/reactionRecognize.py": ["/lib/chatbot/reaction/reactionBase.py"], "/lib/chatbot/reaction/reactionAuthorize.py": ["/lib/chatbot/reaction/reactionBase.py"], "/lib/chatbot/reaction/reactionStart.py": ["/lib/chatbot/reaction/reactionBase.py"], "/lib/chatbot/reaction/reactionDownloadPhoto.py": ["/lib/chatbot/reaction/reactionBase.py", "/lib/utils/helpers.py"], "/main.py": ["/lib/utils/startup_manager.py"], "/lib/utils/startup_manager.py": ["/lib/manager.py", "/lib/chatbot/telegramBot.py", "/lib/storage/localStorage.py"], "/lib/chatbot/state/conversationState.py": ["/lib/chatbot/telegramObject.py", "/lib/utils/helpers.py"], "/lib/chatbot/state/stateAwait.py": ["/lib/chatbot/state/conversationState.py", "/lib/chatbot/state/stateRecognize.py", "/lib/chatbot/state/stateAddPhoto.py"], "/lib/facerec/recognize.py": ["/lib/facerec/encode.py"], "/tests/testReactionFactory.py": ["/lib/utils/startup_manager.py", "/lib/chatbot/reaction/reactionFactory.py", "/lib/chatbot/reaction/reactionDefault.py", "/lib/chatbot/reaction/reactionStart.py", "/lib/chatbot/reaction/reactionAuthorize.py", "/lib/chatbot/reaction/reactionDownloadPhoto.py", "/lib/chatbot/reaction/reactionEnd.py", "/lib/chatbot/reaction/reactionCommandUnknown.py", "/lib/chatbot/reaction/reactionRecognize.py", "/lib/chatbot/reaction/reactionTrainModel.py"], "/lib/chatbot/state/stateUnknownInput.py": ["/lib/chatbot/state/conversationState.py"], "/lib/chatbot/state/UpdateParser.py": ["/lib/utils/user.py"], "/lib/chatbot/state/conversationContext.py": ["/lib/chatbot/state/stateAwait.py", "/lib/chatbot/state/stateRecognize.py", "/lib/chatbot/state/stateAddPhoto.py"], "/lib/storage/localStorage.py": ["/lib/storage/interface.py"], "/lib/chatbot/state/stateRecognize.py": ["/lib/chatbot/state/conversationState.py"], "/lib/chatbot/state/stateAddPhoto.py": ["/lib/chatbot/state/conversationState.py"], "/lib/facerec/tests/testEncoder.py": ["/lib/facerec/encode.py"], "/lib/chatbot/telegramBot.py": ["/lib/chatbot/interface.py", "/lib/chatbot/state/UpdateParser.py"], "/tests/testUpdatesHandler.py": ["/lib/utils/user.py"], "/lib/facerec/api.py": ["/lib/facerec/recognize.py"], "/lib/facerec/tests/testRecognizer.py": ["/lib/facerec/recognize.py", "/lib/facerec/encode.py"]}
|
22,913,421
|
bevzzz/bouncer
|
refs/heads/master
|
/tests/testReactionFactory.py
|
import os
import unittest
from lib.utils.startup_manager import manager
from lib.chatbot.updatesHandler import UpdatesHandler
from lib.chatbot.reaction.reactionFactory import ReactionFactory
from lib.chatbot.reaction.reactionDefault import ReactionDefault
from lib.chatbot.reaction.reactionStart import ReactionStart
from lib.chatbot.reaction.reactionAuthorize import ReactionAuthorize
from lib.chatbot.reaction.reactionNotAuthorized import ReactionNotAuthorized
from lib.chatbot.reaction.reactionDownloadPhoto import ReactionDownloadPhoto
from lib.chatbot.reaction.reactionEnd import ReactionEnd
from lib.chatbot.reaction.reactionCommandUnknown import ReactionCommandUnknown
from lib.chatbot.reaction.reactionRecognize import ReactionRecognize
from lib.chatbot.reaction.reactionTrainModel import ReactionTrainModel
class TestReactionFactory(unittest.TestCase):
@staticmethod
def get_cb_with(cmd=None):
cb = {'update_id': 317007529, 'callback_query': {'id': '488459458556047547', 'from': {'id': 113728330, 'is_bot': False, 'first_name': 'Dima', 'last_name': 'Solovei', 'username': 'bevzzz', 'language_code': 'en'}, 'message': {'message_id': 17, 'from': {'id': 1790996180, 'is_bot': True, 'first_name': 'Sobaka', 'username': 'dvoretzki_bot'}, 'chat': {'id': 113728330, 'first_name': 'Dima', 'last_name': 'Solovei', 'username': 'bevzzz', 'type': 'private'}, 'date': 1619760482, 'text': 'Hi, Dima!', 'reply_markup': {'inline_keyboard': [[{'text': 'Recognize', 'callback_data': 'recognize'}], [{'text': 'Save photo', 'callback_data': 'save_photo'}], [{'text': 'Train', 'callback_data': 'train'}]]}}, 'chat_instance': '-3889430022395058016', 'data': 'recognize'}}
if cmd is not None:
cb['callback_query']['data'] = cmd
return UpdatesHandler.factory(cb)
@staticmethod
def get_msg_with(cmd=None, photo=False):
msg = {'update_id': 317007528, 'message': {'message_id': 16, 'from': {'id': 113728330, 'is_bot': False, 'first_name': 'Dima', 'last_name': 'Solovei', 'username': 'bevzzz', 'language_code': 'en'}, 'chat': {'id': 113728330, 'first_name': 'Dima', 'last_name': 'Solovei', 'username': 'bevzzz', 'type': 'private'}, 'date': 1619760481, 'text': 'Test'}}
if cmd is not None:
msg = {'update_id': 317007528, 'message': {'message_id': 16, 'from': {'id': 113728330, 'is_bot': False, 'first_name': 'Dima', 'last_name': 'Solovei', 'username': 'bevzzz', 'language_code': 'en'}, 'chat': {'id': 113728330, 'first_name': 'Dima', 'last_name': 'Solovei', 'username': 'bevzzz', 'type': 'private'}, 'date': 1619760481, 'text': 'Test', 'entities': [{'offset': 0, 'length': 6, 'type': 'bot_command'}]}}
msg['message']['text'] = f'/{cmd}'
if photo:
msg = {'update_id': 317007528, 'message': {'message_id': 16, 'from': {'id': 113728330, 'is_bot': False, 'first_name': 'Dima', 'last_name': 'Solovei', 'username': 'bevzzz', 'language_code': 'en'}, 'chat': {'id': 113728330, 'first_name': 'Dima', 'last_name': 'Solovei', 'username': 'bevzzz', 'type': 'private'}, 'date': 1619760481, 'text': 'Test', 'photo': [{'file_id': 'AgACAgIAAxkBAAMaYI6Yd6lz4W1fA4ze_NhnqNWuRA8AAq6zMRtHKXlIUo519LSCRQJw8AGfLgADAQADAgADbQADhcEDAAEfBA', 'file_unique_id': 'AQADcPABny4AA4XBAwAB', 'file_size': 18998, 'width': 240, 'height': 320}, {'file_id': 'AgACAgIAAxkBAAMaYI6Yd6lz4W1fA4ze_NhnqNWuRA8AAq6zMRtHKXlIUo519LSCRQJw8AGfLgADAQADAgADeAADh8EDAAEfBA', 'file_unique_id': 'AQADcPABny4AA4fBAwAB', 'file_size': 80457, 'width': 601, 'height': 800}, {'file_id': 'AgACAgIAAxkBAAMaYI6Yd6lz4W1fA4ze_NhnqNWuRA8AAq6zMRtHKXlIUo519LSCRQJw8AGfLgADAQADAgADeQADiMEDAAEfBA', 'file_unique_id': 'AQADcPABny4AA4jBAwAB', 'file_size': 123157, 'width': 961, 'height': 1280}]}}
return UpdatesHandler.factory(msg)
def test_command_start(self):
# arrange
message = self.get_cb_with(cmd='start')
# act
rf = ReactionFactory(manager).get(message=message)
# assert
self.assertIsInstance(rf, ReactionStart)
def test_command_end(self):
# arrange
message = self.get_cb_with(cmd='end')
# act
rf = ReactionFactory(manager).get(message=message)
# assert
self.assertIsInstance(rf, ReactionEnd)
def test_command_recognize(self):
# arrange
message = self.get_cb_with(cmd='recognize')
# act
rf = ReactionFactory(manager).get(message=message)
# assert
self.assertIsInstance(rf, ReactionDefault)
def test_act_recognize_photo(self):
# arrange
message = self.get_msg_with(photo=True)
# act
rf = ReactionFactory(manager).get(
message=message,
state='recognize'
)
# assert
self.assertIsInstance(rf, ReactionRecognize)
def test_command_train(self):
# arrange
message = self.get_cb_with(cmd='train')
# act
rf = ReactionFactory(manager).get(message=message)
# assert
self.assertIsInstance(rf, ReactionTrainModel)
def test_command_save_photo(self):
# arrange
message = self.get_cb_with(cmd='save_photo')
# act
rf = ReactionFactory(manager).get(message=message)
# assert
self.assertIsInstance(rf, ReactionDefault)
def test_act_save_photo(self):
# arrange
message = self.get_msg_with(photo=True)
# act
rf = ReactionFactory(manager).get(
message=message,
state='save_photo'
)
# assert
self.assertIsInstance(rf, ReactionDownloadPhoto)
if __name__ == '__main__':
unittest.main()
|
{"/lib/chatbot/reaction/reactionTrainModel.py": ["/lib/chatbot/reaction/reactionBase.py"], "/lib/chatbot/reaction/reactionCommandUnknown.py": ["/lib/chatbot/reaction/reactionBase.py"], "/lib/chatbot/reaction/reactionEnd.py": ["/lib/chatbot/reaction/reactionBase.py"], "/lib/facerec/recognition.py": ["/lib/utils/helpers.py", "/lib/facerec/model.py", "/lib/storage/localStorage.py"], "/lib/manager.py": ["/lib/chatbot/reaction/reactionFactory.py", "/lib/chatbot/conversation.py", "/lib/chatbot/state/conversationContext.py", "/lib/chatbot/state/UpdateParser.py"], "/lib/chatbot/reaction/reactionDefault.py": ["/lib/chatbot/reaction/reactionBase.py"], "/lib/chatbot/reaction/reactionBase.py": ["/lib/chatbot/telegramObject.py"], "/lib/chatbot/reaction/reactionFactory.py": ["/lib/chatbot/conversation.py", "/lib/chatbot/reaction/reactionDefault.py", "/lib/chatbot/reaction/reactionStart.py", "/lib/chatbot/reaction/reactionAuthorize.py", "/lib/chatbot/reaction/reactionDownloadPhoto.py", "/lib/chatbot/reaction/reactionEnd.py", "/lib/chatbot/reaction/reactionCommandUnknown.py", "/lib/chatbot/reaction/reactionRecognize.py", "/lib/chatbot/reaction/reactionTrainModel.py"], "/lib/camera/camera_test.py": ["/lib/camera/drawer.py"], "/lib/chatbot/reaction/reactionRecognize.py": ["/lib/chatbot/reaction/reactionBase.py"], "/lib/chatbot/reaction/reactionAuthorize.py": ["/lib/chatbot/reaction/reactionBase.py"], "/lib/chatbot/reaction/reactionStart.py": ["/lib/chatbot/reaction/reactionBase.py"], "/lib/chatbot/reaction/reactionDownloadPhoto.py": ["/lib/chatbot/reaction/reactionBase.py", "/lib/utils/helpers.py"], "/main.py": ["/lib/utils/startup_manager.py"], "/lib/utils/startup_manager.py": ["/lib/manager.py", "/lib/chatbot/telegramBot.py", "/lib/storage/localStorage.py"], "/lib/chatbot/state/conversationState.py": ["/lib/chatbot/telegramObject.py", "/lib/utils/helpers.py"], "/lib/chatbot/state/stateAwait.py": ["/lib/chatbot/state/conversationState.py", "/lib/chatbot/state/stateRecognize.py", "/lib/chatbot/state/stateAddPhoto.py"], "/lib/facerec/recognize.py": ["/lib/facerec/encode.py"], "/tests/testReactionFactory.py": ["/lib/utils/startup_manager.py", "/lib/chatbot/reaction/reactionFactory.py", "/lib/chatbot/reaction/reactionDefault.py", "/lib/chatbot/reaction/reactionStart.py", "/lib/chatbot/reaction/reactionAuthorize.py", "/lib/chatbot/reaction/reactionDownloadPhoto.py", "/lib/chatbot/reaction/reactionEnd.py", "/lib/chatbot/reaction/reactionCommandUnknown.py", "/lib/chatbot/reaction/reactionRecognize.py", "/lib/chatbot/reaction/reactionTrainModel.py"], "/lib/chatbot/state/stateUnknownInput.py": ["/lib/chatbot/state/conversationState.py"], "/lib/chatbot/state/UpdateParser.py": ["/lib/utils/user.py"], "/lib/chatbot/state/conversationContext.py": ["/lib/chatbot/state/stateAwait.py", "/lib/chatbot/state/stateRecognize.py", "/lib/chatbot/state/stateAddPhoto.py"], "/lib/storage/localStorage.py": ["/lib/storage/interface.py"], "/lib/chatbot/state/stateRecognize.py": ["/lib/chatbot/state/conversationState.py"], "/lib/chatbot/state/stateAddPhoto.py": ["/lib/chatbot/state/conversationState.py"], "/lib/facerec/tests/testEncoder.py": ["/lib/facerec/encode.py"], "/lib/chatbot/telegramBot.py": ["/lib/chatbot/interface.py", "/lib/chatbot/state/UpdateParser.py"], "/tests/testUpdatesHandler.py": ["/lib/utils/user.py"], "/lib/facerec/api.py": ["/lib/facerec/recognize.py"], "/lib/facerec/tests/testRecognizer.py": ["/lib/facerec/recognize.py", "/lib/facerec/encode.py"]}
|
22,913,422
|
bevzzz/bouncer
|
refs/heads/master
|
/lib/chatbot/interface.py
|
from abc import ABCMeta, abstractmethod
import logging
class Chatbot(metaclass=ABCMeta):
def __init__(self):
self.log = logging.getLogger()
@abstractmethod
def get_updates(self):
pass
@abstractmethod
def download_file(self, file):
pass
@abstractmethod
def send_message(self, message):
pass
@abstractmethod
def send_file(self, file, chat_id):
pass
|
{"/lib/chatbot/reaction/reactionTrainModel.py": ["/lib/chatbot/reaction/reactionBase.py"], "/lib/chatbot/reaction/reactionCommandUnknown.py": ["/lib/chatbot/reaction/reactionBase.py"], "/lib/chatbot/reaction/reactionEnd.py": ["/lib/chatbot/reaction/reactionBase.py"], "/lib/facerec/recognition.py": ["/lib/utils/helpers.py", "/lib/facerec/model.py", "/lib/storage/localStorage.py"], "/lib/manager.py": ["/lib/chatbot/reaction/reactionFactory.py", "/lib/chatbot/conversation.py", "/lib/chatbot/state/conversationContext.py", "/lib/chatbot/state/UpdateParser.py"], "/lib/chatbot/reaction/reactionDefault.py": ["/lib/chatbot/reaction/reactionBase.py"], "/lib/chatbot/reaction/reactionBase.py": ["/lib/chatbot/telegramObject.py"], "/lib/chatbot/reaction/reactionFactory.py": ["/lib/chatbot/conversation.py", "/lib/chatbot/reaction/reactionDefault.py", "/lib/chatbot/reaction/reactionStart.py", "/lib/chatbot/reaction/reactionAuthorize.py", "/lib/chatbot/reaction/reactionDownloadPhoto.py", "/lib/chatbot/reaction/reactionEnd.py", "/lib/chatbot/reaction/reactionCommandUnknown.py", "/lib/chatbot/reaction/reactionRecognize.py", "/lib/chatbot/reaction/reactionTrainModel.py"], "/lib/camera/camera_test.py": ["/lib/camera/drawer.py"], "/lib/chatbot/reaction/reactionRecognize.py": ["/lib/chatbot/reaction/reactionBase.py"], "/lib/chatbot/reaction/reactionAuthorize.py": ["/lib/chatbot/reaction/reactionBase.py"], "/lib/chatbot/reaction/reactionStart.py": ["/lib/chatbot/reaction/reactionBase.py"], "/lib/chatbot/reaction/reactionDownloadPhoto.py": ["/lib/chatbot/reaction/reactionBase.py", "/lib/utils/helpers.py"], "/main.py": ["/lib/utils/startup_manager.py"], "/lib/utils/startup_manager.py": ["/lib/manager.py", "/lib/chatbot/telegramBot.py", "/lib/storage/localStorage.py"], "/lib/chatbot/state/conversationState.py": ["/lib/chatbot/telegramObject.py", "/lib/utils/helpers.py"], "/lib/chatbot/state/stateAwait.py": ["/lib/chatbot/state/conversationState.py", "/lib/chatbot/state/stateRecognize.py", "/lib/chatbot/state/stateAddPhoto.py"], "/lib/facerec/recognize.py": ["/lib/facerec/encode.py"], "/tests/testReactionFactory.py": ["/lib/utils/startup_manager.py", "/lib/chatbot/reaction/reactionFactory.py", "/lib/chatbot/reaction/reactionDefault.py", "/lib/chatbot/reaction/reactionStart.py", "/lib/chatbot/reaction/reactionAuthorize.py", "/lib/chatbot/reaction/reactionDownloadPhoto.py", "/lib/chatbot/reaction/reactionEnd.py", "/lib/chatbot/reaction/reactionCommandUnknown.py", "/lib/chatbot/reaction/reactionRecognize.py", "/lib/chatbot/reaction/reactionTrainModel.py"], "/lib/chatbot/state/stateUnknownInput.py": ["/lib/chatbot/state/conversationState.py"], "/lib/chatbot/state/UpdateParser.py": ["/lib/utils/user.py"], "/lib/chatbot/state/conversationContext.py": ["/lib/chatbot/state/stateAwait.py", "/lib/chatbot/state/stateRecognize.py", "/lib/chatbot/state/stateAddPhoto.py"], "/lib/storage/localStorage.py": ["/lib/storage/interface.py"], "/lib/chatbot/state/stateRecognize.py": ["/lib/chatbot/state/conversationState.py"], "/lib/chatbot/state/stateAddPhoto.py": ["/lib/chatbot/state/conversationState.py"], "/lib/facerec/tests/testEncoder.py": ["/lib/facerec/encode.py"], "/lib/chatbot/telegramBot.py": ["/lib/chatbot/interface.py", "/lib/chatbot/state/UpdateParser.py"], "/tests/testUpdatesHandler.py": ["/lib/utils/user.py"], "/lib/facerec/api.py": ["/lib/facerec/recognize.py"], "/lib/facerec/tests/testRecognizer.py": ["/lib/facerec/recognize.py", "/lib/facerec/encode.py"]}
|
22,913,423
|
bevzzz/bouncer
|
refs/heads/master
|
/lib/chatbot/state/stateUnknownInput.py
|
from lib.chatbot.state.conversationState import ConversationState
class StateUnknownInput(ConversationState):
buttons = {
"recognize": {
"label": "Recognize",
"row": 1
},
"add_photo": {
"label": "Add photo",
"row": 1
},
"end": {
"label": "Exit",
"row": 2
}
}
def invoke(self, params):
pass
def act(self):
pass
def get_response(self):
name = "User"
text = f"How can I help you, {name}?"
# TODO: add Train button if the user has the right permission
return self.build_message(text=text)
def change_state(self):
pass
|
{"/lib/chatbot/reaction/reactionTrainModel.py": ["/lib/chatbot/reaction/reactionBase.py"], "/lib/chatbot/reaction/reactionCommandUnknown.py": ["/lib/chatbot/reaction/reactionBase.py"], "/lib/chatbot/reaction/reactionEnd.py": ["/lib/chatbot/reaction/reactionBase.py"], "/lib/facerec/recognition.py": ["/lib/utils/helpers.py", "/lib/facerec/model.py", "/lib/storage/localStorage.py"], "/lib/manager.py": ["/lib/chatbot/reaction/reactionFactory.py", "/lib/chatbot/conversation.py", "/lib/chatbot/state/conversationContext.py", "/lib/chatbot/state/UpdateParser.py"], "/lib/chatbot/reaction/reactionDefault.py": ["/lib/chatbot/reaction/reactionBase.py"], "/lib/chatbot/reaction/reactionBase.py": ["/lib/chatbot/telegramObject.py"], "/lib/chatbot/reaction/reactionFactory.py": ["/lib/chatbot/conversation.py", "/lib/chatbot/reaction/reactionDefault.py", "/lib/chatbot/reaction/reactionStart.py", "/lib/chatbot/reaction/reactionAuthorize.py", "/lib/chatbot/reaction/reactionDownloadPhoto.py", "/lib/chatbot/reaction/reactionEnd.py", "/lib/chatbot/reaction/reactionCommandUnknown.py", "/lib/chatbot/reaction/reactionRecognize.py", "/lib/chatbot/reaction/reactionTrainModel.py"], "/lib/camera/camera_test.py": ["/lib/camera/drawer.py"], "/lib/chatbot/reaction/reactionRecognize.py": ["/lib/chatbot/reaction/reactionBase.py"], "/lib/chatbot/reaction/reactionAuthorize.py": ["/lib/chatbot/reaction/reactionBase.py"], "/lib/chatbot/reaction/reactionStart.py": ["/lib/chatbot/reaction/reactionBase.py"], "/lib/chatbot/reaction/reactionDownloadPhoto.py": ["/lib/chatbot/reaction/reactionBase.py", "/lib/utils/helpers.py"], "/main.py": ["/lib/utils/startup_manager.py"], "/lib/utils/startup_manager.py": ["/lib/manager.py", "/lib/chatbot/telegramBot.py", "/lib/storage/localStorage.py"], "/lib/chatbot/state/conversationState.py": ["/lib/chatbot/telegramObject.py", "/lib/utils/helpers.py"], "/lib/chatbot/state/stateAwait.py": ["/lib/chatbot/state/conversationState.py", "/lib/chatbot/state/stateRecognize.py", "/lib/chatbot/state/stateAddPhoto.py"], "/lib/facerec/recognize.py": ["/lib/facerec/encode.py"], "/tests/testReactionFactory.py": ["/lib/utils/startup_manager.py", "/lib/chatbot/reaction/reactionFactory.py", "/lib/chatbot/reaction/reactionDefault.py", "/lib/chatbot/reaction/reactionStart.py", "/lib/chatbot/reaction/reactionAuthorize.py", "/lib/chatbot/reaction/reactionDownloadPhoto.py", "/lib/chatbot/reaction/reactionEnd.py", "/lib/chatbot/reaction/reactionCommandUnknown.py", "/lib/chatbot/reaction/reactionRecognize.py", "/lib/chatbot/reaction/reactionTrainModel.py"], "/lib/chatbot/state/stateUnknownInput.py": ["/lib/chatbot/state/conversationState.py"], "/lib/chatbot/state/UpdateParser.py": ["/lib/utils/user.py"], "/lib/chatbot/state/conversationContext.py": ["/lib/chatbot/state/stateAwait.py", "/lib/chatbot/state/stateRecognize.py", "/lib/chatbot/state/stateAddPhoto.py"], "/lib/storage/localStorage.py": ["/lib/storage/interface.py"], "/lib/chatbot/state/stateRecognize.py": ["/lib/chatbot/state/conversationState.py"], "/lib/chatbot/state/stateAddPhoto.py": ["/lib/chatbot/state/conversationState.py"], "/lib/facerec/tests/testEncoder.py": ["/lib/facerec/encode.py"], "/lib/chatbot/telegramBot.py": ["/lib/chatbot/interface.py", "/lib/chatbot/state/UpdateParser.py"], "/tests/testUpdatesHandler.py": ["/lib/utils/user.py"], "/lib/facerec/api.py": ["/lib/facerec/recognize.py"], "/lib/facerec/tests/testRecognizer.py": ["/lib/facerec/recognize.py", "/lib/facerec/encode.py"]}
|
22,913,424
|
bevzzz/bouncer
|
refs/heads/master
|
/lib/chatbot/state/UpdateParser.py
|
import re
from lib.utils.user import Owner
class UpdateParser:
@staticmethod
def factory(update):
if update.get('message', False):
handler = MessageDTO(update['message'])
elif update.get('callback_query', False):
handler = CallbackDTO(update['callback_query'])
else:
key = list(update.keys())[1]
raise LookupError(f"Unknown update type: {key}")
return handler
class MessageDTO(UpdateParser):
"""
MessageDTO works with responses from Telegram API. It receives a "message" JSON
from Conversation and extracts key features of the message: text, attachments and
attachment mime_types if such exist etc.
"""
def __init__(self, message):
self.message = message
self.read = False
self.author = Owner.get_instance(self._from())
def get_author(self):
return self.author
def is_read(self):
return self.read
def mark_as_read(self):
self.read = True
# from
def _from(self):
return self.message['from']
# chat
def _chat(self):
return self.message['chat']
def get_chat_id(self):
chat = self._chat()
chat_id = chat['id']
return str(chat_id)
def is_private_chat(self):
chat = self._chat()
return chat['type'] == 'private'
# message
def get_message_id(self):
return self.message['message_id']
def _entities(self):
res = self.message.get('entities', {})
if res:
res = res[0]
return res
def get_phrase(self):
text = self.message.get('text', '')
if self.is_command():
text = re.sub('/', '', text)
return text
# attachments
def has_photo(self):
return self._attachment_mime_type() == 'image/jpeg'
def is_command(self):
msg_type = self._entities().get('type', False)
if msg_type:
return msg_type == 'bot_command'
else:
return msg_type
def _attachment_mime_type(self):
if self._photo_as_photo():
mime_type = 'image/jpeg'
elif self._photo_as_document():
mime_type = self.message['document']['mime_type']
else:
mime_type = ''
return mime_type
def _photo_as_photo(self):
return self.message.get('photo', False)
def _photo_as_document(self):
return self.message.get('document', False)
def get_picture_with_caption(self):
file_id = ''
if self._photo_as_photo():
file_id += self._get_small_photo_file_id()
elif self._photo_as_document():
file_id += self._get_document_file_id()
caption = self.message.get('caption', '')
return file_id, caption
def _get_document_file_id(self):
return self.message['document']['file_id']
def _get_small_photo_file_id(self):
return self.message['photo'][0]['file_id']
class CallbackDTO(MessageDTO):
def __init__(self, callback_query):
self.callback_query = callback_query
self.author = Owner.get_instance(self._from())
super().__init__(self._message())
def _from(self):
return self.callback_query['from']
def _message(self):
return self.callback_query['message']
def get_phrase(self):
return self.callback_query.get('data', '')
def is_command(self):
return True
|
{"/lib/chatbot/reaction/reactionTrainModel.py": ["/lib/chatbot/reaction/reactionBase.py"], "/lib/chatbot/reaction/reactionCommandUnknown.py": ["/lib/chatbot/reaction/reactionBase.py"], "/lib/chatbot/reaction/reactionEnd.py": ["/lib/chatbot/reaction/reactionBase.py"], "/lib/facerec/recognition.py": ["/lib/utils/helpers.py", "/lib/facerec/model.py", "/lib/storage/localStorage.py"], "/lib/manager.py": ["/lib/chatbot/reaction/reactionFactory.py", "/lib/chatbot/conversation.py", "/lib/chatbot/state/conversationContext.py", "/lib/chatbot/state/UpdateParser.py"], "/lib/chatbot/reaction/reactionDefault.py": ["/lib/chatbot/reaction/reactionBase.py"], "/lib/chatbot/reaction/reactionBase.py": ["/lib/chatbot/telegramObject.py"], "/lib/chatbot/reaction/reactionFactory.py": ["/lib/chatbot/conversation.py", "/lib/chatbot/reaction/reactionDefault.py", "/lib/chatbot/reaction/reactionStart.py", "/lib/chatbot/reaction/reactionAuthorize.py", "/lib/chatbot/reaction/reactionDownloadPhoto.py", "/lib/chatbot/reaction/reactionEnd.py", "/lib/chatbot/reaction/reactionCommandUnknown.py", "/lib/chatbot/reaction/reactionRecognize.py", "/lib/chatbot/reaction/reactionTrainModel.py"], "/lib/camera/camera_test.py": ["/lib/camera/drawer.py"], "/lib/chatbot/reaction/reactionRecognize.py": ["/lib/chatbot/reaction/reactionBase.py"], "/lib/chatbot/reaction/reactionAuthorize.py": ["/lib/chatbot/reaction/reactionBase.py"], "/lib/chatbot/reaction/reactionStart.py": ["/lib/chatbot/reaction/reactionBase.py"], "/lib/chatbot/reaction/reactionDownloadPhoto.py": ["/lib/chatbot/reaction/reactionBase.py", "/lib/utils/helpers.py"], "/main.py": ["/lib/utils/startup_manager.py"], "/lib/utils/startup_manager.py": ["/lib/manager.py", "/lib/chatbot/telegramBot.py", "/lib/storage/localStorage.py"], "/lib/chatbot/state/conversationState.py": ["/lib/chatbot/telegramObject.py", "/lib/utils/helpers.py"], "/lib/chatbot/state/stateAwait.py": ["/lib/chatbot/state/conversationState.py", "/lib/chatbot/state/stateRecognize.py", "/lib/chatbot/state/stateAddPhoto.py"], "/lib/facerec/recognize.py": ["/lib/facerec/encode.py"], "/tests/testReactionFactory.py": ["/lib/utils/startup_manager.py", "/lib/chatbot/reaction/reactionFactory.py", "/lib/chatbot/reaction/reactionDefault.py", "/lib/chatbot/reaction/reactionStart.py", "/lib/chatbot/reaction/reactionAuthorize.py", "/lib/chatbot/reaction/reactionDownloadPhoto.py", "/lib/chatbot/reaction/reactionEnd.py", "/lib/chatbot/reaction/reactionCommandUnknown.py", "/lib/chatbot/reaction/reactionRecognize.py", "/lib/chatbot/reaction/reactionTrainModel.py"], "/lib/chatbot/state/stateUnknownInput.py": ["/lib/chatbot/state/conversationState.py"], "/lib/chatbot/state/UpdateParser.py": ["/lib/utils/user.py"], "/lib/chatbot/state/conversationContext.py": ["/lib/chatbot/state/stateAwait.py", "/lib/chatbot/state/stateRecognize.py", "/lib/chatbot/state/stateAddPhoto.py"], "/lib/storage/localStorage.py": ["/lib/storage/interface.py"], "/lib/chatbot/state/stateRecognize.py": ["/lib/chatbot/state/conversationState.py"], "/lib/chatbot/state/stateAddPhoto.py": ["/lib/chatbot/state/conversationState.py"], "/lib/facerec/tests/testEncoder.py": ["/lib/facerec/encode.py"], "/lib/chatbot/telegramBot.py": ["/lib/chatbot/interface.py", "/lib/chatbot/state/UpdateParser.py"], "/tests/testUpdatesHandler.py": ["/lib/utils/user.py"], "/lib/facerec/api.py": ["/lib/facerec/recognize.py"], "/lib/facerec/tests/testRecognizer.py": ["/lib/facerec/recognize.py", "/lib/facerec/encode.py"]}
|
22,913,425
|
bevzzz/bouncer
|
refs/heads/master
|
/lib/chatbot/state/conversationContext.py
|
import logging
from lib.chatbot.state.stateMain import StateMain
from lib.chatbot.state.stateAwait import StateAwait
from lib.chatbot.state.stateRecognize import StateRecognize
from lib.chatbot.state.stateAddPhoto import StateAddPhoto
class ConversationContext:
states = {
"StateMain": StateMain,
"StateAwait": StateAwait,
"StateRecognize": StateRecognize,
"StateAddPhoto": StateAddPhoto,
}
_instances = {}
def __init__(self, parent, update):
self.log = logging.getLogger()
self.parent = parent
self.update = update
self._last_message_id = None
self.last_state = None
self._state = None
self._instances[update.get_chat_id()] = self
@classmethod
def open(cls, parent, update):
chat_id = update.get_chat_id()
if chat_id in cls._instances:
instance = cls._instances[chat_id]
instance.set_update(update)
return instance
else:
return ConversationContext(parent, update)
def set_update(self, update):
self.update = update
def reply(self):
# set default state
if self._state is None:
self.change_state(StateMain(self))
# handle states
if self.update.get_phrase() != 'start':
last_state = self._state
self._state.set_next_state()
self.last_state = last_state
# pass necessary parameters
params = {}
self._state.invoke(params)
# execute command
self._state.act()
# update ui
response = self._state.get_response()
msg_id = self.parent.update_message(
chat_id=self.update.get_chat_id(),
to_delete_id=self._last_message_id,
to_send=response
)
self._last_message_id = msg_id
def change_state(self, state):
self._state = state
def download_photo(self):
file_id, caption = self.update.get_picture_with_caption()
photo = self.parent.chatbot.download_file(file_id)
return photo
def store_photo(self, photo, name, to_dir):
self.parent.storage.write_image(
img=photo,
name=name,
to_dir=to_dir
)
|
{"/lib/chatbot/reaction/reactionTrainModel.py": ["/lib/chatbot/reaction/reactionBase.py"], "/lib/chatbot/reaction/reactionCommandUnknown.py": ["/lib/chatbot/reaction/reactionBase.py"], "/lib/chatbot/reaction/reactionEnd.py": ["/lib/chatbot/reaction/reactionBase.py"], "/lib/facerec/recognition.py": ["/lib/utils/helpers.py", "/lib/facerec/model.py", "/lib/storage/localStorage.py"], "/lib/manager.py": ["/lib/chatbot/reaction/reactionFactory.py", "/lib/chatbot/conversation.py", "/lib/chatbot/state/conversationContext.py", "/lib/chatbot/state/UpdateParser.py"], "/lib/chatbot/reaction/reactionDefault.py": ["/lib/chatbot/reaction/reactionBase.py"], "/lib/chatbot/reaction/reactionBase.py": ["/lib/chatbot/telegramObject.py"], "/lib/chatbot/reaction/reactionFactory.py": ["/lib/chatbot/conversation.py", "/lib/chatbot/reaction/reactionDefault.py", "/lib/chatbot/reaction/reactionStart.py", "/lib/chatbot/reaction/reactionAuthorize.py", "/lib/chatbot/reaction/reactionDownloadPhoto.py", "/lib/chatbot/reaction/reactionEnd.py", "/lib/chatbot/reaction/reactionCommandUnknown.py", "/lib/chatbot/reaction/reactionRecognize.py", "/lib/chatbot/reaction/reactionTrainModel.py"], "/lib/camera/camera_test.py": ["/lib/camera/drawer.py"], "/lib/chatbot/reaction/reactionRecognize.py": ["/lib/chatbot/reaction/reactionBase.py"], "/lib/chatbot/reaction/reactionAuthorize.py": ["/lib/chatbot/reaction/reactionBase.py"], "/lib/chatbot/reaction/reactionStart.py": ["/lib/chatbot/reaction/reactionBase.py"], "/lib/chatbot/reaction/reactionDownloadPhoto.py": ["/lib/chatbot/reaction/reactionBase.py", "/lib/utils/helpers.py"], "/main.py": ["/lib/utils/startup_manager.py"], "/lib/utils/startup_manager.py": ["/lib/manager.py", "/lib/chatbot/telegramBot.py", "/lib/storage/localStorage.py"], "/lib/chatbot/state/conversationState.py": ["/lib/chatbot/telegramObject.py", "/lib/utils/helpers.py"], "/lib/chatbot/state/stateAwait.py": ["/lib/chatbot/state/conversationState.py", "/lib/chatbot/state/stateRecognize.py", "/lib/chatbot/state/stateAddPhoto.py"], "/lib/facerec/recognize.py": ["/lib/facerec/encode.py"], "/tests/testReactionFactory.py": ["/lib/utils/startup_manager.py", "/lib/chatbot/reaction/reactionFactory.py", "/lib/chatbot/reaction/reactionDefault.py", "/lib/chatbot/reaction/reactionStart.py", "/lib/chatbot/reaction/reactionAuthorize.py", "/lib/chatbot/reaction/reactionDownloadPhoto.py", "/lib/chatbot/reaction/reactionEnd.py", "/lib/chatbot/reaction/reactionCommandUnknown.py", "/lib/chatbot/reaction/reactionRecognize.py", "/lib/chatbot/reaction/reactionTrainModel.py"], "/lib/chatbot/state/stateUnknownInput.py": ["/lib/chatbot/state/conversationState.py"], "/lib/chatbot/state/UpdateParser.py": ["/lib/utils/user.py"], "/lib/chatbot/state/conversationContext.py": ["/lib/chatbot/state/stateAwait.py", "/lib/chatbot/state/stateRecognize.py", "/lib/chatbot/state/stateAddPhoto.py"], "/lib/storage/localStorage.py": ["/lib/storage/interface.py"], "/lib/chatbot/state/stateRecognize.py": ["/lib/chatbot/state/conversationState.py"], "/lib/chatbot/state/stateAddPhoto.py": ["/lib/chatbot/state/conversationState.py"], "/lib/facerec/tests/testEncoder.py": ["/lib/facerec/encode.py"], "/lib/chatbot/telegramBot.py": ["/lib/chatbot/interface.py", "/lib/chatbot/state/UpdateParser.py"], "/tests/testUpdatesHandler.py": ["/lib/utils/user.py"], "/lib/facerec/api.py": ["/lib/facerec/recognize.py"], "/lib/facerec/tests/testRecognizer.py": ["/lib/facerec/recognize.py", "/lib/facerec/encode.py"]}
|
22,913,426
|
bevzzz/bouncer
|
refs/heads/master
|
/svc/facerec.py
|
from flask import Flask
from flask_restx import Api, Resource, fields
app = Flask(__name__)
api = Api(app)
ns = api.namespace("facerec", description="Recognizing people's faces")
model = api.model("recognize", {
'name': fields.String
})
@ns.route('/recognize')
class RecognizeFace(Resource):
def get(self):
return "Dima"
def post(self):
return "Vasya"
if __name__ == "__main__":
app.run(debug=True, port=5000)
|
{"/lib/chatbot/reaction/reactionTrainModel.py": ["/lib/chatbot/reaction/reactionBase.py"], "/lib/chatbot/reaction/reactionCommandUnknown.py": ["/lib/chatbot/reaction/reactionBase.py"], "/lib/chatbot/reaction/reactionEnd.py": ["/lib/chatbot/reaction/reactionBase.py"], "/lib/facerec/recognition.py": ["/lib/utils/helpers.py", "/lib/facerec/model.py", "/lib/storage/localStorage.py"], "/lib/manager.py": ["/lib/chatbot/reaction/reactionFactory.py", "/lib/chatbot/conversation.py", "/lib/chatbot/state/conversationContext.py", "/lib/chatbot/state/UpdateParser.py"], "/lib/chatbot/reaction/reactionDefault.py": ["/lib/chatbot/reaction/reactionBase.py"], "/lib/chatbot/reaction/reactionBase.py": ["/lib/chatbot/telegramObject.py"], "/lib/chatbot/reaction/reactionFactory.py": ["/lib/chatbot/conversation.py", "/lib/chatbot/reaction/reactionDefault.py", "/lib/chatbot/reaction/reactionStart.py", "/lib/chatbot/reaction/reactionAuthorize.py", "/lib/chatbot/reaction/reactionDownloadPhoto.py", "/lib/chatbot/reaction/reactionEnd.py", "/lib/chatbot/reaction/reactionCommandUnknown.py", "/lib/chatbot/reaction/reactionRecognize.py", "/lib/chatbot/reaction/reactionTrainModel.py"], "/lib/camera/camera_test.py": ["/lib/camera/drawer.py"], "/lib/chatbot/reaction/reactionRecognize.py": ["/lib/chatbot/reaction/reactionBase.py"], "/lib/chatbot/reaction/reactionAuthorize.py": ["/lib/chatbot/reaction/reactionBase.py"], "/lib/chatbot/reaction/reactionStart.py": ["/lib/chatbot/reaction/reactionBase.py"], "/lib/chatbot/reaction/reactionDownloadPhoto.py": ["/lib/chatbot/reaction/reactionBase.py", "/lib/utils/helpers.py"], "/main.py": ["/lib/utils/startup_manager.py"], "/lib/utils/startup_manager.py": ["/lib/manager.py", "/lib/chatbot/telegramBot.py", "/lib/storage/localStorage.py"], "/lib/chatbot/state/conversationState.py": ["/lib/chatbot/telegramObject.py", "/lib/utils/helpers.py"], "/lib/chatbot/state/stateAwait.py": ["/lib/chatbot/state/conversationState.py", "/lib/chatbot/state/stateRecognize.py", "/lib/chatbot/state/stateAddPhoto.py"], "/lib/facerec/recognize.py": ["/lib/facerec/encode.py"], "/tests/testReactionFactory.py": ["/lib/utils/startup_manager.py", "/lib/chatbot/reaction/reactionFactory.py", "/lib/chatbot/reaction/reactionDefault.py", "/lib/chatbot/reaction/reactionStart.py", "/lib/chatbot/reaction/reactionAuthorize.py", "/lib/chatbot/reaction/reactionDownloadPhoto.py", "/lib/chatbot/reaction/reactionEnd.py", "/lib/chatbot/reaction/reactionCommandUnknown.py", "/lib/chatbot/reaction/reactionRecognize.py", "/lib/chatbot/reaction/reactionTrainModel.py"], "/lib/chatbot/state/stateUnknownInput.py": ["/lib/chatbot/state/conversationState.py"], "/lib/chatbot/state/UpdateParser.py": ["/lib/utils/user.py"], "/lib/chatbot/state/conversationContext.py": ["/lib/chatbot/state/stateAwait.py", "/lib/chatbot/state/stateRecognize.py", "/lib/chatbot/state/stateAddPhoto.py"], "/lib/storage/localStorage.py": ["/lib/storage/interface.py"], "/lib/chatbot/state/stateRecognize.py": ["/lib/chatbot/state/conversationState.py"], "/lib/chatbot/state/stateAddPhoto.py": ["/lib/chatbot/state/conversationState.py"], "/lib/facerec/tests/testEncoder.py": ["/lib/facerec/encode.py"], "/lib/chatbot/telegramBot.py": ["/lib/chatbot/interface.py", "/lib/chatbot/state/UpdateParser.py"], "/tests/testUpdatesHandler.py": ["/lib/utils/user.py"], "/lib/facerec/api.py": ["/lib/facerec/recognize.py"], "/lib/facerec/tests/testRecognizer.py": ["/lib/facerec/recognize.py", "/lib/facerec/encode.py"]}
|
22,913,427
|
bevzzz/bouncer
|
refs/heads/master
|
/lib/storage/localStorage.py
|
import os
import json
import pickle
from lib.storage.interface import Storage
class LocalStorage(Storage):
def __init__(self, root_path='images'):
self.root_path = os.path.join(
os.getcwd(),
'resources',
root_path
)
super().__init__()
def set_root_path(self, root_path):
self.root_path = os.path.join(
os.getcwd(),
'resources',
root_path
)
def _build_filepath(self, directory='', *args):
return os.path.join(
self.root_path,
directory,
*args
)
def list_directory(self, name=None):
if name is None:
filepath = self._build_filepath()
else:
filepath = self._build_filepath(name)
return os.listdir(filepath)
def is_empty_dir(self, path):
return self.list_directory(path) == []
def create_directory(self, name):
if not self.exists_directory(name):
self.log.info(f"Directory {name} didn't exist, adding")
filepath = self._build_filepath(name)
os.mkdir(filepath)
def _read_file(self, from_dir, name, func):
filepath = self._build_filepath(from_dir, name)
with open(filepath, 'rb') as from_file:
return func(
from_file.read()
)
def read_image(self, from_dir, name):
return self._read_file(
from_dir,
name,
func=lambda i_o: i_o
)
def read_json(self, from_dir, name):
return self._read_file(
from_dir,
name,
func=lambda i_o: json.loads(i_o)
)
def read_pickle(self, from_dir, name):
return self._read_file(
from_dir,
name,
func=lambda i_o: pickle.loads(i_o)
)
def _write_file(self, file, name, to_dir, func):
filepath = self._build_filepath(to_dir, name)
with open(filepath, 'wb') as to_file:
to_file.write(
func(file)
)
def write_image(self, img, name, to_dir=None):
self.log.info(f'Saving new image of {to_dir}')
self.create_directory(to_dir)
self._write_file(
img,
name,
to_dir,
func=lambda f: f
)
def write_json(self, file, name, to_dir=None):
self.log.info(f"Writing JSON: {name}")
self._write_file(
file,
name,
to_dir,
func=lambda f: json.dumps(f)
)
def write_pickle(self, file, name, to_dir=None):
self.log.info(f"Writing pickle: {name}")
self._write_file(
file,
name,
to_dir,
func=lambda f: pickle.dumps(f)
)
|
{"/lib/chatbot/reaction/reactionTrainModel.py": ["/lib/chatbot/reaction/reactionBase.py"], "/lib/chatbot/reaction/reactionCommandUnknown.py": ["/lib/chatbot/reaction/reactionBase.py"], "/lib/chatbot/reaction/reactionEnd.py": ["/lib/chatbot/reaction/reactionBase.py"], "/lib/facerec/recognition.py": ["/lib/utils/helpers.py", "/lib/facerec/model.py", "/lib/storage/localStorage.py"], "/lib/manager.py": ["/lib/chatbot/reaction/reactionFactory.py", "/lib/chatbot/conversation.py", "/lib/chatbot/state/conversationContext.py", "/lib/chatbot/state/UpdateParser.py"], "/lib/chatbot/reaction/reactionDefault.py": ["/lib/chatbot/reaction/reactionBase.py"], "/lib/chatbot/reaction/reactionBase.py": ["/lib/chatbot/telegramObject.py"], "/lib/chatbot/reaction/reactionFactory.py": ["/lib/chatbot/conversation.py", "/lib/chatbot/reaction/reactionDefault.py", "/lib/chatbot/reaction/reactionStart.py", "/lib/chatbot/reaction/reactionAuthorize.py", "/lib/chatbot/reaction/reactionDownloadPhoto.py", "/lib/chatbot/reaction/reactionEnd.py", "/lib/chatbot/reaction/reactionCommandUnknown.py", "/lib/chatbot/reaction/reactionRecognize.py", "/lib/chatbot/reaction/reactionTrainModel.py"], "/lib/camera/camera_test.py": ["/lib/camera/drawer.py"], "/lib/chatbot/reaction/reactionRecognize.py": ["/lib/chatbot/reaction/reactionBase.py"], "/lib/chatbot/reaction/reactionAuthorize.py": ["/lib/chatbot/reaction/reactionBase.py"], "/lib/chatbot/reaction/reactionStart.py": ["/lib/chatbot/reaction/reactionBase.py"], "/lib/chatbot/reaction/reactionDownloadPhoto.py": ["/lib/chatbot/reaction/reactionBase.py", "/lib/utils/helpers.py"], "/main.py": ["/lib/utils/startup_manager.py"], "/lib/utils/startup_manager.py": ["/lib/manager.py", "/lib/chatbot/telegramBot.py", "/lib/storage/localStorage.py"], "/lib/chatbot/state/conversationState.py": ["/lib/chatbot/telegramObject.py", "/lib/utils/helpers.py"], "/lib/chatbot/state/stateAwait.py": ["/lib/chatbot/state/conversationState.py", "/lib/chatbot/state/stateRecognize.py", "/lib/chatbot/state/stateAddPhoto.py"], "/lib/facerec/recognize.py": ["/lib/facerec/encode.py"], "/tests/testReactionFactory.py": ["/lib/utils/startup_manager.py", "/lib/chatbot/reaction/reactionFactory.py", "/lib/chatbot/reaction/reactionDefault.py", "/lib/chatbot/reaction/reactionStart.py", "/lib/chatbot/reaction/reactionAuthorize.py", "/lib/chatbot/reaction/reactionDownloadPhoto.py", "/lib/chatbot/reaction/reactionEnd.py", "/lib/chatbot/reaction/reactionCommandUnknown.py", "/lib/chatbot/reaction/reactionRecognize.py", "/lib/chatbot/reaction/reactionTrainModel.py"], "/lib/chatbot/state/stateUnknownInput.py": ["/lib/chatbot/state/conversationState.py"], "/lib/chatbot/state/UpdateParser.py": ["/lib/utils/user.py"], "/lib/chatbot/state/conversationContext.py": ["/lib/chatbot/state/stateAwait.py", "/lib/chatbot/state/stateRecognize.py", "/lib/chatbot/state/stateAddPhoto.py"], "/lib/storage/localStorage.py": ["/lib/storage/interface.py"], "/lib/chatbot/state/stateRecognize.py": ["/lib/chatbot/state/conversationState.py"], "/lib/chatbot/state/stateAddPhoto.py": ["/lib/chatbot/state/conversationState.py"], "/lib/facerec/tests/testEncoder.py": ["/lib/facerec/encode.py"], "/lib/chatbot/telegramBot.py": ["/lib/chatbot/interface.py", "/lib/chatbot/state/UpdateParser.py"], "/tests/testUpdatesHandler.py": ["/lib/utils/user.py"], "/lib/facerec/api.py": ["/lib/facerec/recognize.py"], "/lib/facerec/tests/testRecognizer.py": ["/lib/facerec/recognize.py", "/lib/facerec/encode.py"]}
|
22,913,428
|
bevzzz/bouncer
|
refs/heads/master
|
/lib/chatbot/state/stateRecognize.py
|
from lib.chatbot.state.conversationState import ConversationState
class StateRecognize(ConversationState):
buttons = {
"recognize": {
"label": "Try different photo",
"row": 1,
"next": "StateAwait"
},
"main": {
"label": "Back to main",
"row": 1,
"next": "StateMain"
}
}
def __init__(self, context):
self.photo = None
self.people_in_photo = None
self.error_happened = None
super().__init__(context)
def invoke(self, params):
self.photo = self.download_photo()
def act(self):
response = self._context.parent.send_request_to_recognize(
self.photo
).get('response')
if response['status'] == 200:
self.people_in_photo = response['content']['person']
else:
self.error_happened = True
def get_response(self):
if self.error_happened:
text = "Sorry, an error occurred while sending a request to Facerec"
elif not len(self.people_in_photo):
text = "Couldn't find a face in this photo :("
elif self._unknown_person():
text = "I do not know this person"
else:
text = f"I see {', '.join(self.people_in_photo)}"
return self.build_message(text=text)
def _unknown_person(self):
return self.people_in_photo[0] == 'Unknown'
def set_next_state(self):
super().set_next_state()
|
{"/lib/chatbot/reaction/reactionTrainModel.py": ["/lib/chatbot/reaction/reactionBase.py"], "/lib/chatbot/reaction/reactionCommandUnknown.py": ["/lib/chatbot/reaction/reactionBase.py"], "/lib/chatbot/reaction/reactionEnd.py": ["/lib/chatbot/reaction/reactionBase.py"], "/lib/facerec/recognition.py": ["/lib/utils/helpers.py", "/lib/facerec/model.py", "/lib/storage/localStorage.py"], "/lib/manager.py": ["/lib/chatbot/reaction/reactionFactory.py", "/lib/chatbot/conversation.py", "/lib/chatbot/state/conversationContext.py", "/lib/chatbot/state/UpdateParser.py"], "/lib/chatbot/reaction/reactionDefault.py": ["/lib/chatbot/reaction/reactionBase.py"], "/lib/chatbot/reaction/reactionBase.py": ["/lib/chatbot/telegramObject.py"], "/lib/chatbot/reaction/reactionFactory.py": ["/lib/chatbot/conversation.py", "/lib/chatbot/reaction/reactionDefault.py", "/lib/chatbot/reaction/reactionStart.py", "/lib/chatbot/reaction/reactionAuthorize.py", "/lib/chatbot/reaction/reactionDownloadPhoto.py", "/lib/chatbot/reaction/reactionEnd.py", "/lib/chatbot/reaction/reactionCommandUnknown.py", "/lib/chatbot/reaction/reactionRecognize.py", "/lib/chatbot/reaction/reactionTrainModel.py"], "/lib/camera/camera_test.py": ["/lib/camera/drawer.py"], "/lib/chatbot/reaction/reactionRecognize.py": ["/lib/chatbot/reaction/reactionBase.py"], "/lib/chatbot/reaction/reactionAuthorize.py": ["/lib/chatbot/reaction/reactionBase.py"], "/lib/chatbot/reaction/reactionStart.py": ["/lib/chatbot/reaction/reactionBase.py"], "/lib/chatbot/reaction/reactionDownloadPhoto.py": ["/lib/chatbot/reaction/reactionBase.py", "/lib/utils/helpers.py"], "/main.py": ["/lib/utils/startup_manager.py"], "/lib/utils/startup_manager.py": ["/lib/manager.py", "/lib/chatbot/telegramBot.py", "/lib/storage/localStorage.py"], "/lib/chatbot/state/conversationState.py": ["/lib/chatbot/telegramObject.py", "/lib/utils/helpers.py"], "/lib/chatbot/state/stateAwait.py": ["/lib/chatbot/state/conversationState.py", "/lib/chatbot/state/stateRecognize.py", "/lib/chatbot/state/stateAddPhoto.py"], "/lib/facerec/recognize.py": ["/lib/facerec/encode.py"], "/tests/testReactionFactory.py": ["/lib/utils/startup_manager.py", "/lib/chatbot/reaction/reactionFactory.py", "/lib/chatbot/reaction/reactionDefault.py", "/lib/chatbot/reaction/reactionStart.py", "/lib/chatbot/reaction/reactionAuthorize.py", "/lib/chatbot/reaction/reactionDownloadPhoto.py", "/lib/chatbot/reaction/reactionEnd.py", "/lib/chatbot/reaction/reactionCommandUnknown.py", "/lib/chatbot/reaction/reactionRecognize.py", "/lib/chatbot/reaction/reactionTrainModel.py"], "/lib/chatbot/state/stateUnknownInput.py": ["/lib/chatbot/state/conversationState.py"], "/lib/chatbot/state/UpdateParser.py": ["/lib/utils/user.py"], "/lib/chatbot/state/conversationContext.py": ["/lib/chatbot/state/stateAwait.py", "/lib/chatbot/state/stateRecognize.py", "/lib/chatbot/state/stateAddPhoto.py"], "/lib/storage/localStorage.py": ["/lib/storage/interface.py"], "/lib/chatbot/state/stateRecognize.py": ["/lib/chatbot/state/conversationState.py"], "/lib/chatbot/state/stateAddPhoto.py": ["/lib/chatbot/state/conversationState.py"], "/lib/facerec/tests/testEncoder.py": ["/lib/facerec/encode.py"], "/lib/chatbot/telegramBot.py": ["/lib/chatbot/interface.py", "/lib/chatbot/state/UpdateParser.py"], "/tests/testUpdatesHandler.py": ["/lib/utils/user.py"], "/lib/facerec/api.py": ["/lib/facerec/recognize.py"], "/lib/facerec/tests/testRecognizer.py": ["/lib/facerec/recognize.py", "/lib/facerec/encode.py"]}
|
22,913,429
|
bevzzz/bouncer
|
refs/heads/master
|
/lib/facerec/encode.py
|
import face_recognition
class Encoder:
"""
`Encoder` is a util class that detects faces in the image,
extracts boxes that contain them and for every box returns
an `<numpy.ndarray>` with the image inside the box encoded
"""
def __init__(self, method='hog'):
self.method = method
def locate(self, arr):
return face_recognition.face_locations(
img=arr,
model=self.method
)
def _encode_single(self, arr):
boxes = self.locate(arr)
return face_recognition.face_encodings(
face_image=arr,
known_face_locations=boxes
)
def _encode_multiple(self, list_array):
res = []
for arr in list_array:
res.append(self.locate(arr))
return res
def encode(self, *args):
if len(args) == 1:
return self._encode_single(args[0])
else:
return self._encode_multiple(args)
|
{"/lib/chatbot/reaction/reactionTrainModel.py": ["/lib/chatbot/reaction/reactionBase.py"], "/lib/chatbot/reaction/reactionCommandUnknown.py": ["/lib/chatbot/reaction/reactionBase.py"], "/lib/chatbot/reaction/reactionEnd.py": ["/lib/chatbot/reaction/reactionBase.py"], "/lib/facerec/recognition.py": ["/lib/utils/helpers.py", "/lib/facerec/model.py", "/lib/storage/localStorage.py"], "/lib/manager.py": ["/lib/chatbot/reaction/reactionFactory.py", "/lib/chatbot/conversation.py", "/lib/chatbot/state/conversationContext.py", "/lib/chatbot/state/UpdateParser.py"], "/lib/chatbot/reaction/reactionDefault.py": ["/lib/chatbot/reaction/reactionBase.py"], "/lib/chatbot/reaction/reactionBase.py": ["/lib/chatbot/telegramObject.py"], "/lib/chatbot/reaction/reactionFactory.py": ["/lib/chatbot/conversation.py", "/lib/chatbot/reaction/reactionDefault.py", "/lib/chatbot/reaction/reactionStart.py", "/lib/chatbot/reaction/reactionAuthorize.py", "/lib/chatbot/reaction/reactionDownloadPhoto.py", "/lib/chatbot/reaction/reactionEnd.py", "/lib/chatbot/reaction/reactionCommandUnknown.py", "/lib/chatbot/reaction/reactionRecognize.py", "/lib/chatbot/reaction/reactionTrainModel.py"], "/lib/camera/camera_test.py": ["/lib/camera/drawer.py"], "/lib/chatbot/reaction/reactionRecognize.py": ["/lib/chatbot/reaction/reactionBase.py"], "/lib/chatbot/reaction/reactionAuthorize.py": ["/lib/chatbot/reaction/reactionBase.py"], "/lib/chatbot/reaction/reactionStart.py": ["/lib/chatbot/reaction/reactionBase.py"], "/lib/chatbot/reaction/reactionDownloadPhoto.py": ["/lib/chatbot/reaction/reactionBase.py", "/lib/utils/helpers.py"], "/main.py": ["/lib/utils/startup_manager.py"], "/lib/utils/startup_manager.py": ["/lib/manager.py", "/lib/chatbot/telegramBot.py", "/lib/storage/localStorage.py"], "/lib/chatbot/state/conversationState.py": ["/lib/chatbot/telegramObject.py", "/lib/utils/helpers.py"], "/lib/chatbot/state/stateAwait.py": ["/lib/chatbot/state/conversationState.py", "/lib/chatbot/state/stateRecognize.py", "/lib/chatbot/state/stateAddPhoto.py"], "/lib/facerec/recognize.py": ["/lib/facerec/encode.py"], "/tests/testReactionFactory.py": ["/lib/utils/startup_manager.py", "/lib/chatbot/reaction/reactionFactory.py", "/lib/chatbot/reaction/reactionDefault.py", "/lib/chatbot/reaction/reactionStart.py", "/lib/chatbot/reaction/reactionAuthorize.py", "/lib/chatbot/reaction/reactionDownloadPhoto.py", "/lib/chatbot/reaction/reactionEnd.py", "/lib/chatbot/reaction/reactionCommandUnknown.py", "/lib/chatbot/reaction/reactionRecognize.py", "/lib/chatbot/reaction/reactionTrainModel.py"], "/lib/chatbot/state/stateUnknownInput.py": ["/lib/chatbot/state/conversationState.py"], "/lib/chatbot/state/UpdateParser.py": ["/lib/utils/user.py"], "/lib/chatbot/state/conversationContext.py": ["/lib/chatbot/state/stateAwait.py", "/lib/chatbot/state/stateRecognize.py", "/lib/chatbot/state/stateAddPhoto.py"], "/lib/storage/localStorage.py": ["/lib/storage/interface.py"], "/lib/chatbot/state/stateRecognize.py": ["/lib/chatbot/state/conversationState.py"], "/lib/chatbot/state/stateAddPhoto.py": ["/lib/chatbot/state/conversationState.py"], "/lib/facerec/tests/testEncoder.py": ["/lib/facerec/encode.py"], "/lib/chatbot/telegramBot.py": ["/lib/chatbot/interface.py", "/lib/chatbot/state/UpdateParser.py"], "/tests/testUpdatesHandler.py": ["/lib/utils/user.py"], "/lib/facerec/api.py": ["/lib/facerec/recognize.py"], "/lib/facerec/tests/testRecognizer.py": ["/lib/facerec/recognize.py", "/lib/facerec/encode.py"]}
|
22,913,430
|
bevzzz/bouncer
|
refs/heads/master
|
/lib/chatbot/state/stateAddPhoto.py
|
from lib.chatbot.state.conversationState import ConversationState
class StateAddPhoto(ConversationState):
buttons = {
"add_photo": {
"label": "Try again",
"row": 1,
"next": "StateAwait"
},
"main": {
"label": "Back to main",
"row": 2,
"next": "StateMain"
}
}
def __init__(self, context):
self.photo = None
self.error_happened = False
super().__init__(context)
def invoke(self, params):
self.photo = self.download_photo()
def act(self):
try:
self.store_photo(self.photo)
except AttributeError as err:
self.log.warning(err)
self.error_happened = True
def get_response(self):
if not self.error_happened:
text = "Nice pic! I added it to your personal folder"
else:
text = "Oh crap, I couldn't download that. Try again with a different photo"
return self.build_message(text=text)
def set_next_state(self):
super().set_next_state()
|
{"/lib/chatbot/reaction/reactionTrainModel.py": ["/lib/chatbot/reaction/reactionBase.py"], "/lib/chatbot/reaction/reactionCommandUnknown.py": ["/lib/chatbot/reaction/reactionBase.py"], "/lib/chatbot/reaction/reactionEnd.py": ["/lib/chatbot/reaction/reactionBase.py"], "/lib/facerec/recognition.py": ["/lib/utils/helpers.py", "/lib/facerec/model.py", "/lib/storage/localStorage.py"], "/lib/manager.py": ["/lib/chatbot/reaction/reactionFactory.py", "/lib/chatbot/conversation.py", "/lib/chatbot/state/conversationContext.py", "/lib/chatbot/state/UpdateParser.py"], "/lib/chatbot/reaction/reactionDefault.py": ["/lib/chatbot/reaction/reactionBase.py"], "/lib/chatbot/reaction/reactionBase.py": ["/lib/chatbot/telegramObject.py"], "/lib/chatbot/reaction/reactionFactory.py": ["/lib/chatbot/conversation.py", "/lib/chatbot/reaction/reactionDefault.py", "/lib/chatbot/reaction/reactionStart.py", "/lib/chatbot/reaction/reactionAuthorize.py", "/lib/chatbot/reaction/reactionDownloadPhoto.py", "/lib/chatbot/reaction/reactionEnd.py", "/lib/chatbot/reaction/reactionCommandUnknown.py", "/lib/chatbot/reaction/reactionRecognize.py", "/lib/chatbot/reaction/reactionTrainModel.py"], "/lib/camera/camera_test.py": ["/lib/camera/drawer.py"], "/lib/chatbot/reaction/reactionRecognize.py": ["/lib/chatbot/reaction/reactionBase.py"], "/lib/chatbot/reaction/reactionAuthorize.py": ["/lib/chatbot/reaction/reactionBase.py"], "/lib/chatbot/reaction/reactionStart.py": ["/lib/chatbot/reaction/reactionBase.py"], "/lib/chatbot/reaction/reactionDownloadPhoto.py": ["/lib/chatbot/reaction/reactionBase.py", "/lib/utils/helpers.py"], "/main.py": ["/lib/utils/startup_manager.py"], "/lib/utils/startup_manager.py": ["/lib/manager.py", "/lib/chatbot/telegramBot.py", "/lib/storage/localStorage.py"], "/lib/chatbot/state/conversationState.py": ["/lib/chatbot/telegramObject.py", "/lib/utils/helpers.py"], "/lib/chatbot/state/stateAwait.py": ["/lib/chatbot/state/conversationState.py", "/lib/chatbot/state/stateRecognize.py", "/lib/chatbot/state/stateAddPhoto.py"], "/lib/facerec/recognize.py": ["/lib/facerec/encode.py"], "/tests/testReactionFactory.py": ["/lib/utils/startup_manager.py", "/lib/chatbot/reaction/reactionFactory.py", "/lib/chatbot/reaction/reactionDefault.py", "/lib/chatbot/reaction/reactionStart.py", "/lib/chatbot/reaction/reactionAuthorize.py", "/lib/chatbot/reaction/reactionDownloadPhoto.py", "/lib/chatbot/reaction/reactionEnd.py", "/lib/chatbot/reaction/reactionCommandUnknown.py", "/lib/chatbot/reaction/reactionRecognize.py", "/lib/chatbot/reaction/reactionTrainModel.py"], "/lib/chatbot/state/stateUnknownInput.py": ["/lib/chatbot/state/conversationState.py"], "/lib/chatbot/state/UpdateParser.py": ["/lib/utils/user.py"], "/lib/chatbot/state/conversationContext.py": ["/lib/chatbot/state/stateAwait.py", "/lib/chatbot/state/stateRecognize.py", "/lib/chatbot/state/stateAddPhoto.py"], "/lib/storage/localStorage.py": ["/lib/storage/interface.py"], "/lib/chatbot/state/stateRecognize.py": ["/lib/chatbot/state/conversationState.py"], "/lib/chatbot/state/stateAddPhoto.py": ["/lib/chatbot/state/conversationState.py"], "/lib/facerec/tests/testEncoder.py": ["/lib/facerec/encode.py"], "/lib/chatbot/telegramBot.py": ["/lib/chatbot/interface.py", "/lib/chatbot/state/UpdateParser.py"], "/tests/testUpdatesHandler.py": ["/lib/utils/user.py"], "/lib/facerec/api.py": ["/lib/facerec/recognize.py"], "/lib/facerec/tests/testRecognizer.py": ["/lib/facerec/recognize.py", "/lib/facerec/encode.py"]}
|
22,913,431
|
bevzzz/bouncer
|
refs/heads/master
|
/lib/facerec/tests/testEncoder.py
|
import unittest
import face_recognition
from PIL import Image
import numpy as np
import lib.facerec.encode as e
class TestEncode(unittest.TestCase):
test_img_path = "/lib/facerec/tests/bin/dannydevito.png"
@classmethod
def setUpClass(cls):
cls.encoder = e.Encoder()
def get_test_image(self):
im = Image.open(self.test_img_path).convert("RGB")
return np.array(im)
def test_locate_faces(self):
# arrange
want = [(82, 311, 211, 182)]
arr = self.get_test_image()
# act
boxes = self.encoder.locate(arr)
# assert
self.assertEqual(boxes, want)
def test_encode_one(self):
# arrange
arr = self.get_test_image()
boxes = face_recognition.face_locations(arr, model='hog')
want = face_recognition.face_encodings(arr, boxes)
# act
got = self.encoder.encode(arr)
# assert
self.assertTrue(np.array_equal(got, want))
if __name__ == '__main__':
unittest.main()
|
{"/lib/chatbot/reaction/reactionTrainModel.py": ["/lib/chatbot/reaction/reactionBase.py"], "/lib/chatbot/reaction/reactionCommandUnknown.py": ["/lib/chatbot/reaction/reactionBase.py"], "/lib/chatbot/reaction/reactionEnd.py": ["/lib/chatbot/reaction/reactionBase.py"], "/lib/facerec/recognition.py": ["/lib/utils/helpers.py", "/lib/facerec/model.py", "/lib/storage/localStorage.py"], "/lib/manager.py": ["/lib/chatbot/reaction/reactionFactory.py", "/lib/chatbot/conversation.py", "/lib/chatbot/state/conversationContext.py", "/lib/chatbot/state/UpdateParser.py"], "/lib/chatbot/reaction/reactionDefault.py": ["/lib/chatbot/reaction/reactionBase.py"], "/lib/chatbot/reaction/reactionBase.py": ["/lib/chatbot/telegramObject.py"], "/lib/chatbot/reaction/reactionFactory.py": ["/lib/chatbot/conversation.py", "/lib/chatbot/reaction/reactionDefault.py", "/lib/chatbot/reaction/reactionStart.py", "/lib/chatbot/reaction/reactionAuthorize.py", "/lib/chatbot/reaction/reactionDownloadPhoto.py", "/lib/chatbot/reaction/reactionEnd.py", "/lib/chatbot/reaction/reactionCommandUnknown.py", "/lib/chatbot/reaction/reactionRecognize.py", "/lib/chatbot/reaction/reactionTrainModel.py"], "/lib/camera/camera_test.py": ["/lib/camera/drawer.py"], "/lib/chatbot/reaction/reactionRecognize.py": ["/lib/chatbot/reaction/reactionBase.py"], "/lib/chatbot/reaction/reactionAuthorize.py": ["/lib/chatbot/reaction/reactionBase.py"], "/lib/chatbot/reaction/reactionStart.py": ["/lib/chatbot/reaction/reactionBase.py"], "/lib/chatbot/reaction/reactionDownloadPhoto.py": ["/lib/chatbot/reaction/reactionBase.py", "/lib/utils/helpers.py"], "/main.py": ["/lib/utils/startup_manager.py"], "/lib/utils/startup_manager.py": ["/lib/manager.py", "/lib/chatbot/telegramBot.py", "/lib/storage/localStorage.py"], "/lib/chatbot/state/conversationState.py": ["/lib/chatbot/telegramObject.py", "/lib/utils/helpers.py"], "/lib/chatbot/state/stateAwait.py": ["/lib/chatbot/state/conversationState.py", "/lib/chatbot/state/stateRecognize.py", "/lib/chatbot/state/stateAddPhoto.py"], "/lib/facerec/recognize.py": ["/lib/facerec/encode.py"], "/tests/testReactionFactory.py": ["/lib/utils/startup_manager.py", "/lib/chatbot/reaction/reactionFactory.py", "/lib/chatbot/reaction/reactionDefault.py", "/lib/chatbot/reaction/reactionStart.py", "/lib/chatbot/reaction/reactionAuthorize.py", "/lib/chatbot/reaction/reactionDownloadPhoto.py", "/lib/chatbot/reaction/reactionEnd.py", "/lib/chatbot/reaction/reactionCommandUnknown.py", "/lib/chatbot/reaction/reactionRecognize.py", "/lib/chatbot/reaction/reactionTrainModel.py"], "/lib/chatbot/state/stateUnknownInput.py": ["/lib/chatbot/state/conversationState.py"], "/lib/chatbot/state/UpdateParser.py": ["/lib/utils/user.py"], "/lib/chatbot/state/conversationContext.py": ["/lib/chatbot/state/stateAwait.py", "/lib/chatbot/state/stateRecognize.py", "/lib/chatbot/state/stateAddPhoto.py"], "/lib/storage/localStorage.py": ["/lib/storage/interface.py"], "/lib/chatbot/state/stateRecognize.py": ["/lib/chatbot/state/conversationState.py"], "/lib/chatbot/state/stateAddPhoto.py": ["/lib/chatbot/state/conversationState.py"], "/lib/facerec/tests/testEncoder.py": ["/lib/facerec/encode.py"], "/lib/chatbot/telegramBot.py": ["/lib/chatbot/interface.py", "/lib/chatbot/state/UpdateParser.py"], "/tests/testUpdatesHandler.py": ["/lib/utils/user.py"], "/lib/facerec/api.py": ["/lib/facerec/recognize.py"], "/lib/facerec/tests/testRecognizer.py": ["/lib/facerec/recognize.py", "/lib/facerec/encode.py"]}
|
22,913,432
|
bevzzz/bouncer
|
refs/heads/master
|
/lib/chatbot/telegramBot.py
|
from lib.chatbot.interface import Chatbot
from lib.chatbot.state.UpdateParser import UpdateParser
import requests
import logging
class TelegramBot(Chatbot):
host_url = 'https://api.telegram.org'
def __init__(self, token):
super().__init__()
self.token = token
self.base_url = self._build_base_url()
self.offset = 0
self.updates = {}
self.log = logging.getLogger()
def _build_base_url(self):
return '{}/bot{}'.format(self.host_url, self.token)
def _build_request(self, method):
return '{}/{}'.format(self.base_url, method)
def _build_download_request(self, file_path):
return '{}/file/bot{}/{}'.format(self.host_url, self.token, file_path)
def get_me(self):
req = self._build_request('getMe')
response = requests.get(req).json()
return response['result']
def update_offset(self):
try:
self.offset = self.updates[-1]['update_id'] + 1
except IndexError:
pass
def get_updates(self):
req = self._build_request('getUpdates')
params = {'offset': self.offset}
response = requests.get(req, params).json()
self.updates = response.get('result', [])
return self.updates
def send_message(self, message_body):
req = self._build_request('sendMessage')
res = requests.post(req, message_body).json()
return res['result']['message_id']
def delete_message(self, chat_id, message_id):
req = self._build_request('deleteMessage')
params = {
'chat_id': chat_id,
'message_id': message_id,
}
requests.post(req, params).json()
def _get_file(self, file_id):
req = self._build_request('getFile')
params = {
'file_id': file_id
}
response = requests.get(req, params).json()
file_path = response['result']['file_path']
return file_path
def download_file(self, file_id):
file_path = self._get_file(file_id)
req = self._build_download_request(file_path)
byte_array = requests.get(req).content
return byte_array
def send_file(self, file, chat_id):
req = self._build_request('sendPhoto')
data = {
'chat_id': chat_id
}
files = {
'photo': file
}
requests.post(req, data=data, files=files).json()
|
{"/lib/chatbot/reaction/reactionTrainModel.py": ["/lib/chatbot/reaction/reactionBase.py"], "/lib/chatbot/reaction/reactionCommandUnknown.py": ["/lib/chatbot/reaction/reactionBase.py"], "/lib/chatbot/reaction/reactionEnd.py": ["/lib/chatbot/reaction/reactionBase.py"], "/lib/facerec/recognition.py": ["/lib/utils/helpers.py", "/lib/facerec/model.py", "/lib/storage/localStorage.py"], "/lib/manager.py": ["/lib/chatbot/reaction/reactionFactory.py", "/lib/chatbot/conversation.py", "/lib/chatbot/state/conversationContext.py", "/lib/chatbot/state/UpdateParser.py"], "/lib/chatbot/reaction/reactionDefault.py": ["/lib/chatbot/reaction/reactionBase.py"], "/lib/chatbot/reaction/reactionBase.py": ["/lib/chatbot/telegramObject.py"], "/lib/chatbot/reaction/reactionFactory.py": ["/lib/chatbot/conversation.py", "/lib/chatbot/reaction/reactionDefault.py", "/lib/chatbot/reaction/reactionStart.py", "/lib/chatbot/reaction/reactionAuthorize.py", "/lib/chatbot/reaction/reactionDownloadPhoto.py", "/lib/chatbot/reaction/reactionEnd.py", "/lib/chatbot/reaction/reactionCommandUnknown.py", "/lib/chatbot/reaction/reactionRecognize.py", "/lib/chatbot/reaction/reactionTrainModel.py"], "/lib/camera/camera_test.py": ["/lib/camera/drawer.py"], "/lib/chatbot/reaction/reactionRecognize.py": ["/lib/chatbot/reaction/reactionBase.py"], "/lib/chatbot/reaction/reactionAuthorize.py": ["/lib/chatbot/reaction/reactionBase.py"], "/lib/chatbot/reaction/reactionStart.py": ["/lib/chatbot/reaction/reactionBase.py"], "/lib/chatbot/reaction/reactionDownloadPhoto.py": ["/lib/chatbot/reaction/reactionBase.py", "/lib/utils/helpers.py"], "/main.py": ["/lib/utils/startup_manager.py"], "/lib/utils/startup_manager.py": ["/lib/manager.py", "/lib/chatbot/telegramBot.py", "/lib/storage/localStorage.py"], "/lib/chatbot/state/conversationState.py": ["/lib/chatbot/telegramObject.py", "/lib/utils/helpers.py"], "/lib/chatbot/state/stateAwait.py": ["/lib/chatbot/state/conversationState.py", "/lib/chatbot/state/stateRecognize.py", "/lib/chatbot/state/stateAddPhoto.py"], "/lib/facerec/recognize.py": ["/lib/facerec/encode.py"], "/tests/testReactionFactory.py": ["/lib/utils/startup_manager.py", "/lib/chatbot/reaction/reactionFactory.py", "/lib/chatbot/reaction/reactionDefault.py", "/lib/chatbot/reaction/reactionStart.py", "/lib/chatbot/reaction/reactionAuthorize.py", "/lib/chatbot/reaction/reactionDownloadPhoto.py", "/lib/chatbot/reaction/reactionEnd.py", "/lib/chatbot/reaction/reactionCommandUnknown.py", "/lib/chatbot/reaction/reactionRecognize.py", "/lib/chatbot/reaction/reactionTrainModel.py"], "/lib/chatbot/state/stateUnknownInput.py": ["/lib/chatbot/state/conversationState.py"], "/lib/chatbot/state/UpdateParser.py": ["/lib/utils/user.py"], "/lib/chatbot/state/conversationContext.py": ["/lib/chatbot/state/stateAwait.py", "/lib/chatbot/state/stateRecognize.py", "/lib/chatbot/state/stateAddPhoto.py"], "/lib/storage/localStorage.py": ["/lib/storage/interface.py"], "/lib/chatbot/state/stateRecognize.py": ["/lib/chatbot/state/conversationState.py"], "/lib/chatbot/state/stateAddPhoto.py": ["/lib/chatbot/state/conversationState.py"], "/lib/facerec/tests/testEncoder.py": ["/lib/facerec/encode.py"], "/lib/chatbot/telegramBot.py": ["/lib/chatbot/interface.py", "/lib/chatbot/state/UpdateParser.py"], "/tests/testUpdatesHandler.py": ["/lib/utils/user.py"], "/lib/facerec/api.py": ["/lib/facerec/recognize.py"], "/lib/facerec/tests/testRecognizer.py": ["/lib/facerec/recognize.py", "/lib/facerec/encode.py"]}
|
22,913,433
|
bevzzz/bouncer
|
refs/heads/master
|
/tests/testUpdatesHandler.py
|
import unittest
from lib.chatbot.updatesHandler import UpdatesHandler
from lib.chatbot.updatesHandler import MessageDTO
from lib.chatbot.updatesHandler import CallbackDTO
from lib.utils.user import Owner
class UpdatesHandlerTest(unittest.TestCase):
valid_message = {'update_id': 317007528, 'message': {'message_id': 16, 'from': {'id': 113728330, 'is_bot': False, 'first_name': 'Dima', 'last_name': 'Solovei', 'username': 'bevzzz', 'language_code': 'en'}, 'chat': {'id': 113728330, 'first_name': 'Dima', 'last_name': 'Solovei', 'username': 'bevzzz', 'type': 'private'}, 'date': 1619760481, 'text': '/recognize', 'entities': [{'offset': 0, 'length': 6, 'type': 'bot_command'}]}}
valid_callback = {'update_id': 317007529, 'callback_query': {'id': '488459458556047547', 'from': {'id': 113728330, 'is_bot': False, 'first_name': 'Dima', 'last_name': 'Solovei', 'username': 'bevzzz', 'language_code': 'en'}, 'message': {'message_id': 17, 'from': {'id': 1790996180, 'is_bot': True, 'first_name': 'Sobaka', 'username': 'dvoretzki_bot'}, 'chat': {'id': 113728330, 'first_name': 'Dima', 'last_name': 'Solovei', 'username': 'bevzzz', 'type': 'private'}, 'date': 1619760482, 'text': 'Hi, Dima!', 'reply_markup': {'inline_keyboard': [[{'text': 'Recognize', 'callback_data': 'recognize'}], [{'text': 'Save photo', 'callback_data': 'save_photo'}], [{'text': 'Train', 'callback_data': 'train'}]]}}, 'chat_instance': '-3889430022395058016', 'data': 'recognize'}}
def get_MessageDTO(self):
message = self.valid_message.get('message')
return MessageDTO(message)
def get_CallbackDTO(self):
cb = self.valid_callback.get('callback_query')
return CallbackDTO(cb)
def test_factory_msg(self):
# arrange
# act
handler = UpdatesHandler().factory(self.valid_message)
# assert
self.assertIsInstance(handler, MessageDTO)
def test_factory_cb(self):
# arrange
# act
handler = UpdatesHandler().factory(self.valid_callback)
# assert
self.assertIsInstance(handler, CallbackDTO)
def test_create_message_dto(self):
# arrange
message = self.valid_message.get('message')
# act
handler = MessageDTO(message)
# assert
self.assertIsNotNone(handler)
self.assertFalse(handler.is_read())
self.assertIsInstance(handler.get_author(), Owner)
def test_create_callback_dto(self):
# arrange
cb = self.valid_callback.get('callback_query')
# act
handler = CallbackDTO(cb)
# assert
self.assertFalse(handler.has_photo())
self.assertIsInstance(handler.get_author(), Owner)
def test_mark_as_read_msg(self):
# arrange
handler = self.get_MessageDTO()
# act
handler.mark_as_read()
# assert
self.assertTrue(handler.is_read())
def test_get_chat_id_msg(self):
# arrange
handler = self.get_MessageDTO()
# act
chat_id = handler.get_chat_id()
# assert
self.assertEqual(chat_id, '113728330')
def test_get_message_id(self):
# arrange
handler = self.get_MessageDTO()
# act
message_id = handler.get_message_id()
# assert
self.assertEqual(message_id, 16)
def test_is_private_cb(self):
# arrange
handler = self.get_CallbackDTO()
# act
# assert
self.assertTrue(handler.is_private_chat())
def test_is_private_msg(self):
# arrange
handler = self.get_MessageDTO()
# act
# assert
self.assertTrue(handler.is_private_chat())
def test_entities_dict_msg(self):
# arrange
handler = self.get_MessageDTO()
# act
entities = handler._entities()
# assert
self.assertIsInstance(entities, dict)
def test_entities_empty_msg(self):
# arrange
message = dict(self.valid_message['message'])
del message['entities']
message = {'message': message}
handler = UpdatesHandler.factory(message)
# act
entities = handler._entities()
# assert
self.assertEqual(entities, {})
def test_entities_empty_cd(self):
# arrange
handler = self.get_CallbackDTO()
# act
entities = handler._entities()
# assert
self.assertEqual(entities, {})
def test_is_command_msg(self):
# arrange
handler = self.get_MessageDTO()
# act
# assert
self.assertTrue(handler.is_command())
def test_is_command_cb(self):
# arrange
handler = self.get_CallbackDTO()
# act
# assert
self.assertTrue(handler.is_command())
def test_get_phrase_cb(self):
# arrange
handler = self.get_CallbackDTO()
# act
phrase = handler.get_phrase()
# assert
self.assertEqual(phrase, 'recognize')
def test_get_phrase_msg(self):
# arrange
handler = self.get_MessageDTO()
# act
phrase = handler.get_phrase()
# assert
self.assertEqual(phrase, 'recognize')
def test_phrase_identical(self):
# arrange
msg_handler = self.get_MessageDTO()
cb_handler = self.get_CallbackDTO()
# act
msg_phrase = msg_handler.get_phrase()
cb_phrase = cb_handler.get_phrase()
# assert
self.assertEqual(msg_phrase, cb_phrase)
if __name__ == '__main__':
unittest.main()
|
{"/lib/chatbot/reaction/reactionTrainModel.py": ["/lib/chatbot/reaction/reactionBase.py"], "/lib/chatbot/reaction/reactionCommandUnknown.py": ["/lib/chatbot/reaction/reactionBase.py"], "/lib/chatbot/reaction/reactionEnd.py": ["/lib/chatbot/reaction/reactionBase.py"], "/lib/facerec/recognition.py": ["/lib/utils/helpers.py", "/lib/facerec/model.py", "/lib/storage/localStorage.py"], "/lib/manager.py": ["/lib/chatbot/reaction/reactionFactory.py", "/lib/chatbot/conversation.py", "/lib/chatbot/state/conversationContext.py", "/lib/chatbot/state/UpdateParser.py"], "/lib/chatbot/reaction/reactionDefault.py": ["/lib/chatbot/reaction/reactionBase.py"], "/lib/chatbot/reaction/reactionBase.py": ["/lib/chatbot/telegramObject.py"], "/lib/chatbot/reaction/reactionFactory.py": ["/lib/chatbot/conversation.py", "/lib/chatbot/reaction/reactionDefault.py", "/lib/chatbot/reaction/reactionStart.py", "/lib/chatbot/reaction/reactionAuthorize.py", "/lib/chatbot/reaction/reactionDownloadPhoto.py", "/lib/chatbot/reaction/reactionEnd.py", "/lib/chatbot/reaction/reactionCommandUnknown.py", "/lib/chatbot/reaction/reactionRecognize.py", "/lib/chatbot/reaction/reactionTrainModel.py"], "/lib/camera/camera_test.py": ["/lib/camera/drawer.py"], "/lib/chatbot/reaction/reactionRecognize.py": ["/lib/chatbot/reaction/reactionBase.py"], "/lib/chatbot/reaction/reactionAuthorize.py": ["/lib/chatbot/reaction/reactionBase.py"], "/lib/chatbot/reaction/reactionStart.py": ["/lib/chatbot/reaction/reactionBase.py"], "/lib/chatbot/reaction/reactionDownloadPhoto.py": ["/lib/chatbot/reaction/reactionBase.py", "/lib/utils/helpers.py"], "/main.py": ["/lib/utils/startup_manager.py"], "/lib/utils/startup_manager.py": ["/lib/manager.py", "/lib/chatbot/telegramBot.py", "/lib/storage/localStorage.py"], "/lib/chatbot/state/conversationState.py": ["/lib/chatbot/telegramObject.py", "/lib/utils/helpers.py"], "/lib/chatbot/state/stateAwait.py": ["/lib/chatbot/state/conversationState.py", "/lib/chatbot/state/stateRecognize.py", "/lib/chatbot/state/stateAddPhoto.py"], "/lib/facerec/recognize.py": ["/lib/facerec/encode.py"], "/tests/testReactionFactory.py": ["/lib/utils/startup_manager.py", "/lib/chatbot/reaction/reactionFactory.py", "/lib/chatbot/reaction/reactionDefault.py", "/lib/chatbot/reaction/reactionStart.py", "/lib/chatbot/reaction/reactionAuthorize.py", "/lib/chatbot/reaction/reactionDownloadPhoto.py", "/lib/chatbot/reaction/reactionEnd.py", "/lib/chatbot/reaction/reactionCommandUnknown.py", "/lib/chatbot/reaction/reactionRecognize.py", "/lib/chatbot/reaction/reactionTrainModel.py"], "/lib/chatbot/state/stateUnknownInput.py": ["/lib/chatbot/state/conversationState.py"], "/lib/chatbot/state/UpdateParser.py": ["/lib/utils/user.py"], "/lib/chatbot/state/conversationContext.py": ["/lib/chatbot/state/stateAwait.py", "/lib/chatbot/state/stateRecognize.py", "/lib/chatbot/state/stateAddPhoto.py"], "/lib/storage/localStorage.py": ["/lib/storage/interface.py"], "/lib/chatbot/state/stateRecognize.py": ["/lib/chatbot/state/conversationState.py"], "/lib/chatbot/state/stateAddPhoto.py": ["/lib/chatbot/state/conversationState.py"], "/lib/facerec/tests/testEncoder.py": ["/lib/facerec/encode.py"], "/lib/chatbot/telegramBot.py": ["/lib/chatbot/interface.py", "/lib/chatbot/state/UpdateParser.py"], "/tests/testUpdatesHandler.py": ["/lib/utils/user.py"], "/lib/facerec/api.py": ["/lib/facerec/recognize.py"], "/lib/facerec/tests/testRecognizer.py": ["/lib/facerec/recognize.py", "/lib/facerec/encode.py"]}
|
22,913,434
|
bevzzz/bouncer
|
refs/heads/master
|
/lib/utils/helpers.py
|
from datetime import datetime
from functools import reduce
def get_timestamp():
ts = datetime.now().strftime('%Y%m%d%H%M%S')
return ts
def dict_len(dictionary):
values_lengths = [len(v) for v in dictionary.values()]
return reduce(lambda a, b: a + b, values_lengths)
|
{"/lib/chatbot/reaction/reactionTrainModel.py": ["/lib/chatbot/reaction/reactionBase.py"], "/lib/chatbot/reaction/reactionCommandUnknown.py": ["/lib/chatbot/reaction/reactionBase.py"], "/lib/chatbot/reaction/reactionEnd.py": ["/lib/chatbot/reaction/reactionBase.py"], "/lib/facerec/recognition.py": ["/lib/utils/helpers.py", "/lib/facerec/model.py", "/lib/storage/localStorage.py"], "/lib/manager.py": ["/lib/chatbot/reaction/reactionFactory.py", "/lib/chatbot/conversation.py", "/lib/chatbot/state/conversationContext.py", "/lib/chatbot/state/UpdateParser.py"], "/lib/chatbot/reaction/reactionDefault.py": ["/lib/chatbot/reaction/reactionBase.py"], "/lib/chatbot/reaction/reactionBase.py": ["/lib/chatbot/telegramObject.py"], "/lib/chatbot/reaction/reactionFactory.py": ["/lib/chatbot/conversation.py", "/lib/chatbot/reaction/reactionDefault.py", "/lib/chatbot/reaction/reactionStart.py", "/lib/chatbot/reaction/reactionAuthorize.py", "/lib/chatbot/reaction/reactionDownloadPhoto.py", "/lib/chatbot/reaction/reactionEnd.py", "/lib/chatbot/reaction/reactionCommandUnknown.py", "/lib/chatbot/reaction/reactionRecognize.py", "/lib/chatbot/reaction/reactionTrainModel.py"], "/lib/camera/camera_test.py": ["/lib/camera/drawer.py"], "/lib/chatbot/reaction/reactionRecognize.py": ["/lib/chatbot/reaction/reactionBase.py"], "/lib/chatbot/reaction/reactionAuthorize.py": ["/lib/chatbot/reaction/reactionBase.py"], "/lib/chatbot/reaction/reactionStart.py": ["/lib/chatbot/reaction/reactionBase.py"], "/lib/chatbot/reaction/reactionDownloadPhoto.py": ["/lib/chatbot/reaction/reactionBase.py", "/lib/utils/helpers.py"], "/main.py": ["/lib/utils/startup_manager.py"], "/lib/utils/startup_manager.py": ["/lib/manager.py", "/lib/chatbot/telegramBot.py", "/lib/storage/localStorage.py"], "/lib/chatbot/state/conversationState.py": ["/lib/chatbot/telegramObject.py", "/lib/utils/helpers.py"], "/lib/chatbot/state/stateAwait.py": ["/lib/chatbot/state/conversationState.py", "/lib/chatbot/state/stateRecognize.py", "/lib/chatbot/state/stateAddPhoto.py"], "/lib/facerec/recognize.py": ["/lib/facerec/encode.py"], "/tests/testReactionFactory.py": ["/lib/utils/startup_manager.py", "/lib/chatbot/reaction/reactionFactory.py", "/lib/chatbot/reaction/reactionDefault.py", "/lib/chatbot/reaction/reactionStart.py", "/lib/chatbot/reaction/reactionAuthorize.py", "/lib/chatbot/reaction/reactionDownloadPhoto.py", "/lib/chatbot/reaction/reactionEnd.py", "/lib/chatbot/reaction/reactionCommandUnknown.py", "/lib/chatbot/reaction/reactionRecognize.py", "/lib/chatbot/reaction/reactionTrainModel.py"], "/lib/chatbot/state/stateUnknownInput.py": ["/lib/chatbot/state/conversationState.py"], "/lib/chatbot/state/UpdateParser.py": ["/lib/utils/user.py"], "/lib/chatbot/state/conversationContext.py": ["/lib/chatbot/state/stateAwait.py", "/lib/chatbot/state/stateRecognize.py", "/lib/chatbot/state/stateAddPhoto.py"], "/lib/storage/localStorage.py": ["/lib/storage/interface.py"], "/lib/chatbot/state/stateRecognize.py": ["/lib/chatbot/state/conversationState.py"], "/lib/chatbot/state/stateAddPhoto.py": ["/lib/chatbot/state/conversationState.py"], "/lib/facerec/tests/testEncoder.py": ["/lib/facerec/encode.py"], "/lib/chatbot/telegramBot.py": ["/lib/chatbot/interface.py", "/lib/chatbot/state/UpdateParser.py"], "/tests/testUpdatesHandler.py": ["/lib/utils/user.py"], "/lib/facerec/api.py": ["/lib/facerec/recognize.py"], "/lib/facerec/tests/testRecognizer.py": ["/lib/facerec/recognize.py", "/lib/facerec/encode.py"]}
|
22,913,435
|
bevzzz/bouncer
|
refs/heads/master
|
/lib/chatbot/telegramObject.py
|
import json
class TelegramObject:
def __str__(self):
return str(self.to_dict())
def __getitem__(self, item):
return self.__dict__[item]
def __setitem__(self, key, value):
self.__dict__[key] = value
def to_dict(self):
data = dict()
for key in iter(self.__dict__):
value = self.__dict__[key]
if value is not None:
if hasattr(value, 'to_dict'):
data[key] = value.to_dict()
else:
data[key] = value
return data
class TextMessage(TelegramObject):
def __init__(self, text, chat_id=None, reply_markup=None):
self.text = text
self.chat_id = chat_id
self.reply_markup = reply_markup
def to_dict(self):
data = super().to_dict()
if self.reply_markup is not None:
reply_markup = self.reply_markup.to_dict()
data['reply_markup'] = json.dumps(reply_markup)
return data
class InlineKeyboardButton(TelegramObject):
def __init__(
self,
text,
url=None,
login_url=None,
callback_data=None
):
self.text = text
self.url = url
self.login_url = login_url
self.callback_data = callback_data
super().__init__()
class InlineKeyboardMarkup(TelegramObject):
def __init__(self, inline_keyboard):
self.inline_keyboard = []
for row in inline_keyboard:
button_row = []
for button in row:
if isinstance(button, InlineKeyboardButton):
button_row.append(button)
else: # passed as string
button_row.append(InlineKeyboardButton(button))
self.inline_keyboard.append(button_row)
def to_dict(self):
data = super().to_dict()
data['inline_keyboard'] = []
for inline_key in self.inline_keyboard:
inline_key = [x.to_dict() for x in inline_key]
data['inline_keyboard'].append(inline_key)
return data
class KeyboardButton(TelegramObject):
def __init__(
self,
text,
request_contact=None,
request_location=None,
request_pole=None
):
self.text = text
self.request_contact = request_contact
self.request_location = request_location
self.request_pole = request_pole
class ReplyKeyboardMarkup(TelegramObject):
def __init__(
self,
keyboard,
resize_keyboard=False,
one_time_keyboard=True,
selective=False
):
self.keyboard = []
for row in keyboard:
button_row = []
for button in row:
if isinstance(button, KeyboardButton):
button_row.append(button)
else: # passed as string
button_row.append(KeyboardButton(button))
self.keyboard.append(button_row)
self.keyboard = keyboard
self.resize_keyboard = resize_keyboard
self.one_time_keyboard = one_time_keyboard
self.selective = selective
def to_dict(self):
data = super().to_dict()
data['keyboard'] = []
for row in self.keyboard:
button_row = [button.to_dict() for button in row]
data['keyboard'].append(button_row)
return data
|
{"/lib/chatbot/reaction/reactionTrainModel.py": ["/lib/chatbot/reaction/reactionBase.py"], "/lib/chatbot/reaction/reactionCommandUnknown.py": ["/lib/chatbot/reaction/reactionBase.py"], "/lib/chatbot/reaction/reactionEnd.py": ["/lib/chatbot/reaction/reactionBase.py"], "/lib/facerec/recognition.py": ["/lib/utils/helpers.py", "/lib/facerec/model.py", "/lib/storage/localStorage.py"], "/lib/manager.py": ["/lib/chatbot/reaction/reactionFactory.py", "/lib/chatbot/conversation.py", "/lib/chatbot/state/conversationContext.py", "/lib/chatbot/state/UpdateParser.py"], "/lib/chatbot/reaction/reactionDefault.py": ["/lib/chatbot/reaction/reactionBase.py"], "/lib/chatbot/reaction/reactionBase.py": ["/lib/chatbot/telegramObject.py"], "/lib/chatbot/reaction/reactionFactory.py": ["/lib/chatbot/conversation.py", "/lib/chatbot/reaction/reactionDefault.py", "/lib/chatbot/reaction/reactionStart.py", "/lib/chatbot/reaction/reactionAuthorize.py", "/lib/chatbot/reaction/reactionDownloadPhoto.py", "/lib/chatbot/reaction/reactionEnd.py", "/lib/chatbot/reaction/reactionCommandUnknown.py", "/lib/chatbot/reaction/reactionRecognize.py", "/lib/chatbot/reaction/reactionTrainModel.py"], "/lib/camera/camera_test.py": ["/lib/camera/drawer.py"], "/lib/chatbot/reaction/reactionRecognize.py": ["/lib/chatbot/reaction/reactionBase.py"], "/lib/chatbot/reaction/reactionAuthorize.py": ["/lib/chatbot/reaction/reactionBase.py"], "/lib/chatbot/reaction/reactionStart.py": ["/lib/chatbot/reaction/reactionBase.py"], "/lib/chatbot/reaction/reactionDownloadPhoto.py": ["/lib/chatbot/reaction/reactionBase.py", "/lib/utils/helpers.py"], "/main.py": ["/lib/utils/startup_manager.py"], "/lib/utils/startup_manager.py": ["/lib/manager.py", "/lib/chatbot/telegramBot.py", "/lib/storage/localStorage.py"], "/lib/chatbot/state/conversationState.py": ["/lib/chatbot/telegramObject.py", "/lib/utils/helpers.py"], "/lib/chatbot/state/stateAwait.py": ["/lib/chatbot/state/conversationState.py", "/lib/chatbot/state/stateRecognize.py", "/lib/chatbot/state/stateAddPhoto.py"], "/lib/facerec/recognize.py": ["/lib/facerec/encode.py"], "/tests/testReactionFactory.py": ["/lib/utils/startup_manager.py", "/lib/chatbot/reaction/reactionFactory.py", "/lib/chatbot/reaction/reactionDefault.py", "/lib/chatbot/reaction/reactionStart.py", "/lib/chatbot/reaction/reactionAuthorize.py", "/lib/chatbot/reaction/reactionDownloadPhoto.py", "/lib/chatbot/reaction/reactionEnd.py", "/lib/chatbot/reaction/reactionCommandUnknown.py", "/lib/chatbot/reaction/reactionRecognize.py", "/lib/chatbot/reaction/reactionTrainModel.py"], "/lib/chatbot/state/stateUnknownInput.py": ["/lib/chatbot/state/conversationState.py"], "/lib/chatbot/state/UpdateParser.py": ["/lib/utils/user.py"], "/lib/chatbot/state/conversationContext.py": ["/lib/chatbot/state/stateAwait.py", "/lib/chatbot/state/stateRecognize.py", "/lib/chatbot/state/stateAddPhoto.py"], "/lib/storage/localStorage.py": ["/lib/storage/interface.py"], "/lib/chatbot/state/stateRecognize.py": ["/lib/chatbot/state/conversationState.py"], "/lib/chatbot/state/stateAddPhoto.py": ["/lib/chatbot/state/conversationState.py"], "/lib/facerec/tests/testEncoder.py": ["/lib/facerec/encode.py"], "/lib/chatbot/telegramBot.py": ["/lib/chatbot/interface.py", "/lib/chatbot/state/UpdateParser.py"], "/tests/testUpdatesHandler.py": ["/lib/utils/user.py"], "/lib/facerec/api.py": ["/lib/facerec/recognize.py"], "/lib/facerec/tests/testRecognizer.py": ["/lib/facerec/recognize.py", "/lib/facerec/encode.py"]}
|
22,913,436
|
bevzzz/bouncer
|
refs/heads/master
|
/lib/utils/user.py
|
class Owner:
"""
Represents a person, who talks to TelegramBot and whose pictures might be sent.
Has information about the Storage (both LocalStorage and DriveStorage) where
files related to him are written to/read from.
"""
instances = {}
def __init__(self, owner_dto):
self.username = owner_dto.get_username()
self.owner_id = owner_dto.get_id()
self.first_name = owner_dto.get_firstname()
self.last_name = owner_dto.get_lastname()
self.full_name = owner_dto.get_fullname()
self.instances[self.owner_id] = self
@classmethod
def get_instance(cls, params):
owner_dto = OwnerDTO(params)
owner_id = owner_dto.get_id()
try:
owner = cls.instances[owner_id]
except KeyError:
owner = cls(owner_dto)
return owner
def get_name(self):
if self.first_name:
return self.first_name
else:
return self.get_username()
def get_username(self):
return self.username
class OwnerDTO:
def __init__(self, params):
self.params = params
def get_id(self):
return self.params['id']
def is_bot(self):
return self.params['is_bot']
def get_username(self):
return self.params.get('username', '')
def get_firstname(self):
return self.params.get('first_name', '')
def get_lastname(self):
return self.params.get('last_name', '')
def get_fullname(self):
firstname = self.get_firstname()
lastname = self.get_lastname()
return ' '.join([firstname, lastname])
|
{"/lib/chatbot/reaction/reactionTrainModel.py": ["/lib/chatbot/reaction/reactionBase.py"], "/lib/chatbot/reaction/reactionCommandUnknown.py": ["/lib/chatbot/reaction/reactionBase.py"], "/lib/chatbot/reaction/reactionEnd.py": ["/lib/chatbot/reaction/reactionBase.py"], "/lib/facerec/recognition.py": ["/lib/utils/helpers.py", "/lib/facerec/model.py", "/lib/storage/localStorage.py"], "/lib/manager.py": ["/lib/chatbot/reaction/reactionFactory.py", "/lib/chatbot/conversation.py", "/lib/chatbot/state/conversationContext.py", "/lib/chatbot/state/UpdateParser.py"], "/lib/chatbot/reaction/reactionDefault.py": ["/lib/chatbot/reaction/reactionBase.py"], "/lib/chatbot/reaction/reactionBase.py": ["/lib/chatbot/telegramObject.py"], "/lib/chatbot/reaction/reactionFactory.py": ["/lib/chatbot/conversation.py", "/lib/chatbot/reaction/reactionDefault.py", "/lib/chatbot/reaction/reactionStart.py", "/lib/chatbot/reaction/reactionAuthorize.py", "/lib/chatbot/reaction/reactionDownloadPhoto.py", "/lib/chatbot/reaction/reactionEnd.py", "/lib/chatbot/reaction/reactionCommandUnknown.py", "/lib/chatbot/reaction/reactionRecognize.py", "/lib/chatbot/reaction/reactionTrainModel.py"], "/lib/camera/camera_test.py": ["/lib/camera/drawer.py"], "/lib/chatbot/reaction/reactionRecognize.py": ["/lib/chatbot/reaction/reactionBase.py"], "/lib/chatbot/reaction/reactionAuthorize.py": ["/lib/chatbot/reaction/reactionBase.py"], "/lib/chatbot/reaction/reactionStart.py": ["/lib/chatbot/reaction/reactionBase.py"], "/lib/chatbot/reaction/reactionDownloadPhoto.py": ["/lib/chatbot/reaction/reactionBase.py", "/lib/utils/helpers.py"], "/main.py": ["/lib/utils/startup_manager.py"], "/lib/utils/startup_manager.py": ["/lib/manager.py", "/lib/chatbot/telegramBot.py", "/lib/storage/localStorage.py"], "/lib/chatbot/state/conversationState.py": ["/lib/chatbot/telegramObject.py", "/lib/utils/helpers.py"], "/lib/chatbot/state/stateAwait.py": ["/lib/chatbot/state/conversationState.py", "/lib/chatbot/state/stateRecognize.py", "/lib/chatbot/state/stateAddPhoto.py"], "/lib/facerec/recognize.py": ["/lib/facerec/encode.py"], "/tests/testReactionFactory.py": ["/lib/utils/startup_manager.py", "/lib/chatbot/reaction/reactionFactory.py", "/lib/chatbot/reaction/reactionDefault.py", "/lib/chatbot/reaction/reactionStart.py", "/lib/chatbot/reaction/reactionAuthorize.py", "/lib/chatbot/reaction/reactionDownloadPhoto.py", "/lib/chatbot/reaction/reactionEnd.py", "/lib/chatbot/reaction/reactionCommandUnknown.py", "/lib/chatbot/reaction/reactionRecognize.py", "/lib/chatbot/reaction/reactionTrainModel.py"], "/lib/chatbot/state/stateUnknownInput.py": ["/lib/chatbot/state/conversationState.py"], "/lib/chatbot/state/UpdateParser.py": ["/lib/utils/user.py"], "/lib/chatbot/state/conversationContext.py": ["/lib/chatbot/state/stateAwait.py", "/lib/chatbot/state/stateRecognize.py", "/lib/chatbot/state/stateAddPhoto.py"], "/lib/storage/localStorage.py": ["/lib/storage/interface.py"], "/lib/chatbot/state/stateRecognize.py": ["/lib/chatbot/state/conversationState.py"], "/lib/chatbot/state/stateAddPhoto.py": ["/lib/chatbot/state/conversationState.py"], "/lib/facerec/tests/testEncoder.py": ["/lib/facerec/encode.py"], "/lib/chatbot/telegramBot.py": ["/lib/chatbot/interface.py", "/lib/chatbot/state/UpdateParser.py"], "/tests/testUpdatesHandler.py": ["/lib/utils/user.py"], "/lib/facerec/api.py": ["/lib/facerec/recognize.py"], "/lib/facerec/tests/testRecognizer.py": ["/lib/facerec/recognize.py", "/lib/facerec/encode.py"]}
|
22,913,437
|
bevzzz/bouncer
|
refs/heads/master
|
/lib/chatbot/chat.py
|
class Chat:
_instance = {}
def __init__(self, chat_id):
self.messages = {}
self.state = None
self._instance[chat_id] = self
@classmethod
def get_instance(cls, chat_id):
if chat_id in cls._instance:
return cls._instance[chat_id]
else:
cls(chat_id)
def add_message(self, message):
self.messages = {
message.get_id(): message
}
# TODO: change state according to the message
def get_state(self):
return self.state
|
{"/lib/chatbot/reaction/reactionTrainModel.py": ["/lib/chatbot/reaction/reactionBase.py"], "/lib/chatbot/reaction/reactionCommandUnknown.py": ["/lib/chatbot/reaction/reactionBase.py"], "/lib/chatbot/reaction/reactionEnd.py": ["/lib/chatbot/reaction/reactionBase.py"], "/lib/facerec/recognition.py": ["/lib/utils/helpers.py", "/lib/facerec/model.py", "/lib/storage/localStorage.py"], "/lib/manager.py": ["/lib/chatbot/reaction/reactionFactory.py", "/lib/chatbot/conversation.py", "/lib/chatbot/state/conversationContext.py", "/lib/chatbot/state/UpdateParser.py"], "/lib/chatbot/reaction/reactionDefault.py": ["/lib/chatbot/reaction/reactionBase.py"], "/lib/chatbot/reaction/reactionBase.py": ["/lib/chatbot/telegramObject.py"], "/lib/chatbot/reaction/reactionFactory.py": ["/lib/chatbot/conversation.py", "/lib/chatbot/reaction/reactionDefault.py", "/lib/chatbot/reaction/reactionStart.py", "/lib/chatbot/reaction/reactionAuthorize.py", "/lib/chatbot/reaction/reactionDownloadPhoto.py", "/lib/chatbot/reaction/reactionEnd.py", "/lib/chatbot/reaction/reactionCommandUnknown.py", "/lib/chatbot/reaction/reactionRecognize.py", "/lib/chatbot/reaction/reactionTrainModel.py"], "/lib/camera/camera_test.py": ["/lib/camera/drawer.py"], "/lib/chatbot/reaction/reactionRecognize.py": ["/lib/chatbot/reaction/reactionBase.py"], "/lib/chatbot/reaction/reactionAuthorize.py": ["/lib/chatbot/reaction/reactionBase.py"], "/lib/chatbot/reaction/reactionStart.py": ["/lib/chatbot/reaction/reactionBase.py"], "/lib/chatbot/reaction/reactionDownloadPhoto.py": ["/lib/chatbot/reaction/reactionBase.py", "/lib/utils/helpers.py"], "/main.py": ["/lib/utils/startup_manager.py"], "/lib/utils/startup_manager.py": ["/lib/manager.py", "/lib/chatbot/telegramBot.py", "/lib/storage/localStorage.py"], "/lib/chatbot/state/conversationState.py": ["/lib/chatbot/telegramObject.py", "/lib/utils/helpers.py"], "/lib/chatbot/state/stateAwait.py": ["/lib/chatbot/state/conversationState.py", "/lib/chatbot/state/stateRecognize.py", "/lib/chatbot/state/stateAddPhoto.py"], "/lib/facerec/recognize.py": ["/lib/facerec/encode.py"], "/tests/testReactionFactory.py": ["/lib/utils/startup_manager.py", "/lib/chatbot/reaction/reactionFactory.py", "/lib/chatbot/reaction/reactionDefault.py", "/lib/chatbot/reaction/reactionStart.py", "/lib/chatbot/reaction/reactionAuthorize.py", "/lib/chatbot/reaction/reactionDownloadPhoto.py", "/lib/chatbot/reaction/reactionEnd.py", "/lib/chatbot/reaction/reactionCommandUnknown.py", "/lib/chatbot/reaction/reactionRecognize.py", "/lib/chatbot/reaction/reactionTrainModel.py"], "/lib/chatbot/state/stateUnknownInput.py": ["/lib/chatbot/state/conversationState.py"], "/lib/chatbot/state/UpdateParser.py": ["/lib/utils/user.py"], "/lib/chatbot/state/conversationContext.py": ["/lib/chatbot/state/stateAwait.py", "/lib/chatbot/state/stateRecognize.py", "/lib/chatbot/state/stateAddPhoto.py"], "/lib/storage/localStorage.py": ["/lib/storage/interface.py"], "/lib/chatbot/state/stateRecognize.py": ["/lib/chatbot/state/conversationState.py"], "/lib/chatbot/state/stateAddPhoto.py": ["/lib/chatbot/state/conversationState.py"], "/lib/facerec/tests/testEncoder.py": ["/lib/facerec/encode.py"], "/lib/chatbot/telegramBot.py": ["/lib/chatbot/interface.py", "/lib/chatbot/state/UpdateParser.py"], "/tests/testUpdatesHandler.py": ["/lib/utils/user.py"], "/lib/facerec/api.py": ["/lib/facerec/recognize.py"], "/lib/facerec/tests/testRecognizer.py": ["/lib/facerec/recognize.py", "/lib/facerec/encode.py"]}
|
22,913,438
|
bevzzz/bouncer
|
refs/heads/master
|
/lib/manager.py
|
from lib.chatbot.state.conversationContext import ConversationContext
from lib.chatbot.state.UpdateParser import UpdateParser
import logging
import time
import base64
import requests
class Manager:
def __init__(self, chatbot, storage):
self.chatbot = chatbot
self.storage = storage
self.conversations = []
self.log = logging.getLogger()
def talk(self):
self.log.info("start talk()")
while True:
updates = self.chatbot.get_updates()
for update in updates:
try:
update = UpdateParser.factory(update)
self.log.info(
f"new message from {update.get_author().get_username()}"
)
conversation = ConversationContext.open(self, update)
conversation.reply()
except LookupError as err:
self.log.warning(err)
self.chatbot.update_offset()
def update_message(self, chat_id, to_delete_id, to_send):
self.chatbot.delete_message(
chat_id=chat_id,
message_id=to_delete_id
)
return self.chatbot.send_message(to_send)
def get_user_roles(self):
self.storage.set_root_path('')
user_roles = self.storage.read_json('config', 'users.json')
self.storage.set_root_path('images')
return user_roles
def is_authorized_user(self, user):
user_roles = self.get_user_roles()
return user.get_username() in list(user_roles.keys())
def is_admin(self, user):
user_roles = self.get_user_roles()
return user_roles[user.get_username()] == 'admin'
@staticmethod
def send_request_to_recognize(img):
base_url = 'http://localhost:5000/bouncer/v1/model/recognize'
img = base64.encodebytes(img).decode('utf-8')
body_json = {
'img': img
}
response = requests.post(url=base_url, json=body_json)
return response.json()
def send_request_to_train(self, people=None):
# TODO: probably I should use facerec:5000 when running this from docker-compose
base_url = 'http://localhost:5000/bouncer/v1/model/train'
if people is None:
people = self.get_user_roles()
people = list(people.keys())
body_json = {
'people': people
}
response = requests.post(url=base_url, json=body_json)
return response.json()
|
{"/lib/chatbot/reaction/reactionTrainModel.py": ["/lib/chatbot/reaction/reactionBase.py"], "/lib/chatbot/reaction/reactionCommandUnknown.py": ["/lib/chatbot/reaction/reactionBase.py"], "/lib/chatbot/reaction/reactionEnd.py": ["/lib/chatbot/reaction/reactionBase.py"], "/lib/facerec/recognition.py": ["/lib/utils/helpers.py", "/lib/facerec/model.py", "/lib/storage/localStorage.py"], "/lib/manager.py": ["/lib/chatbot/reaction/reactionFactory.py", "/lib/chatbot/conversation.py", "/lib/chatbot/state/conversationContext.py", "/lib/chatbot/state/UpdateParser.py"], "/lib/chatbot/reaction/reactionDefault.py": ["/lib/chatbot/reaction/reactionBase.py"], "/lib/chatbot/reaction/reactionBase.py": ["/lib/chatbot/telegramObject.py"], "/lib/chatbot/reaction/reactionFactory.py": ["/lib/chatbot/conversation.py", "/lib/chatbot/reaction/reactionDefault.py", "/lib/chatbot/reaction/reactionStart.py", "/lib/chatbot/reaction/reactionAuthorize.py", "/lib/chatbot/reaction/reactionDownloadPhoto.py", "/lib/chatbot/reaction/reactionEnd.py", "/lib/chatbot/reaction/reactionCommandUnknown.py", "/lib/chatbot/reaction/reactionRecognize.py", "/lib/chatbot/reaction/reactionTrainModel.py"], "/lib/camera/camera_test.py": ["/lib/camera/drawer.py"], "/lib/chatbot/reaction/reactionRecognize.py": ["/lib/chatbot/reaction/reactionBase.py"], "/lib/chatbot/reaction/reactionAuthorize.py": ["/lib/chatbot/reaction/reactionBase.py"], "/lib/chatbot/reaction/reactionStart.py": ["/lib/chatbot/reaction/reactionBase.py"], "/lib/chatbot/reaction/reactionDownloadPhoto.py": ["/lib/chatbot/reaction/reactionBase.py", "/lib/utils/helpers.py"], "/main.py": ["/lib/utils/startup_manager.py"], "/lib/utils/startup_manager.py": ["/lib/manager.py", "/lib/chatbot/telegramBot.py", "/lib/storage/localStorage.py"], "/lib/chatbot/state/conversationState.py": ["/lib/chatbot/telegramObject.py", "/lib/utils/helpers.py"], "/lib/chatbot/state/stateAwait.py": ["/lib/chatbot/state/conversationState.py", "/lib/chatbot/state/stateRecognize.py", "/lib/chatbot/state/stateAddPhoto.py"], "/lib/facerec/recognize.py": ["/lib/facerec/encode.py"], "/tests/testReactionFactory.py": ["/lib/utils/startup_manager.py", "/lib/chatbot/reaction/reactionFactory.py", "/lib/chatbot/reaction/reactionDefault.py", "/lib/chatbot/reaction/reactionStart.py", "/lib/chatbot/reaction/reactionAuthorize.py", "/lib/chatbot/reaction/reactionDownloadPhoto.py", "/lib/chatbot/reaction/reactionEnd.py", "/lib/chatbot/reaction/reactionCommandUnknown.py", "/lib/chatbot/reaction/reactionRecognize.py", "/lib/chatbot/reaction/reactionTrainModel.py"], "/lib/chatbot/state/stateUnknownInput.py": ["/lib/chatbot/state/conversationState.py"], "/lib/chatbot/state/UpdateParser.py": ["/lib/utils/user.py"], "/lib/chatbot/state/conversationContext.py": ["/lib/chatbot/state/stateAwait.py", "/lib/chatbot/state/stateRecognize.py", "/lib/chatbot/state/stateAddPhoto.py"], "/lib/storage/localStorage.py": ["/lib/storage/interface.py"], "/lib/chatbot/state/stateRecognize.py": ["/lib/chatbot/state/conversationState.py"], "/lib/chatbot/state/stateAddPhoto.py": ["/lib/chatbot/state/conversationState.py"], "/lib/facerec/tests/testEncoder.py": ["/lib/facerec/encode.py"], "/lib/chatbot/telegramBot.py": ["/lib/chatbot/interface.py", "/lib/chatbot/state/UpdateParser.py"], "/tests/testUpdatesHandler.py": ["/lib/utils/user.py"], "/lib/facerec/api.py": ["/lib/facerec/recognize.py"], "/lib/facerec/tests/testRecognizer.py": ["/lib/facerec/recognize.py", "/lib/facerec/encode.py"]}
|
22,913,439
|
bevzzz/bouncer
|
refs/heads/master
|
/lib/facerec/api.py
|
# Third-party
import flask as f
import flask_restx as fx
from werkzeug.datastructures import FileStorage
# Local libraries
from lib.facerec.recognize import Recognizer
# Define the RestX API instance
app = f.Flask(__name__)
api = fx.Api(
app=app,
version="1.0",
title="Facerec",
description="Recognize faces"
)
# Define namespaces for the API
ns = api.namespace("facerec")
# Set up request parsing
parser = fx.reqparse.RequestParser()
parser.add_argument(
"file",
location='files',
type=FileStorage,
required=True
)
# Create dependencies
recognizer = Recognizer()
print("WORKING")
# Define endpoint
@ns.route("/recognize")
class RecognizeEndpoint(fx.Resource):
def get(self):
return {"healthcheck": "I'm good"}
@ns.expect(parser)
def post(self):
args = parser.parse_args()
uploaded_file = args["file"]
img_bytes = uploaded_file.stream.read()
person = recognizer.recognize(img_bytes)
return person, 200
|
{"/lib/chatbot/reaction/reactionTrainModel.py": ["/lib/chatbot/reaction/reactionBase.py"], "/lib/chatbot/reaction/reactionCommandUnknown.py": ["/lib/chatbot/reaction/reactionBase.py"], "/lib/chatbot/reaction/reactionEnd.py": ["/lib/chatbot/reaction/reactionBase.py"], "/lib/facerec/recognition.py": ["/lib/utils/helpers.py", "/lib/facerec/model.py", "/lib/storage/localStorage.py"], "/lib/manager.py": ["/lib/chatbot/reaction/reactionFactory.py", "/lib/chatbot/conversation.py", "/lib/chatbot/state/conversationContext.py", "/lib/chatbot/state/UpdateParser.py"], "/lib/chatbot/reaction/reactionDefault.py": ["/lib/chatbot/reaction/reactionBase.py"], "/lib/chatbot/reaction/reactionBase.py": ["/lib/chatbot/telegramObject.py"], "/lib/chatbot/reaction/reactionFactory.py": ["/lib/chatbot/conversation.py", "/lib/chatbot/reaction/reactionDefault.py", "/lib/chatbot/reaction/reactionStart.py", "/lib/chatbot/reaction/reactionAuthorize.py", "/lib/chatbot/reaction/reactionDownloadPhoto.py", "/lib/chatbot/reaction/reactionEnd.py", "/lib/chatbot/reaction/reactionCommandUnknown.py", "/lib/chatbot/reaction/reactionRecognize.py", "/lib/chatbot/reaction/reactionTrainModel.py"], "/lib/camera/camera_test.py": ["/lib/camera/drawer.py"], "/lib/chatbot/reaction/reactionRecognize.py": ["/lib/chatbot/reaction/reactionBase.py"], "/lib/chatbot/reaction/reactionAuthorize.py": ["/lib/chatbot/reaction/reactionBase.py"], "/lib/chatbot/reaction/reactionStart.py": ["/lib/chatbot/reaction/reactionBase.py"], "/lib/chatbot/reaction/reactionDownloadPhoto.py": ["/lib/chatbot/reaction/reactionBase.py", "/lib/utils/helpers.py"], "/main.py": ["/lib/utils/startup_manager.py"], "/lib/utils/startup_manager.py": ["/lib/manager.py", "/lib/chatbot/telegramBot.py", "/lib/storage/localStorage.py"], "/lib/chatbot/state/conversationState.py": ["/lib/chatbot/telegramObject.py", "/lib/utils/helpers.py"], "/lib/chatbot/state/stateAwait.py": ["/lib/chatbot/state/conversationState.py", "/lib/chatbot/state/stateRecognize.py", "/lib/chatbot/state/stateAddPhoto.py"], "/lib/facerec/recognize.py": ["/lib/facerec/encode.py"], "/tests/testReactionFactory.py": ["/lib/utils/startup_manager.py", "/lib/chatbot/reaction/reactionFactory.py", "/lib/chatbot/reaction/reactionDefault.py", "/lib/chatbot/reaction/reactionStart.py", "/lib/chatbot/reaction/reactionAuthorize.py", "/lib/chatbot/reaction/reactionDownloadPhoto.py", "/lib/chatbot/reaction/reactionEnd.py", "/lib/chatbot/reaction/reactionCommandUnknown.py", "/lib/chatbot/reaction/reactionRecognize.py", "/lib/chatbot/reaction/reactionTrainModel.py"], "/lib/chatbot/state/stateUnknownInput.py": ["/lib/chatbot/state/conversationState.py"], "/lib/chatbot/state/UpdateParser.py": ["/lib/utils/user.py"], "/lib/chatbot/state/conversationContext.py": ["/lib/chatbot/state/stateAwait.py", "/lib/chatbot/state/stateRecognize.py", "/lib/chatbot/state/stateAddPhoto.py"], "/lib/storage/localStorage.py": ["/lib/storage/interface.py"], "/lib/chatbot/state/stateRecognize.py": ["/lib/chatbot/state/conversationState.py"], "/lib/chatbot/state/stateAddPhoto.py": ["/lib/chatbot/state/conversationState.py"], "/lib/facerec/tests/testEncoder.py": ["/lib/facerec/encode.py"], "/lib/chatbot/telegramBot.py": ["/lib/chatbot/interface.py", "/lib/chatbot/state/UpdateParser.py"], "/tests/testUpdatesHandler.py": ["/lib/utils/user.py"], "/lib/facerec/api.py": ["/lib/facerec/recognize.py"], "/lib/facerec/tests/testRecognizer.py": ["/lib/facerec/recognize.py", "/lib/facerec/encode.py"]}
|
22,913,440
|
bevzzz/bouncer
|
refs/heads/master
|
/lib/facerec/tests/testRecognizer.py
|
import unittest
import numpy as np
from PIL import Image
from lib.facerec.recognize import Recognizer
from lib.facerec.encode import Encoder
class TestRecognizer(unittest.TestCase):
test_img_path = "/lib/facerec/tests/bin/dannydevito.png"
@classmethod
def setUpClass(cls):
cls.r = Recognizer()
def tearDown(self):
self.r.set_known({"names": None, "encodings": None})
def get_encodings(self, name, path=""):
e = Encoder()
imgb = self.get_bytes_image(path)
arr = self.r._prepare_for_encoding(imgb)
enc = e.encode(arr)
return name, enc
def get_known_list(self, ntrue=1, nfalse=1):
nd, encd = self.get_encodings("Danny Devito")
na, enca = self.get_encodings("Arnold", "/lib/facerec/tests/bin/schwarz.jpg")
names = [nd]*ntrue + [na]*nfalse
encodings = encd*ntrue + enca*nfalse
return {"encodings": encodings, "names": names}
def get_bytes_image(self, path=""):
if path == "":
path = self.test_img_path
with open(path, 'rb') as b:
return b.read()
def get_pil_image(self):
return Image.open(self.test_img_path)
def test_convert_PIL_image_to_array(self):
# arrange
img = self.get_pil_image()
# act
got = self.r._convert_pil_to_array(img)
# assert
self.assertIsInstance(got, np.ndarray)
def test_convert_bytes_to_pil(self):
# arrange
imgb = self.get_bytes_image()
# act
img = self.r._convert_bytes_to_pil(imgb)
# assert
self.assertIsInstance(img, Image.Image)
def test_is_RGB(self):
# arrange
img_not_rgb = self.get_pil_image()
img_rgb = img_not_rgb
# act
img_rgb = img_rgb.convert("RGB")
# assert
self.assertTrue(self.r._is_rgb(img_rgb))
self.assertFalse(self.r._is_rgb(img_not_rgb))
def test_prepare_for_encoding(self):
# arrange
imgb = self.get_bytes_image()
# act
arr = self.r._prepare_for_encoding(imgb)
# assert
self.assertIsInstance(arr, np.ndarray)
def test_set_encodings(self):
# arrange
enc = self.get_known_list()
# act
self.r.set_known(enc)
# assert
self.assertIsNotNone(self.r._encodings)
def test_finds_a_match(self):
# arrange
imgb = self.get_bytes_image()
arr = self.r._prepare_for_encoding(imgb)
e = Encoder()
encoded_img = e.encode(arr)
known_encodings = self.get_known_list()
self.r.set_known(known_encodings)
# act
matched = self.r._find_matches(encoded_img[0])
# assert
self.assertTrue(matched[0])
def test_determines_match(self):
# arrange
matches = [True, True, True, False, False, True, False, False, False, False]
known_encodings = self.get_known_list(ntrue=4, nfalse=6)
self.r.set_known(known_encodings)
# act
person = self.r._determine_the_match(matches)
# assert
self.assertEqual(person, "Danny Devito")
def test_recognize_returns_none_if_none_known(self):
# arrange
imgb = self.get_bytes_image()
# act
person = self.r.recognize(imgb)
# assert
self.assertIsNone(person)
# def test_recognizes_danny(self):
# # arrange
# imgb = self.get_bytes_image()
# known_encodings = self.get_known_list()
# self.r.set_known(known_encodings)
# # act
# person = self.r.recognize(imgb)
# # assert
# self.assertEqual(person, "Danny Devito")
|
{"/lib/chatbot/reaction/reactionTrainModel.py": ["/lib/chatbot/reaction/reactionBase.py"], "/lib/chatbot/reaction/reactionCommandUnknown.py": ["/lib/chatbot/reaction/reactionBase.py"], "/lib/chatbot/reaction/reactionEnd.py": ["/lib/chatbot/reaction/reactionBase.py"], "/lib/facerec/recognition.py": ["/lib/utils/helpers.py", "/lib/facerec/model.py", "/lib/storage/localStorage.py"], "/lib/manager.py": ["/lib/chatbot/reaction/reactionFactory.py", "/lib/chatbot/conversation.py", "/lib/chatbot/state/conversationContext.py", "/lib/chatbot/state/UpdateParser.py"], "/lib/chatbot/reaction/reactionDefault.py": ["/lib/chatbot/reaction/reactionBase.py"], "/lib/chatbot/reaction/reactionBase.py": ["/lib/chatbot/telegramObject.py"], "/lib/chatbot/reaction/reactionFactory.py": ["/lib/chatbot/conversation.py", "/lib/chatbot/reaction/reactionDefault.py", "/lib/chatbot/reaction/reactionStart.py", "/lib/chatbot/reaction/reactionAuthorize.py", "/lib/chatbot/reaction/reactionDownloadPhoto.py", "/lib/chatbot/reaction/reactionEnd.py", "/lib/chatbot/reaction/reactionCommandUnknown.py", "/lib/chatbot/reaction/reactionRecognize.py", "/lib/chatbot/reaction/reactionTrainModel.py"], "/lib/camera/camera_test.py": ["/lib/camera/drawer.py"], "/lib/chatbot/reaction/reactionRecognize.py": ["/lib/chatbot/reaction/reactionBase.py"], "/lib/chatbot/reaction/reactionAuthorize.py": ["/lib/chatbot/reaction/reactionBase.py"], "/lib/chatbot/reaction/reactionStart.py": ["/lib/chatbot/reaction/reactionBase.py"], "/lib/chatbot/reaction/reactionDownloadPhoto.py": ["/lib/chatbot/reaction/reactionBase.py", "/lib/utils/helpers.py"], "/main.py": ["/lib/utils/startup_manager.py"], "/lib/utils/startup_manager.py": ["/lib/manager.py", "/lib/chatbot/telegramBot.py", "/lib/storage/localStorage.py"], "/lib/chatbot/state/conversationState.py": ["/lib/chatbot/telegramObject.py", "/lib/utils/helpers.py"], "/lib/chatbot/state/stateAwait.py": ["/lib/chatbot/state/conversationState.py", "/lib/chatbot/state/stateRecognize.py", "/lib/chatbot/state/stateAddPhoto.py"], "/lib/facerec/recognize.py": ["/lib/facerec/encode.py"], "/tests/testReactionFactory.py": ["/lib/utils/startup_manager.py", "/lib/chatbot/reaction/reactionFactory.py", "/lib/chatbot/reaction/reactionDefault.py", "/lib/chatbot/reaction/reactionStart.py", "/lib/chatbot/reaction/reactionAuthorize.py", "/lib/chatbot/reaction/reactionDownloadPhoto.py", "/lib/chatbot/reaction/reactionEnd.py", "/lib/chatbot/reaction/reactionCommandUnknown.py", "/lib/chatbot/reaction/reactionRecognize.py", "/lib/chatbot/reaction/reactionTrainModel.py"], "/lib/chatbot/state/stateUnknownInput.py": ["/lib/chatbot/state/conversationState.py"], "/lib/chatbot/state/UpdateParser.py": ["/lib/utils/user.py"], "/lib/chatbot/state/conversationContext.py": ["/lib/chatbot/state/stateAwait.py", "/lib/chatbot/state/stateRecognize.py", "/lib/chatbot/state/stateAddPhoto.py"], "/lib/storage/localStorage.py": ["/lib/storage/interface.py"], "/lib/chatbot/state/stateRecognize.py": ["/lib/chatbot/state/conversationState.py"], "/lib/chatbot/state/stateAddPhoto.py": ["/lib/chatbot/state/conversationState.py"], "/lib/facerec/tests/testEncoder.py": ["/lib/facerec/encode.py"], "/lib/chatbot/telegramBot.py": ["/lib/chatbot/interface.py", "/lib/chatbot/state/UpdateParser.py"], "/tests/testUpdatesHandler.py": ["/lib/utils/user.py"], "/lib/facerec/api.py": ["/lib/facerec/recognize.py"], "/lib/facerec/tests/testRecognizer.py": ["/lib/facerec/recognize.py", "/lib/facerec/encode.py"]}
|
22,913,441
|
bevzzz/bouncer
|
refs/heads/master
|
/lib/storage/interface.py
|
from abc import ABCMeta, abstractmethod
import logging
class Storage(metaclass=ABCMeta):
def __init__(self):
self.log = logging.getLogger("Storage")
@abstractmethod
def write_image(self, img, name, to_dir):
pass
@abstractmethod
def read_image(self, name, from_dir):
pass
@abstractmethod
def create_directory(self, name):
pass
@abstractmethod
def list_directory(self, name=None):
pass
def exists_directory(self, my_dir):
all_dirs = self.list_directory()
return any(f == my_dir for f in all_dirs)
|
{"/lib/chatbot/reaction/reactionTrainModel.py": ["/lib/chatbot/reaction/reactionBase.py"], "/lib/chatbot/reaction/reactionCommandUnknown.py": ["/lib/chatbot/reaction/reactionBase.py"], "/lib/chatbot/reaction/reactionEnd.py": ["/lib/chatbot/reaction/reactionBase.py"], "/lib/facerec/recognition.py": ["/lib/utils/helpers.py", "/lib/facerec/model.py", "/lib/storage/localStorage.py"], "/lib/manager.py": ["/lib/chatbot/reaction/reactionFactory.py", "/lib/chatbot/conversation.py", "/lib/chatbot/state/conversationContext.py", "/lib/chatbot/state/UpdateParser.py"], "/lib/chatbot/reaction/reactionDefault.py": ["/lib/chatbot/reaction/reactionBase.py"], "/lib/chatbot/reaction/reactionBase.py": ["/lib/chatbot/telegramObject.py"], "/lib/chatbot/reaction/reactionFactory.py": ["/lib/chatbot/conversation.py", "/lib/chatbot/reaction/reactionDefault.py", "/lib/chatbot/reaction/reactionStart.py", "/lib/chatbot/reaction/reactionAuthorize.py", "/lib/chatbot/reaction/reactionDownloadPhoto.py", "/lib/chatbot/reaction/reactionEnd.py", "/lib/chatbot/reaction/reactionCommandUnknown.py", "/lib/chatbot/reaction/reactionRecognize.py", "/lib/chatbot/reaction/reactionTrainModel.py"], "/lib/camera/camera_test.py": ["/lib/camera/drawer.py"], "/lib/chatbot/reaction/reactionRecognize.py": ["/lib/chatbot/reaction/reactionBase.py"], "/lib/chatbot/reaction/reactionAuthorize.py": ["/lib/chatbot/reaction/reactionBase.py"], "/lib/chatbot/reaction/reactionStart.py": ["/lib/chatbot/reaction/reactionBase.py"], "/lib/chatbot/reaction/reactionDownloadPhoto.py": ["/lib/chatbot/reaction/reactionBase.py", "/lib/utils/helpers.py"], "/main.py": ["/lib/utils/startup_manager.py"], "/lib/utils/startup_manager.py": ["/lib/manager.py", "/lib/chatbot/telegramBot.py", "/lib/storage/localStorage.py"], "/lib/chatbot/state/conversationState.py": ["/lib/chatbot/telegramObject.py", "/lib/utils/helpers.py"], "/lib/chatbot/state/stateAwait.py": ["/lib/chatbot/state/conversationState.py", "/lib/chatbot/state/stateRecognize.py", "/lib/chatbot/state/stateAddPhoto.py"], "/lib/facerec/recognize.py": ["/lib/facerec/encode.py"], "/tests/testReactionFactory.py": ["/lib/utils/startup_manager.py", "/lib/chatbot/reaction/reactionFactory.py", "/lib/chatbot/reaction/reactionDefault.py", "/lib/chatbot/reaction/reactionStart.py", "/lib/chatbot/reaction/reactionAuthorize.py", "/lib/chatbot/reaction/reactionDownloadPhoto.py", "/lib/chatbot/reaction/reactionEnd.py", "/lib/chatbot/reaction/reactionCommandUnknown.py", "/lib/chatbot/reaction/reactionRecognize.py", "/lib/chatbot/reaction/reactionTrainModel.py"], "/lib/chatbot/state/stateUnknownInput.py": ["/lib/chatbot/state/conversationState.py"], "/lib/chatbot/state/UpdateParser.py": ["/lib/utils/user.py"], "/lib/chatbot/state/conversationContext.py": ["/lib/chatbot/state/stateAwait.py", "/lib/chatbot/state/stateRecognize.py", "/lib/chatbot/state/stateAddPhoto.py"], "/lib/storage/localStorage.py": ["/lib/storage/interface.py"], "/lib/chatbot/state/stateRecognize.py": ["/lib/chatbot/state/conversationState.py"], "/lib/chatbot/state/stateAddPhoto.py": ["/lib/chatbot/state/conversationState.py"], "/lib/facerec/tests/testEncoder.py": ["/lib/facerec/encode.py"], "/lib/chatbot/telegramBot.py": ["/lib/chatbot/interface.py", "/lib/chatbot/state/UpdateParser.py"], "/tests/testUpdatesHandler.py": ["/lib/utils/user.py"], "/lib/facerec/api.py": ["/lib/facerec/recognize.py"], "/lib/facerec/tests/testRecognizer.py": ["/lib/facerec/recognize.py", "/lib/facerec/encode.py"]}
|
22,992,119
|
creativechern/django-blog
|
refs/heads/main
|
/blog/urls.py
|
from django.urls import path, include
from . import views
urlpatterns = [
path('', views.BlogListView.as_view(), name="home"),
path('about/', views.AboutView.as_view(), name="about"),
path('contact/', views.ContactView.as_view(), name="contact"),
path('post/<int:pk>/', views.BlogDetailView.as_view(), name="post_detail"),
path('post/new/', views.BlogCreateView.as_view(), name="post_new"),
]
|
{"/users/forms.py": ["/users/models.py"], "/blog/views.py": ["/blog/models.py"], "/users/urls.py": ["/users/forms.py"]}
|
22,992,120
|
creativechern/django-blog
|
refs/heads/main
|
/users/forms.py
|
# users/forms.py
from django import forms
from django.contrib.auth.forms import UserCreationForm, UserChangeForm, AuthenticationForm
from .models import CustomUser
class CustomUserCreationForm(UserCreationForm):
YEARS= [x for x in range(2021,1900,-1)]
date_of_birth = forms.DateField(widget=forms.SelectDateWidget(years=YEARS))
class Meta(UserCreationForm):
model = CustomUser
fields = UserCreationForm.Meta.fields + ('email','date_of_birth')
class CustomUserChangeForm(UserChangeForm):
class Meta:
model = CustomUser
fields = UserChangeForm.Meta.fields
#https://stackoverflow.com/questions/55369645/how-to-customize-default-auth-login-form-in-django
class UserLoginForm(AuthenticationForm):
def __init__(self, *args, **kwargs):
super(UserLoginForm, self).__init__(*args, **kwargs)
username = forms.CharField(widget=forms.TextInput(
attrs={'class': 'form-control', 'placeholder': ''}))
# attrs={'class': 'form-control', 'placeholder': '', 'id': 'hello'}))
password = forms.CharField(widget=forms.PasswordInput(
attrs={
'class': 'form-control',
'placeholder': '',
# 'id': 'hi',
}
))
|
{"/users/forms.py": ["/users/models.py"], "/blog/views.py": ["/blog/models.py"], "/users/urls.py": ["/users/forms.py"]}
|
22,992,121
|
creativechern/django-blog
|
refs/heads/main
|
/users/models.py
|
from django.contrib.auth.models import AbstractUser
from django.db import models
# Create your models here.
class CustomUser(AbstractUser):
date_of_birth = models.DateField(blank=True, null=True)
|
{"/users/forms.py": ["/users/models.py"], "/blog/views.py": ["/blog/models.py"], "/users/urls.py": ["/users/forms.py"]}
|
22,992,122
|
creativechern/django-blog
|
refs/heads/main
|
/blog/views.py
|
from django.shortcuts import render
from django.views.generic import TemplateView, ListView, DetailView
from django.views.generic.edit import CreateView
from django.contrib.auth.mixins import LoginRequiredMixin
from .models import Post
from .forms import PostForm
class BlogListView(ListView):
model = Post
context_object_name = "all_post_list"
template_name = "blog/index.html"
class AboutView(TemplateView):
template_name = "blog/about.html"
class ContactView(TemplateView):
template_name = "blog/contact.html"
class BlogDetailView(DetailView):
model = Post
template_name = "blog/post_detail.html"
class BlogCreateView(LoginRequiredMixin, CreateView):
model = Post
template_name = "blog/create.html"
# fields = ['title', 'body']
form_class = PostForm
login_url = 'login'
def form_valid(self, form):
form.instance.author = self.request.user
return super().form_valid(form)
|
{"/users/forms.py": ["/users/models.py"], "/blog/views.py": ["/blog/models.py"], "/users/urls.py": ["/users/forms.py"]}
|
22,992,123
|
creativechern/django-blog
|
refs/heads/main
|
/users/urls.py
|
from django.urls import path
from django.contrib.auth.views import LoginView
from users.forms import UserLoginForm
from .views import SignUpView
urlpatterns = [
path('signup/', SignUpView.as_view(), name='signup'),
#https://stackoverflow.com/questions/55369645/how-to-customize-default-auth-login-form-in-django
path('login/', LoginView.as_view(authentication_form=UserLoginForm), name='login'),
]
|
{"/users/forms.py": ["/users/models.py"], "/blog/views.py": ["/blog/models.py"], "/users/urls.py": ["/users/forms.py"]}
|
22,992,124
|
creativechern/django-blog
|
refs/heads/main
|
/blog/models.py
|
from django.db import models
from django.urls import reverse
from django.conf import settings
from ckeditor.fields import RichTextField
class Post(models.Model):
title = models.CharField(max_length = 250)
author = models.ForeignKey(
settings.AUTH_USER_MODEL,
on_delete = models.CASCADE,
)
#body = models.TextField()
body = RichTextField(blank=True, null=True)
created = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse("post_detail", kwargs={"pk": self.pk})
|
{"/users/forms.py": ["/users/models.py"], "/blog/views.py": ["/blog/models.py"], "/users/urls.py": ["/users/forms.py"]}
|
23,003,951
|
eirrgang/radical.pilot
|
refs/heads/master
|
/examples/misc/task_overlay_worker.py
|
#!/usr/bin/env python3
import sys
import time
import radical.utils as ru
import radical.pilot as rp
# ------------------------------------------------------------------------------
#
class MyWorker(rp.task_overlay.Worker):
'''
This class provides the required functionality to execute work requests.
In this simple example, the worker only implements a single call: `hello`.
'''
# --------------------------------------------------------------------------
#
def __init__(self, cfg):
# ensure that communication to the pilot agent is up and running, so
# that the worker can respond to management commands (termination).
# This will also read the passed config file and make it available as
# `self._cfg`.
rp.task_overlay.Worker.__init__(self, cfg)
# --------------------------------------------------------------------------
#
def initialize(self):
'''
This method is called during base class construction. All agent
communication channels are available at this point.
We use this point to connect to the request / response ZMQ queues. Note
that incoming requests will trigger an async callback `self.request_cb`.
'''
self._req_get = ru.zmq.Getter('to_req', self._info.req_addr_get,
cb=self.request_cb)
self._res_put = ru.zmq.Putter('to_res', self._info.res_addr_put)
# the worker can return custom information which will be made available
# to the master. This can be used to communicate, for example, worker
# specific communication endpoints.
return {'foo': 'bar'}
# --------------------------------------------------------------------------
#
def request_cb(self, msg):
'''
This implementation only understands a single request type: 'hello'.
It will run that request and immediately return a respone message.
All other requests will immediately trigger an error response.
'''
if msg['call'] == 'hello':
ret = self.hello(*msg['args'], **msg['kwargs'])
res = {'req': msg['uid'],
'res': ret,
'err': None}
self._res_put.put(res)
else:
res = {'req': msg['uid'],
'res': None,
'err': 'no such call %s' % msg['call']}
self._res_put.put(res)
# --------------------------------------------------------------------------
#
def hello(self, world):
'''
important work
'''
return 'hello %s @ %s' % (world, time.time())
# ------------------------------------------------------------------------------
#
if __name__ == '__main__':
# the `info` dict is passed to the worker as config file.
# Create the worker class and run it's work loop.
worker = MyWorker(sys.argv[1])
worker.run()
# ------------------------------------------------------------------------------
|
{"/src/radical/pilot/raptor/master.py": ["/src/radical/pilot/__init__.py"], "/src/radical/pilot/raptor/worker_default.py": ["/src/radical/pilot/raptor/worker.py"], "/src/radical/pilot/task.py": ["/src/radical/pilot/__init__.py", "/src/radical/pilot/staging_directives.py", "/src/radical/pilot/task_description.py"], "/src/radical/pilot/agent/executing/base.py": ["/src/radical/pilot/__init__.py", "/src/radical/pilot/agent/executing/popen.py", "/src/radical/pilot/agent/executing/funcs.py", "/src/radical/pilot/agent/executing/sleep.py"], "/src/radical/pilot/raptor/worker.py": ["/src/radical/pilot/__init__.py", "/src/radical/pilot/raptor/worker_default.py", "/src/radical/pilot/raptor/worker_mpi.py"], "/src/radical/pilot/agent/executing/sleep.py": ["/src/radical/pilot/__init__.py", "/src/radical/pilot/agent/executing/base.py"], "/src/radical/pilot/__init__.py": ["/src/radical/pilot/task.py", "/src/radical/pilot/task_description.py", "/src/radical/pilot/pilot_description.py"], "/src/radical/pilot/agent/executing/funcs.py": ["/src/radical/pilot/__init__.py", "/src/radical/pilot/agent/executing/base.py"], "/src/radical/pilot/agent/executing/popen.py": ["/src/radical/pilot/__init__.py", "/src/radical/pilot/agent/executing/base.py"], "/src/radical/pilot/raptor/worker_mpi.py": ["/src/radical/pilot/raptor/worker.py", "/src/radical/pilot/task_description.py"], "/src/radical/pilot/task_overlay/master.py": ["/src/radical/pilot/__init__.py"], "/src/radical/pilot/task_overlay/worker.py": ["/src/radical/pilot/__init__.py"], "/src/radical/pilot/utils/prof_utils.py": ["/src/radical/pilot/__init__.py", "/src/radical/pilot/utils/session.py"]}
|
23,003,952
|
eirrgang/radical.pilot
|
refs/heads/master
|
/src/radical/pilot/task_overlay/master.py
|
import os
import copy
import time
import radical.utils as ru
from .. import Session, ComputeUnitDescription
from .. import utils as rpu
from .. import states as rps
from .. import constants as rpc
# ------------------------------------------------------------------------------
#
class Master(rpu.Component):
# --------------------------------------------------------------------------
#
def __init__(self, backend='zmq'):
self._backend = backend # FIXME: use
self._lock = ru.Lock('master')
self._workers = dict() # wid: worker
cfg = self._get_config()
session = Session(cfg=cfg, _primary=False)
rpu.Component.__init__(self, cfg, session)
self.register_output(rps.AGENT_STAGING_INPUT_PENDING,
rpc.AGENT_STAGING_INPUT_QUEUE)
self.register_subscriber(rpc.CONTROL_PUBSUB, self._control_cb)
# connect to the local agent
self._log.debug('startup complete')
# --------------------------------------------------------------------------
#
def _get_config(self):
'''
derive a worker base configuration from the control pubsub configuration
'''
# FIXME: this uses insider knowledge on the config location and
# structure. It would be better if agent.0 creates the worker
# base config from scratch on startup.
cfg = ru.read_json('../control_pubsub.json')
del(cfg['channel'])
del(cfg['cmgr'])
cfg['log_lvl'] = 'debug'
cfg['kind'] = 'master'
cfg['base'] = os.getcwd()
cfg['uid'] = ru.generate_id('master')
return ru.Config(cfg=cfg)
# --------------------------------------------------------------------------
#
@property
def workers(self):
return self._workers
# --------------------------------------------------------------------------
#
def _control_cb(self, topic, msg):
cmd = msg['cmd']
arg = msg['arg']
self._log.debug('control: %s: %s', cmd, arg)
if cmd == 'worker_register':
uid = arg['uid']
info = arg['info']
with self._lock:
self._workers[uid]['info'] = info
self._workers[uid]['state'] = 'ACTIVE'
self._log.debug('info: %s', info)
elif cmd == 'worker_unregister':
uid = arg['uid']
with self._lock:
self._workers[uid]['state'] = 'DONE'
# --------------------------------------------------------------------------
#
def submit(self, info, descr, count=1):
'''
submit n workers, do *not* wait for them to come up
'''
tasks = list()
for _ in range(count):
# write config file for that worker
cfg = copy.deepcopy(self._cfg)
cfg['info'] = info
uid = ru.generate_id('worker')
sbox = '%s/%s' % (cfg['base'], uid)
fname = '%s/%s.json' % (sbox, uid)
cfg['kind'] = 'worker'
cfg['uid'] = uid
cfg['base'] = sbox
ru.rec_makedir(sbox)
ru.write_json(cfg, fname)
# grab default settings via CUD construction
descr = ComputeUnitDescription(descr).as_dict()
# create task dict
task = dict()
task['description'] = copy.deepcopy(descr)
task['state'] = rps.AGENT_STAGING_INPUT_PENDING
task['type'] = 'unit'
task['uid'] = uid
task['unit_sandbox_path'] = sbox
task['description']['arguments'] = [fname]
tasks.append(task)
self._workers[uid] = task
# insert the task
self.advance(tasks, publish=False, push=True)
# --------------------------------------------------------------------------
#
def wait(self, count=None, uids=None):
'''
wait for `n` workers, *or* for workers with given UID, *or* for all
workers to become available, then return.
'''
if count:
self._log.debug('wait for %d workers', count)
while True:
with self._lock:
states = [w['state'] for w in self._workers.values()]
n = states.count('ACTIVE')
self._log.debug('states [%d]: %s', n, states)
if n >= count:
self._log.debug('wait ok')
return
time.sleep(0.1)
elif uids:
self._log.debug('wait for workers: %s', uids)
while True:
with self._lock:
states = [self._workers[uid]['state'] for uid in uids]
n = states.count('ACTIVE')
self._log.debug('states [%d]: %s', n, states)
if n == len(uids):
self._log.debug('wait ok')
return
time.sleep(0.1)
# --------------------------------------------------------------------------
#
def terminate(self):
'''
terminate all workers
'''
for uid in self._workers:
self.publish(rpc.CONTROL_PUBSUB, {'cmd': 'worker_register',
'arg': {'uid': uid}})
# ------------------------------------------------------------------------------
|
{"/src/radical/pilot/raptor/master.py": ["/src/radical/pilot/__init__.py"], "/src/radical/pilot/raptor/worker_default.py": ["/src/radical/pilot/raptor/worker.py"], "/src/radical/pilot/task.py": ["/src/radical/pilot/__init__.py", "/src/radical/pilot/staging_directives.py", "/src/radical/pilot/task_description.py"], "/src/radical/pilot/agent/executing/base.py": ["/src/radical/pilot/__init__.py", "/src/radical/pilot/agent/executing/popen.py", "/src/radical/pilot/agent/executing/funcs.py", "/src/radical/pilot/agent/executing/sleep.py"], "/src/radical/pilot/raptor/worker.py": ["/src/radical/pilot/__init__.py", "/src/radical/pilot/raptor/worker_default.py", "/src/radical/pilot/raptor/worker_mpi.py"], "/src/radical/pilot/agent/executing/sleep.py": ["/src/radical/pilot/__init__.py", "/src/radical/pilot/agent/executing/base.py"], "/src/radical/pilot/__init__.py": ["/src/radical/pilot/task.py", "/src/radical/pilot/task_description.py", "/src/radical/pilot/pilot_description.py"], "/src/radical/pilot/agent/executing/funcs.py": ["/src/radical/pilot/__init__.py", "/src/radical/pilot/agent/executing/base.py"], "/src/radical/pilot/agent/executing/popen.py": ["/src/radical/pilot/__init__.py", "/src/radical/pilot/agent/executing/base.py"], "/src/radical/pilot/raptor/worker_mpi.py": ["/src/radical/pilot/raptor/worker.py", "/src/radical/pilot/task_description.py"], "/src/radical/pilot/task_overlay/master.py": ["/src/radical/pilot/__init__.py"], "/src/radical/pilot/task_overlay/worker.py": ["/src/radical/pilot/__init__.py"], "/src/radical/pilot/utils/prof_utils.py": ["/src/radical/pilot/__init__.py", "/src/radical/pilot/utils/session.py"]}
|
23,003,953
|
eirrgang/radical.pilot
|
refs/heads/master
|
/examples/misc/task_overlay.py
|
#!/usr/bin/env python3
import os
import radical.pilot as rp
# ------------------------------------------------------------------------------
#
if __name__ == '__main__':
here = os.path.abspath(os.path.dirname(__file__))
master = '%s/task_overlay_master.py' % here
worker = '%s/task_overlay_worker.py' % here
session = rp.Session()
try:
pd = {'resource' : 'local.debug',
'cores' : 128,
'runtime' : 60}
td = {'executable' : master,
'arguments' : [worker]}
pmgr = rp.PilotManager(session=session)
umgr = rp.UnitManager(session=session)
pilot = pmgr.submit_pilots(rp.ComputePilotDescription(pd))
task = umgr.submit_units(rp.ComputeUnitDescription(td))
umgr.add_pilots(pilot)
umgr.wait_units()
finally:
session.close(download=True)
# ------------------------------------------------------------------------------
|
{"/src/radical/pilot/raptor/master.py": ["/src/radical/pilot/__init__.py"], "/src/radical/pilot/raptor/worker_default.py": ["/src/radical/pilot/raptor/worker.py"], "/src/radical/pilot/task.py": ["/src/radical/pilot/__init__.py", "/src/radical/pilot/staging_directives.py", "/src/radical/pilot/task_description.py"], "/src/radical/pilot/agent/executing/base.py": ["/src/radical/pilot/__init__.py", "/src/radical/pilot/agent/executing/popen.py", "/src/radical/pilot/agent/executing/funcs.py", "/src/radical/pilot/agent/executing/sleep.py"], "/src/radical/pilot/raptor/worker.py": ["/src/radical/pilot/__init__.py", "/src/radical/pilot/raptor/worker_default.py", "/src/radical/pilot/raptor/worker_mpi.py"], "/src/radical/pilot/agent/executing/sleep.py": ["/src/radical/pilot/__init__.py", "/src/radical/pilot/agent/executing/base.py"], "/src/radical/pilot/__init__.py": ["/src/radical/pilot/task.py", "/src/radical/pilot/task_description.py", "/src/radical/pilot/pilot_description.py"], "/src/radical/pilot/agent/executing/funcs.py": ["/src/radical/pilot/__init__.py", "/src/radical/pilot/agent/executing/base.py"], "/src/radical/pilot/agent/executing/popen.py": ["/src/radical/pilot/__init__.py", "/src/radical/pilot/agent/executing/base.py"], "/src/radical/pilot/raptor/worker_mpi.py": ["/src/radical/pilot/raptor/worker.py", "/src/radical/pilot/task_description.py"], "/src/radical/pilot/task_overlay/master.py": ["/src/radical/pilot/__init__.py"], "/src/radical/pilot/task_overlay/worker.py": ["/src/radical/pilot/__init__.py"], "/src/radical/pilot/utils/prof_utils.py": ["/src/radical/pilot/__init__.py", "/src/radical/pilot/utils/session.py"]}
|
23,003,954
|
eirrgang/radical.pilot
|
refs/heads/master
|
/src/radical/pilot/task_overlay/worker.py
|
import sys
import time
import threading as mt
import radical.utils as ru
from .. import Session
from .. import utils as rpu
from .. import constants as rpc
# ------------------------------------------------------------------------------
#
class Worker(rpu.Component):
# --------------------------------------------------------------------------
#
def __init__(self, cfg):
if isinstance(cfg, str): cfg = ru.Config(cfg=ru.read_json(cfg))
else : cfg = ru.Config(cfg=cfg)
self._uid = cfg.uid
self._term = mt.Event()
self._info = ru.Config(cfg=cfg.get('info', {}))
self._session = Session(cfg=cfg, _primary=False)
rpu.Component.__init__(self, cfg, self._session)
# connect to master
self.register_subscriber(rpc.CONTROL_PUBSUB, self._control_cb)
self.register_publisher(rpc.CONTROL_PUBSUB)
info = self.initialize()
self.publish(rpc.CONTROL_PUBSUB, {'cmd': 'worker_register',
'arg': {'uid' : self._uid,
'info': info}})
# --------------------------------------------------------------------------
#
def _control_cb(self, topic, msg):
self._log.debug('got control msg: %s: %s', topic, msg)
if msg['cmd'] == 'worker_terminate':
if msg['arg']['uid'] == self._uid:
self._term.set()
self.stop()
sys.exit(0)
# --------------------------------------------------------------------------
#
def run(self):
while not self._term.is_set():
time.sleep(0.1)
# ------------------------------------------------------------------------------
|
{"/src/radical/pilot/raptor/master.py": ["/src/radical/pilot/__init__.py"], "/src/radical/pilot/raptor/worker_default.py": ["/src/radical/pilot/raptor/worker.py"], "/src/radical/pilot/task.py": ["/src/radical/pilot/__init__.py", "/src/radical/pilot/staging_directives.py", "/src/radical/pilot/task_description.py"], "/src/radical/pilot/agent/executing/base.py": ["/src/radical/pilot/__init__.py", "/src/radical/pilot/agent/executing/popen.py", "/src/radical/pilot/agent/executing/funcs.py", "/src/radical/pilot/agent/executing/sleep.py"], "/src/radical/pilot/raptor/worker.py": ["/src/radical/pilot/__init__.py", "/src/radical/pilot/raptor/worker_default.py", "/src/radical/pilot/raptor/worker_mpi.py"], "/src/radical/pilot/agent/executing/sleep.py": ["/src/radical/pilot/__init__.py", "/src/radical/pilot/agent/executing/base.py"], "/src/radical/pilot/__init__.py": ["/src/radical/pilot/task.py", "/src/radical/pilot/task_description.py", "/src/radical/pilot/pilot_description.py"], "/src/radical/pilot/agent/executing/funcs.py": ["/src/radical/pilot/__init__.py", "/src/radical/pilot/agent/executing/base.py"], "/src/radical/pilot/agent/executing/popen.py": ["/src/radical/pilot/__init__.py", "/src/radical/pilot/agent/executing/base.py"], "/src/radical/pilot/raptor/worker_mpi.py": ["/src/radical/pilot/raptor/worker.py", "/src/radical/pilot/task_description.py"], "/src/radical/pilot/task_overlay/master.py": ["/src/radical/pilot/__init__.py"], "/src/radical/pilot/task_overlay/worker.py": ["/src/radical/pilot/__init__.py"], "/src/radical/pilot/utils/prof_utils.py": ["/src/radical/pilot/__init__.py", "/src/radical/pilot/utils/session.py"]}
|
23,003,955
|
eirrgang/radical.pilot
|
refs/heads/master
|
/examples/misc/task_overlay_master.py
|
#!/usr/bin/env python3
import os
import sys
import time
import signal
import threading as mt
import radical.pilot as rp
import radical.utils as ru
# This script has to run as a task within an pilot allocation, and is
# a demonstration of a task overlay within the RCT framework.
# It will:
#
# - create a master which bootstrappes a specific communication layer
# - insert n workers into the pilot (again as a task)
# - perform RPC handshake with those workers
# - send RPC requests to the workers
# - terminate the worker
#
# The worker itself is an external program which is not covered in this code.
# ------------------------------------------------------------------------------
#
class Request(object):
# poor man's future
# TODO: use proper future implementation
# --------------------------------------------------------------------------
#
def __init__(self, work):
self._uid = ru.generate_id('request')
self._work = work
self._state = 'NEW'
self._result = None
# --------------------------------------------------------------------------
#
@property
def uid(self):
return self._uid
@property
def state(self):
return self._state
@property
def result(self):
return self._result
# --------------------------------------------------------------------------
#
def as_dict(self):
'''
produce the request message to be sent over the wire to the workers
'''
return {'uid' : self._uid,
'state' : self._state,
'result': self._result,
'call' : self._work['call'],
'args' : self._work['args'],
'kwargs': self._work['kwargs'],
}
# --------------------------------------------------------------------------
#
def set_result(self, result, error):
'''
This is called by the master to fulfill the future
'''
self._result = result
self._error = error
if error: self._state = 'FAILED'
else : self._state = 'DONE'
# --------------------------------------------------------------------------
#
def wait(self):
while self.state not in ['DONE', 'FAILED']:
time.sleep(0.1)
return self._result
# ------------------------------------------------------------------------------
#
class MyMaster(rp.task_overlay.Master):
'''
This class provides the communication setup for the task overlay: it will
set up the request / response communication queus and provide the endpoint
information to be forwarded to the workers.
'''
# --------------------------------------------------------------------------
#
def __init__(self):
self._requests = dict() # bookkeeping of submitted requests
self._lock = mt.Lock() # lock the request dist on updates
# initialized the task overlay base class. That base class will ensure
# proper communication channels to the pilot agent.
rp.task_overlay.Master.__init__(self)
# set up RU ZMQ Queues for request distribution and result collection
req_cfg = ru.Config(cfg={'channel' : 'to_req',
'type' : 'queue',
'uid' : self._uid + '.req',
'path' : os.getcwd(),
'stall_hwm' : 0,
'bulk_size' : 0})
res_cfg = ru.Config(cfg={'channel' : 'to_res',
'type' : 'queue',
'uid' : self._uid + '.res',
'path' : os.getcwd(),
'stall_hwm' : 0,
'bulk_size' : 0})
self._req_queue = ru.zmq.Queue(req_cfg)
self._res_queue = ru.zmq.Queue(res_cfg)
self._req_queue.start()
self._res_queue.start()
self._req_addr_put = str(self._req_queue.addr_put)
self._req_addr_get = str(self._req_queue.addr_get)
self._res_addr_put = str(self._res_queue.addr_put)
self._res_addr_get = str(self._res_queue.addr_get)
# this master will put requests onto the request queue, and will get
# responses from the response queue. Note that the responses will be
# delivered via an async callback (`self.result_cb`).
self._req_put = ru.zmq.Putter('to_req', self._req_addr_put)
self._res_get = ru.zmq.Getter('to_res', self._res_addr_get,
cb=self.result_cb)
# for the workers it is the opposite: they will get requests from the
# request queue, and will send responses to the response queue.
self._info = {'req_addr_get': self._req_addr_get,
'res_addr_put': self._res_addr_put}
# make sure the channels are up before allowing to submit requests
time.sleep(1)
# --------------------------------------------------------------------------
#
def submit(self, worker, count=1):
'''
submit n workers, and pass the queue info as configuration file
'''
descr = {'executable': worker}
return rp.task_overlay.Master.submit(self, self._info, descr, count)
# --------------------------------------------------------------------------
#
def request(self, call, *args, **kwargs):
'''
submit a work request (function call spec) to the request queue
'''
# create request and add to bookkeeping dict. That response object will
# be updated once a response for the respective request UID arrives.
req = Request(work={'call' : call,
'args' : args,
'kwargs': kwargs})
with self._lock:
self._requests[req.uid] = req
# push the request message (here and dictionary) onto the request queue
self._req_put.put(req.as_dict())
# return the request to the master script for inspection etc.
return req
# --------------------------------------------------------------------------
#
def result_cb(self, msg):
# update result and error information for the corresponding request UID
uid = msg['req']
res = msg['res']
err = msg['err']
self._requests[uid].set_result(res, err)
# ------------------------------------------------------------------------------
#
if __name__ == '__main__':
# This master script currently runs as a task within a pilot allocation.
# The purpose of this master is to (a) spawn a set or workers within the
# same allocation, (b) to distribute work items (`hello` function calls) to
# those workers, and (c) to collect the responses again.
worker = sys.argv[1]
# create a master class instance - this will establish communitation to the
# pilot agent
master = MyMaster()
# insert `n` worker tasks into the agent. The agent will schedule (place)
# those workers and execute them.
master.submit(count=2, worker=worker)
# wait until `m` of those workers are up
# This is optional, work requests can be submitted before and will wait in
# a work queue.
master.wait(count=2)
# submit work requests. The returned request objects behave like Futures
# (they will be implemented as proper Futures in the future - ha!)
req = list()
for n in range(32):
req.append(master.request('hello', n))
# wait for request completion and print the results
for r in req:
r.wait()
print(r.result)
# simply terminate
# FIXME: this needs to be cleaned up
sys.stdout.flush()
os.kill(os.getpid(), signal.SIGKILL)
os.kill(os.getpid(), signal.SIGTERM)
# ------------------------------------------------------------------------------
|
{"/src/radical/pilot/raptor/master.py": ["/src/radical/pilot/__init__.py"], "/src/radical/pilot/raptor/worker_default.py": ["/src/radical/pilot/raptor/worker.py"], "/src/radical/pilot/task.py": ["/src/radical/pilot/__init__.py", "/src/radical/pilot/staging_directives.py", "/src/radical/pilot/task_description.py"], "/src/radical/pilot/agent/executing/base.py": ["/src/radical/pilot/__init__.py", "/src/radical/pilot/agent/executing/popen.py", "/src/radical/pilot/agent/executing/funcs.py", "/src/radical/pilot/agent/executing/sleep.py"], "/src/radical/pilot/raptor/worker.py": ["/src/radical/pilot/__init__.py", "/src/radical/pilot/raptor/worker_default.py", "/src/radical/pilot/raptor/worker_mpi.py"], "/src/radical/pilot/agent/executing/sleep.py": ["/src/radical/pilot/__init__.py", "/src/radical/pilot/agent/executing/base.py"], "/src/radical/pilot/__init__.py": ["/src/radical/pilot/task.py", "/src/radical/pilot/task_description.py", "/src/radical/pilot/pilot_description.py"], "/src/radical/pilot/agent/executing/funcs.py": ["/src/radical/pilot/__init__.py", "/src/radical/pilot/agent/executing/base.py"], "/src/radical/pilot/agent/executing/popen.py": ["/src/radical/pilot/__init__.py", "/src/radical/pilot/agent/executing/base.py"], "/src/radical/pilot/raptor/worker_mpi.py": ["/src/radical/pilot/raptor/worker.py", "/src/radical/pilot/task_description.py"], "/src/radical/pilot/task_overlay/master.py": ["/src/radical/pilot/__init__.py"], "/src/radical/pilot/task_overlay/worker.py": ["/src/radical/pilot/__init__.py"], "/src/radical/pilot/utils/prof_utils.py": ["/src/radical/pilot/__init__.py", "/src/radical/pilot/utils/session.py"]}
|
23,003,956
|
eirrgang/radical.pilot
|
refs/heads/master
|
/src/radical/pilot/utils/prof_utils.py
|
import os
import glob
import radical.utils as ru
from .. import states as rps
from .session import fetch_json
_debug = os.environ.get('RP_PROF_DEBUG')
# ------------------------------------------------------------------------------
#
# pilot and unit activities: core hours are derived by multiplying the
# respective time durations with pilot size / unit size. The 'idle' utilization
# and the 'agent' utilization are derived separately.
#
# Note that durations should add up to the `x_total` generations to ensure
# accounting for the complete unit/pilot utilization.
PILOT_DURATIONS = {
'provide' : {
'total' : [{ru.EVENT: 'bootstrap_0_start'},
{ru.EVENT: 'bootstrap_0_stop' }]
},
# times between PMGR_ACTIVE and the termination command are not
# considered pilot specific consumptions. If some resources remain
# unused during that time, it is either due to inefficiencies of
# workload management (accounted for in the unit consumption metrics),
# or the pilot is starving for workload.
#
'consume' : {
'boot' : [{ru.EVENT: 'bootstrap_0_start'},
{ru.EVENT: 'sync_rel' }],
'setup_1' : [{ru.EVENT: 'sync_rel' },
{ru.STATE: rps.PMGR_ACTIVE }],
'ignore' : [{ru.STATE: rps.PMGR_ACTIVE },
{ru.EVENT: 'cmd' ,
ru.MSG : 'cancel_pilot' }],
'term' : [{ru.EVENT: 'cmd' ,
ru.MSG : 'cancel_pilot' },
{ru.EVENT: 'bootstrap_0_stop' }],
},
# FIXME: separate out DVM startup time
# 'rte' : [{ru.STATE: rps.PMGR_ACTIVE },
# {ru.STATE: rps.PMGR_ACTIVE }],
# 'setup_2' : [{ru.STATE: rps.PMGR_ACTIVE },
# {ru.STATE: rps.PMGR_ACTIVE }],
# resources on agent nodes are consumed for all of the pilot's lifetime
'agent' : {
'total' : [{ru.EVENT: 'bootstrap_0_start'},
{ru.EVENT: 'bootstrap_0_stop' }]
}
}
UNIT_DURATIONS_DEFAULT = {
'consume' : {
'exec_queue' : [{ru.EVENT: 'schedule_ok' },
{ru.STATE: rps.AGENT_EXECUTING }],
'exec_prep' : [{ru.STATE: rps.AGENT_EXECUTING },
{ru.EVENT: 'exec_start' }],
'exec_rp' : [{ru.EVENT: 'exec_start' },
{ru.EVENT: 'cu_start' }],
'exec_sh' : [{ru.EVENT: 'cu_start' },
{ru.EVENT: 'cu_start' }],
'exec_cmd' : [{ru.EVENT: 'cu_start' },
{ru.EVENT: 'cu_stop' }],
'term_sh' : [{ru.EVENT: 'cu_stop' },
{ru.EVENT: 'cu_stop' }],
'term_rp' : [{ru.EVENT: 'cu_stop' },
{ru.EVENT: 'exec_stop' }],
'unschedule' : [{ru.EVENT: 'exec_stop' },
{ru.EVENT: 'unschedule_stop' }]
# # if we have cmd_start / cmd_stop:
# 'exec_sh' : [{ru.EVENT: 'cu_start' },
# {ru.EVENT: 'cmd_start' }],
# 'exec_cmd' : [{ru.EVENT: 'cmd_start' },
# {ru.EVENT: 'cmd_stop' }],
# 'term_sh' : [{ru.EVENT: 'cmd_stop' },
# {ru.EVENT: 'cu_stop' }],
}
}
UNIT_DURATIONS_PRTE = {
'consume' : {
'exec_queue' : [{ru.EVENT: 'schedule_ok' },
{ru.STATE: rps.AGENT_EXECUTING }],
'exec_prep' : [{ru.STATE: rps.AGENT_EXECUTING },
{ru.EVENT: 'exec_start' }],
'exec_rp' : [{ru.EVENT: 'exec_start' },
{ru.EVENT: 'cu_start' }],
'exec_sh' : [{ru.EVENT: 'cu_start' },
{ru.EVENT: 'cu_exec_start' }],
'prte_phase_1': [{ru.EVENT: 'cu_exec_start' },
{ru.EVENT: 'prte_init_complete' }],
'prte_phase_2': [{ru.EVENT: 'prte_init_complete' },
{ru.EVENT: 'prte_sending_launch_msg'}],
'exec_cmd' : [{ru.EVENT: 'prte_sending_launch_msg'},
{ru.EVENT: 'prte_iof_complete' }],
'prte_phase_3': [{ru.EVENT: 'prte_iof_complete' },
{ru.EVENT: 'prte_notify_completed' }],
'term_sh' : [{ru.EVENT: 'prte_notify_completed' },
{ru.EVENT: 'cu_stop' }],
'term_rp' : [{ru.EVENT: 'cu_stop' },
{ru.EVENT: 'exec_stop' }],
'unschedule' : [{ru.EVENT: 'exec_stop' },
{ru.EVENT: 'unschedule_stop' }],
# if we have cmd_start / cmd_stop:
'prte_phase_2': [{ru.EVENT: 'prte_init_complete' },
{ru.EVENT: 'app_start' }],
'exec_cmd' : [{ru.EVENT: 'app_start' },
{ru.EVENT: 'app_stop' }],
'prte_phase_3': [{ru.EVENT: 'app_stop' },
{ru.EVENT: 'prte_notify_completed' }],
# # if we have app_start / app_stop:
# 'prte_phase_2': [{ru.EVENT: 'prte_init_complete' },
# {ru.EVENT: 'cmd_start' }],
# 'exec_cmd' : [{ru.EVENT: 'cmd_start' },
# {ru.EVENT: 'cmd_stop' }],
# 'prte_phase_3': [{ru.EVENT: 'cmd_stop' },
# {ru.EVENT: 'prte_notify_completed' }],
}
}
# ------------------------------------------------------------------------------
#
def get_hostmap(profile):
'''
We abuse the profile combination to also derive a pilot-host map, which
will tell us on what exact host each pilot has been running. To do so, we
check for the PMGR_ACTIVE advance event in agent.0.prof, and use the NTP
sync info to associate a hostname.
'''
# FIXME: This should be replaced by proper hostname logging
# in `pilot.resource_details`.
hostmap = dict() # map pilot IDs to host names
for entry in profile:
if entry[ru.EVENT] == 'hostname':
hostmap[entry[ru.UID]] = entry[ru.MSG]
return hostmap
# ------------------------------------------------------------------------------
#
def get_hostmap_deprecated(profiles):
'''
This method mangles combine_profiles and get_hostmap, and is deprecated. At
this point it only returns the hostmap
'''
hostmap = dict() # map pilot IDs to host names
for pname, prof in profiles.items():
if not len(prof):
continue
if not prof[0][ru.MSG]:
continue
host, ip, _, _, _ = prof[0][ru.MSG].split(':')
host_id = '%s:%s' % (host, ip)
for row in prof:
if 'agent.0.prof' in pname and \
row[ru.EVENT] == 'advance' and \
row[ru.STATE] == rps.PMGR_ACTIVE:
hostmap[row[ru.UID]] = host_id
break
return hostmap
# ------------------------------------------------------------------------------
#
def get_session_profile(sid, src=None):
if not src:
src = "%s/%s" % (os.getcwd(), sid)
if os.path.exists(src):
# we have profiles locally
profiles = glob.glob("%s/*.prof" % src)
profiles += glob.glob("%s/*/*.prof" % src)
else:
# need to fetch profiles
from .session import fetch_profiles
profiles = fetch_profiles(sid=sid, skip_existing=True)
# filter out some frequent, but uninteresting events
efilter = {ru.EVENT: [
# 'get',
'publish',
'schedule_skip',
'schedule_fail',
'staging_stderr_start',
'staging_stderr_stop',
'staging_stdout_start',
'staging_stdout_stop',
'staging_uprof_start',
'staging_uprof_stop',
'update_pushed',
]}
profiles = ru.read_profiles(profiles, sid, efilter=efilter)
profile, accuracy = ru.combine_profiles(profiles)
profile = ru.clean_profile(profile, sid, rps.FINAL, rps.CANCELED)
hostmap = get_hostmap(profile)
if not hostmap:
# FIXME: legacy host notation - deprecated
hostmap = get_hostmap_deprecated(profiles)
return profile, accuracy, hostmap
# ------------------------------------------------------------------------------
#
def get_session_description(sid, src=None, dburl=None):
"""
This will return a description which is usable for radical.analytics
evaluation. It informs about
- set of stateful entities
- state models of those entities
- event models of those entities (maybe)
- configuration of the application / module
If `src` is given, it is interpreted as path to search for session
information (json dump). `src` defaults to `$PWD/$sid`.
if `dburl` is given, its value is used to fetch session information from
a database. The dburl value defaults to `RADICAL_PILOT_DBURL`.
"""
if not src:
src = "%s/%s" % (os.getcwd(), sid)
if os.path.isfile('%s/%s.json' % (src, sid)):
json = ru.read_json('%s/%s.json' % (src, sid))
else:
ftmp = fetch_json(sid=sid, dburl=dburl, tgt=src, skip_existing=True)
json = ru.read_json(ftmp)
# make sure we have uids
# FIXME v0.47: deprecate
def fix_json(json):
def fix_uids(json):
if isinstance(json, list):
for elem in json:
fix_uids(elem)
elif isinstance(json, dict):
if 'unitmanager' in json and 'umgr' not in json:
json['umgr'] = json['unitmanager']
if 'pilotmanager' in json and 'pmgr' not in json:
json['pmgr'] = json['pilotmanager']
if '_id' in json and 'uid' not in json:
json['uid'] = json['_id']
if 'cfg' not in json:
json['cfg'] = dict()
for k,v in json.items():
fix_uids(v)
fix_uids(json)
fix_json(json)
assert(sid == json['session']['uid']), 'sid inconsistent'
ret = dict()
ret['entities'] = dict()
tree = dict()
tree[sid] = {'uid' : sid,
'etype' : 'session',
'cfg' : json['session']['cfg'],
'has' : ['umgr', 'pmgr'],
'children' : list()
}
for pmgr in sorted(json['pmgr'], key=lambda k: k['uid']):
uid = pmgr['uid']
tree[sid]['children'].append(uid)
tree[uid] = {'uid' : uid,
'etype' : 'pmgr',
'cfg' : pmgr['cfg'],
'has' : ['pilot'],
'children' : list()
}
for umgr in sorted(json['umgr'], key=lambda k: k['uid']):
uid = umgr['uid']
tree[sid]['children'].append(uid)
tree[uid] = {'uid' : uid,
'etype' : 'umgr',
'cfg' : umgr['cfg'],
'has' : ['unit'],
'children' : list()
}
# also inject the pilot description, and resource specifically
tree[uid]['description'] = dict()
for pilot in sorted(json['pilot'], key=lambda k: k['uid']):
uid = pilot['uid']
pmgr = pilot['pmgr']
pilot['cfg']['resource_details'] = pilot['resource_details']
tree[pmgr]['children'].append(uid)
tree[uid] = {'uid' : uid,
'etype' : 'pilot',
'cfg' : pilot['cfg'],
'description': pilot['description'],
'has' : ['unit'],
'children' : list()
}
# also inject the pilot description, and resource specifically
for unit in sorted(json['unit'], key=lambda k: k['uid']):
uid = unit['uid']
pid = unit['pilot']
umgr = unit['umgr']
tree[pid ]['children'].append(uid)
tree[umgr]['children'].append(uid)
tree[uid] = {'uid' : uid,
'etype' : 'unit',
'cfg' : unit,
'description' : unit['description'],
'has' : list(),
'children' : list()
}
# remove duplicate
del(tree[uid]['cfg']['description'])
ret['tree'] = tree
ret['entities']['pilot'] = {'state_model' : rps._pilot_state_values,
'state_values' : rps._pilot_state_inv_full,
'event_model' : dict()}
ret['entities']['unit'] = {'state_model' : rps._unit_state_values,
'state_values' : rps._unit_state_inv_full,
'event_model' : dict()}
ret['entities']['session'] = {'state_model' : None, # has no states
'state_values' : None,
'event_model' : dict()}
ret['config'] = dict() # session config goes here
return ret
# ------------------------------------------------------------------------------
#
def get_node_index(node_list, node, cpn, gpn):
r0 = node_list.index(node) * (cpn + gpn)
r1 = r0 + cpn + gpn - 1
return [r0, r1]
# ------------------------------------------------------------------------------
#
def get_duration(thing, dur):
for e in dur:
if ru.STATE in e and ru.EVENT not in e:
e[ru.EVENT] = 'state'
t0 = thing.timestamps(event=dur[0])
t1 = thing.timestamps(event=dur[1])
if not len(t0) or not len(t1):
return [None, None]
return(t0[0], t1[-1])
# ------------------------------------------------------------------------------
#
def cluster_resources(resources):
# resources is a list of
# - single index (single core of gpu
# - [r0, r1] tuples (ranges of core, gpu indexes)
# cluster continuous stretches of resources
ret = list()
idx = set()
for r in resources:
if isinstance(r, int):
idx.add(r)
else:
for idx in range(r[0], r[1] + 1):
idx.add(idx)
r0 = None
r1 = None
for i in sorted(list(idx)):
if r0 is None:
r0 = i
continue
if r1 is None:
if i == r0 + 1:
r1 = i
continue
ret.append([r0, r0])
r0 = None
continue
if i == r1 + 1:
r1 = i
continue
ret.append([r0, r1])
r0 = i
r1 = None
if r0 is not None:
if r1 is not None:
ret.append([r0, r1])
else:
ret.append([r0, r0])
return ret
# ------------------------------------------------------------------------------
#
def _get_pilot_provision(session, pilot):
pid = pilot.uid
cpn = pilot.cfg['resource_details']['rm_info']['cores_per_node']
gpn = pilot.cfg['resource_details']['rm_info']['gpus_per_node']
ret = dict()
nodes, anodes, pnodes = _get_nodes(pilot)
for metric in PILOT_DURATIONS['provide']:
boxes = list()
t0, t1 = get_duration(pilot, PILOT_DURATIONS['provide'][metric])
if t0 is None:
t0 = pilot.events [0][ru.TIME]
t1 = pilot.events[-1][ru.TIME]
for node in nodes:
r0, r1 = get_node_index(nodes, node, cpn, gpn)
boxes.append([t0, t1, r0, r1])
ret['total'] = {pid: boxes}
return ret
# ------------------------------------------------------------------------------
#
def get_provided_resources(session):
'''
For all ra.pilots, return the amount and time of resources provided.
This computes sets of 4-tuples of the form: [t0, t1, r0, r1] where:
t0: time, begin of resource provision
t1: time, begin of resource provision
r0: int, index of resources provided (min)
r1: int, index of resources provided (max)
The tuples are formed so that t0 to t1 and r0 to r1 are continuous.
'''
provided = dict()
for p in session.get(etype='pilot'):
data = _get_pilot_provision(session, p)
for metric in data:
if metric not in provided:
provided[metric] = dict()
for uid in data[metric]:
provided[metric][uid] = data[metric][uid]
return provided
# ------------------------------------------------------------------------------
#
def get_consumed_resources(session):
'''
For all ra.pilot or ra.unit entities, return the amount and time of
resources consumed. A consumed resource is characterized by:
- a resource type (we know about cores and gpus)
- a metric name (what the resource was used for
- a list of 4-tuples of the form: [t0, t1, r0, r1]
- t0: time, begin of resource consumption
- t1: time, begin of resource consumption
- r0: int, index of resources consumed (min)
- r1: int, index of resources consumed (max)
The tuples are formed so that t0 to t1 and r0 to r1 are continuous.
An entity can consume different resources under different metrics - but the
returned consumption specs will never overlap, meaning, that any resource is
accounted for exactly one metric at any point in time. The returned
structure has the following overall form:
{
'metric_1' : {
uid_1 : [[t0, t1, r0, r1],
[t2, t3, r2, r3],
...
],
uid_2 : ...
},
'metric_2' : ...
}
'''
log = ru.Logger('radical.pilot.utils')
consumed = dict()
for e in session.get(etype=['pilot', 'unit']):
if e.etype == 'pilot': data = _get_pilot_consumption(session, e)
elif e.etype == 'unit' : data = _get_unit_consumption(session, e)
for metric in data:
if metric not in consumed:
consumed[metric] = dict()
for uid in data[metric]:
consumed[metric][uid] = data[metric][uid]
# we defined two additional metrics, 'warmup' and 'drain', which are defined
# for all resources of the pilot. `warmup` is defined as the time from
# when the pilot becomes active, to the time the resource is first consumed
# by a unit. `drain` is the inverse: the time from when any unit last
# consumed the resource to the time when the pilot begins termination.
for pilot in session.get(etype='pilot'):
if pilot.cfg['task_launch_method'] == 'PRTE':
# print('\nusing prte configuration')
unit_durations = UNIT_DURATIONS_PRTE
else:
# print('\nusing default configuration')
unit_durations = UNIT_DURATIONS_DEFAULT
pt = pilot.timestamps
log.debug('timestamps:')
for ts in pt():
log.debug(' %10.2f %-20s %-15s %-15s %-15s %-15s %s',
ts[0], ts[1], ts[2], ts[3], ts[4], ts[5], ts[6])
p_min = pt(event=PILOT_DURATIONS['consume']['ignore'][0]) [0]
p_max = pt(event=PILOT_DURATIONS['consume']['ignore'][1])[-1]
# p_max = pilot.events[-1][ru.TIME]
log.debug('pmin, pmax: %10.2f / %10.2f', p_min, p_max)
pid = pilot.uid
cpn = pilot.cfg['resource_details']['rm_info']['cores_per_node']
gpn = pilot.cfg['resource_details']['rm_info']['gpus_per_node']
nodes, anodes, pnodes = _get_nodes(pilot)
# find resource utilization scope for all resources. We begin filling
# the resource dict with
#
# resource_id : [t_min=None, t_max=None]
#
# and then iterate over all units. Wen we find a unit using some
# resource id, we set or adjust t_min / t_max.
resources = dict()
for pnode in pnodes:
idx = get_node_index(nodes, pnode, cpn, gpn)
for c in range(idx[0], idx[1] + 1):
resources[c] = [None, None]
for unit in session.get(etype='unit'):
if unit.cfg.get('pilot') != pid:
continue
try:
snodes = unit.cfg['slots']['nodes']
ut = unit.timestamps
u_min = ut(event=unit_durations['consume']['exec_queue'][0]) [0]
u_max = ut(event=unit_durations['consume']['unschedule'][1])[-1]
except:
continue
for snode in snodes:
node = [snode['name'], snode['uid']]
r0, _ = get_node_index(nodes, node, cpn, gpn)
for core_map in snode['core_map']:
for core in core_map:
idx = r0 + core
t_min = resources[idx][0]
t_max = resources[idx][1]
if t_min is None or t_min > u_min: t_min = u_min
if t_max is None or t_max < u_max: t_max = u_max
resources[idx] = [t_min, t_max]
for gpu_map in snode['gpu_map']:
for gpu in gpu_map:
idx = r0 + cpn + gpu
t_min = resources[idx][0]
t_max = resources[idx][1]
if t_min is None or t_min > u_min: t_min = u_min
if t_max is None or t_max < u_max: t_max = u_max
resources[idx] = [t_min, t_max]
# now sift through resources and find buckets of pairs with same t_min
# or same t_max
bucket_min = dict()
bucket_max = dict()
bucket_none = list()
for idx in resources:
t_min = resources[idx][0]
t_max = resources[idx][1]
if t_min is None:
assert(t_max is None)
bucket_none.append(idx)
else:
if t_min not in bucket_min:
bucket_min[t_min] = list()
bucket_min[t_min].append(idx)
if t_max not in bucket_max:
bucket_max[t_max] = list()
bucket_max[t_max].append(idx)
boxes_warm = list()
boxes_drain = list()
boxes_idle = list()
# now cluster all lists and add the respective boxes
for t_min in bucket_min:
for r in cluster_resources(bucket_min[t_min]):
boxes_warm.append([p_min, t_min, r[0], r[1]])
for t_max in bucket_max:
for r in cluster_resources(bucket_max[t_max]):
boxes_drain.append([t_max, p_max, r[0], r[1]])
for r in cluster_resources(bucket_none):
boxes_idle.append([p_min, p_max, r[0], r[1]])
if 'warm' not in consumed: consumed['warm'] = dict()
if 'drain' not in consumed: consumed['drain'] = dict()
if 'idle' not in consumed: consumed['idle'] = dict()
consumed['warm'][pid] = boxes_warm
consumed['drain'][pid] = boxes_drain
consumed['idle'][pid] = boxes_idle
# pprint.pprint(consumed)
return consumed
# ------------------------------------------------------------------------------
#
def _get_nodes(pilot):
pnodes = pilot.cfg['resource_details']['rm_info']['node_list']
agents = pilot.cfg['resource_details']['rm_info'].get('agent_nodes', [])
anodes = list()
nodes = list()
for agent in agents:
anodes.append(agents[agent])
nodes = pnodes + anodes
return nodes, anodes, pnodes
# ------------------------------------------------------------------------------
#
def _get_pilot_consumption(session, pilot):
# Pilots consume resources in different ways:
#
# - the pilot needs to bootstrap and initialize before becoming active,
# i.e., before it can begin to manage the workload, and needs to
# terminate and clean up during shutdown;
# - the pilot may block one or more nodes or cores for it's own components
# (sub-agents), and those components are not available for workload
# execution
# - the pilot may perform operations while managing the workload.
#
# This method will compute the first two contributions and part of the 3rd.
# It will *not* account for those parts of the 3rd which are performed while
# specfic resources are blocked for the affected workload element (task)
# - those resource consumption is considered to be a consumption *of that
# task*, which allows us to compute tasks specific resource utilization
# overheads.
pid = pilot.uid
cpn = pilot.cfg['resource_details']['rm_info']['cores_per_node']
gpn = pilot.cfg['resource_details']['rm_info']['gpus_per_node']
ret = dict()
# Account for agent resources. Agents use full nodes, i.e., cores and GPUs
# We happen to know that agents use the first nodes in the allocation and
# their resource tuples thus start at index `0`, but for completeness we
# ensure that by inspecting the pilot cfg.
# Duration is for all of the pilot runtime. This is not precises really,
# since several bootstrapping phases happen before the agents exist - but we
# consider the nodes blocked for the sub-agents from the get-go.
t0, t1 = get_duration(pilot, PILOT_DURATIONS['agent']['total'])
boxes = list()
# Substract agent nodes from the nodelist, so that we correctly attribute
# other global pilot metrics to the remaining nodes.
nodes, anodes, pnodes = _get_nodes(pilot)
if anodes and t0 is not None:
for anode in anodes:
r0, r1 = get_node_index(nodes, anode, cpn, gpn)
boxes.append([t0, t1, r0, r1])
ret['agent'] = {pid: boxes}
# account for all other pilot metrics
for metric in PILOT_DURATIONS['consume']:
if metric == 'ignore':
continue
boxes = list()
t0, t1 = get_duration(pilot, PILOT_DURATIONS['consume'][metric])
if t0 is not None:
for node in pnodes:
r0, r1 = get_node_index(nodes, node, cpn, gpn)
boxes.append([t0, t1, r0, r1])
ret[metric] = {pid: boxes}
return ret
# ------------------------------------------------------------------------------
#
def _get_unit_consumption(session, unit):
# we need to know what pilot the unit ran on. If we don't find a designated
# pilot, no resources were consumed
uid = unit.uid
pid = unit.cfg['pilot']
if not pid:
return dict()
# get the pilot for inspection
pilot = session.get(uid=pid)
if isinstance(pilot, list):
assert(len(pilot) == 1)
pilot = pilot[0]
# FIXME: it is inefficient to query those values again and again
cpn = pilot.cfg['resource_details']['rm_info']['cores_per_node']
gpn = pilot.cfg['resource_details']['rm_info']['gpus_per_node']
nodes, anodes, pnodes = _get_nodes(pilot)
# Units consume only those resources they are scheduled on.
if 'slots' not in unit.cfg:
return dict()
snodes = unit.cfg['slots']['nodes']
resources = list()
for snode in snodes:
node = [snode['name'], snode['uid']]
r0, _ = get_node_index(nodes, node, cpn, gpn)
for core_map in snode['core_map']:
for core in core_map:
resources.append(r0 + core)
for gpu_map in snode['gpu_map']:
for gpu in gpu_map:
resources.append(r0 + cpn + gpu)
# find continuous stretched of resources to minimize number of boxes
resources = cluster_resources(resources)
# we heuristically switch between PRTE event traces and normal (fork) event
# traces
if pilot.cfg['task_launch_method'] == 'PRTE':
unit_durations = UNIT_DURATIONS_PRTE
else:
unit_durations = UNIT_DURATIONS_DEFAULT
if _debug:
print()
ret = dict()
for metric in unit_durations['consume']:
boxes = list()
t0, t1 = get_duration(unit, unit_durations['consume'][metric])
if t0 is not None:
if _debug:
print('%s: %-15s : %10.3f - %10.3f = %10.3f'
% (unit.uid, metric, t1, t0, t1 - t0))
for r in resources:
boxes.append([t0, t1, r[0], r[1]])
else:
if _debug:
print('%s: %-15s : -------------- ' % (unit.uid, metric))
dur = unit_durations['consume'][metric]
print(dur)
for e in dur:
if ru.STATE in e and ru.EVENT not in e:
e[ru.EVENT] = 'state'
t0 = unit.timestamps(event=dur[0])
t1 = unit.timestamps(event=dur[1])
print(t0)
print(t1)
for e in unit.events:
print('\t'.join([str(x) for x in e]))
# sys.exit()
ret[metric] = {uid: boxes}
return ret
# ------------------------------------------------------------------------------
|
{"/src/radical/pilot/raptor/master.py": ["/src/radical/pilot/__init__.py"], "/src/radical/pilot/raptor/worker_default.py": ["/src/radical/pilot/raptor/worker.py"], "/src/radical/pilot/task.py": ["/src/radical/pilot/__init__.py", "/src/radical/pilot/staging_directives.py", "/src/radical/pilot/task_description.py"], "/src/radical/pilot/agent/executing/base.py": ["/src/radical/pilot/__init__.py", "/src/radical/pilot/agent/executing/popen.py", "/src/radical/pilot/agent/executing/funcs.py", "/src/radical/pilot/agent/executing/sleep.py"], "/src/radical/pilot/raptor/worker.py": ["/src/radical/pilot/__init__.py", "/src/radical/pilot/raptor/worker_default.py", "/src/radical/pilot/raptor/worker_mpi.py"], "/src/radical/pilot/agent/executing/sleep.py": ["/src/radical/pilot/__init__.py", "/src/radical/pilot/agent/executing/base.py"], "/src/radical/pilot/__init__.py": ["/src/radical/pilot/task.py", "/src/radical/pilot/task_description.py", "/src/radical/pilot/pilot_description.py"], "/src/radical/pilot/agent/executing/funcs.py": ["/src/radical/pilot/__init__.py", "/src/radical/pilot/agent/executing/base.py"], "/src/radical/pilot/agent/executing/popen.py": ["/src/radical/pilot/__init__.py", "/src/radical/pilot/agent/executing/base.py"], "/src/radical/pilot/raptor/worker_mpi.py": ["/src/radical/pilot/raptor/worker.py", "/src/radical/pilot/task_description.py"], "/src/radical/pilot/task_overlay/master.py": ["/src/radical/pilot/__init__.py"], "/src/radical/pilot/task_overlay/worker.py": ["/src/radical/pilot/__init__.py"], "/src/radical/pilot/utils/prof_utils.py": ["/src/radical/pilot/__init__.py", "/src/radical/pilot/utils/session.py"]}
|
23,205,060
|
qikai521/cfjpjc
|
refs/heads/master
|
/cfjapp/views.py
|
from django.contrib.auth import authenticate,login,logout
from django.shortcuts import render,redirect,HttpResponse
from django.template import RequestContext
from .forms import LoginForm,RegisterForm
from .models import ProduceModel,NewUser
from django.core.exceptions import ObjectDoesNotExist
from django.views.decorators.csrf import csrf_exempt
from django.http import JsonResponse
import re
# Create your views here.
def index(req):
homeShowList = ProduceModel.objects.order_by('sortid')
homeShowList = ProduceModel.objects.order_by('sortid')
loginForms = LoginForm()
reqCtx = RequestContext(req,{})
return render(req,'index.html',{'homeShowList':homeShowList,'loginForms':loginForms})
def aboutus(req):
return render(req,'about.html',{})
def ourStory(req):
return render(req,'our_story.html',{})
def menu(req):
return render(req,'menu.html',{})
def order(req):
return render(req,'shopping_cart_step_1.html',{})
def shop_step_one(req):
return render(req,'shopping_cart_step_1.html',{})
def shop_step_two(req):
return render(req,'shopping_cart_step_2.html',{})
def shop_step_three(req):
return render(req,'shopping_cart_step_3.html',{})
def shop(req):
return render(req,'shop.html',{})
def location(req):
return render(req,'locations.html',{})
def contact(req):
return render(req,'contact.html',{})
def cf_login(req):
if req.method == 'GET':
form = LoginForm()
return render(req, 'login.html', {'form': form})
if req.method == 'POST':
form = LoginForm(req.POST)
if form.is_valid():
username = form.cleaned_data['uid']
password = form.cleaned_data['pwd']
user = authenticate(username=username, password=password)
if user is not None:
login(req, user)
print('login Success')
url = req.POST.get('', '/index')
return redirect(url)
else:
print("出错了")
return render(req, 'login.html', {'form': form, 'error': "用户名或者密码错误"})
else:
return render(req, 'login.html', {'form': form})
return render(req,'login.html',{})
def cf_logout(req):
url = req.POST.get('','/index')
logout(req)
return redirect(url)
def cf_register(req):
error_msg = None
if req.method == 'GET':
form = RegisterForm()
return render(req,'register.html',{'form':form})
if req.method == 'POST':
form = RegisterForm(req.POST)
if form.is_valid():
username = form.cleaned_data['uname']
email = form.cleaned_data['email']
return render(req, 'register.html', {'form': form})
else:
pass
return render(req,'register.html',{"error_msg":"error","form":form})
def register_yanzheng(req):
type = req.GET.get('type')
yz_text = req.GET.get("text")
form = RegisterForm()
if type == 'phone':
# 验证手机号
try:
user = NewUser.objects.get(phonenum=yz_text)
except ObjectDoesNotExist:
data = {"flag": 1, "msg": "可以使用"}
return JsonResponse({"callback": data})
else:
data = {"flag": 0, "msg": "该手机号码已被注册"}
return JsonResponse({"callback": data})
elif type == 'uname':
try:
user = NewUser.objects.get(username=yz_text)
except ObjectDoesNotExist:
data = {"flag": 1, 'msg': "可以使用"}
return JsonResponse({"callback": data})
else:
data = {"flag": 0, "msg": "该账号已被注册"}
return JsonResponse({"callback": data})
else:
print('???')
# return render(req, 'register.html', {"error_msg": "error", "form": form})
@csrf_exempt
def register_submit(req):
username = req.POST['username']
pwd = req.POST['pwd']
emial = req.POST['email']
phone = req.POST['phone']
c_user = NewUser()
c_user.username = username
c_user.phonenum = phone
c_user.email = emial
c_user.password = pwd
c_user.save()
bData = {"flag": 1, "msg": "success"}
return JsonResponse({"callback":bData})
def yanzhengWithType(type,text,repwd):
if type == 'uname':
if len(text) <5 or len(text) > 12:
return (False,'请输入5-12位用户名')
user = NewUser.objects.get(username=text)
if(user):
return (False,'该用户已经存在')
if type == 'email':
regexStr = r"[\w!#$%&'*+/=?^_`{|}~-]+(?:\.[\w!#$%&'*+/=?^_`{|}~-]+)*@(?:[\w](?:[\w-]*[\w])?\.)+[\w](?:[\w-]*[\w])?"
result = re.match(regexStr,text)
if result == False:
return (False,"邮箱地址不正确")
if type == 'pwd':
if len(text) <6 or len(text) > 18:
return (False,'请输入6-18位密码')
elif (text != repwd):
return (False,"两次密码不同")
if type == "phone":
regexStr = r"1\d{10}"
result = re.match(regexStr, text)
if result == False:
return (False, "手机号码格式不正确")
user = NewUser.objects.get(phonenum=text)
if(user):
return (False,"该手机号码已存在")
return (True,"Success")
|
{"/cfjapp/views.py": ["/cfjapp/forms.py", "/cfjapp/models.py"], "/cfjpjc/urls.py": ["/cfjapp/views.py"], "/cfjapp/forms.py": ["/cfjapp/models.py"], "/cfjapp/admin.py": ["/cfjapp/models.py"]}
|
23,205,061
|
qikai521/cfjpjc
|
refs/heads/master
|
/cfjapp/models.py
|
from django.db import models
from django.contrib.auth.models import User
from django.utils.encoding import python_2_unicode_compatible
from django.utils import timezone
from django.contrib.auth.models import AbstractUser
# Create your models here.
class Recive_Adress(models.Model):
name = models.CharField(max_length=63)
phone = models.IntegerField(default=0)
address = models.CharField(max_length=255)
class Meta:
verbose_name = '收货地址'
@python_2_unicode_compatible
class NewUser(AbstractUser):
phonenum = models.IntegerField(default=0)
address = models.CharField(max_length=255,default='')
reviceInfo = models.ForeignKey(Recive_Adress,blank=True, null=True)
def __str__(self):
return self.username
class PgroupModel(models.Model):
name = models.CharField(max_length=126)
def __str__(self):
return self.name
class Meta:
verbose_name = "类别"
verbose_name_plural = "类别"
class ProduceModel(models.Model):
name = models.CharField(max_length=126,default='长丰肉食')
price = models.FloatField(default=0.0)
imgURL = models.CharField(max_length=256)
sortid = models.IntegerField(unique=True,db_index=True,blank=None)
group = models.ForeignKey(PgroupModel)
def __str__(self):
return self.name
class Meta:
verbose_name = "商品名"
verbose_name_plural = "商品名"
|
{"/cfjapp/views.py": ["/cfjapp/forms.py", "/cfjapp/models.py"], "/cfjpjc/urls.py": ["/cfjapp/views.py"], "/cfjapp/forms.py": ["/cfjapp/models.py"], "/cfjapp/admin.py": ["/cfjapp/models.py"]}
|
23,205,062
|
qikai521/cfjpjc
|
refs/heads/master
|
/cfjpjc/urls.py
|
from django.conf.urls import url,include
from django.contrib import admin
from cfjapp.views import index,aboutus,ourStory,menu,order,location,shop,contact,shop_step_one,shop_step_three,shop_step_two,cf_login,cf_logout,cf_register,register_yanzheng,register_submit
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^$',index),
url(r'^index',index),
url(r'^about',aboutus),
url(r'^our_story',ourStory),
url(r'^menu',menu),
url(r'^shopping_cart_step_1',shop_step_one),
url(r'^shopping_cart_step_2',shop_step_two),
url(r'^shopping_cart_step_3',shop_step_three),
url(r'^locations',location),
url(r'^shop',shop),
url(r'^contact',contact),
url(r'^login',cf_login),
url(r'^logout', cf_logout),
url(r'^register', cf_register),
url(r'^yanzheng',register_yanzheng),
url(r'^submit',register_submit),
]
|
{"/cfjapp/views.py": ["/cfjapp/forms.py", "/cfjapp/models.py"], "/cfjpjc/urls.py": ["/cfjapp/views.py"], "/cfjapp/forms.py": ["/cfjapp/models.py"], "/cfjapp/admin.py": ["/cfjapp/models.py"]}
|
23,205,063
|
qikai521/cfjpjc
|
refs/heads/master
|
/cfjapp/forms.py
|
from django import forms
from .models import User
from django.core.exceptions import ValidationError
import re
class LoginForm(forms.Form):
uid = forms.CharField(widget=forms.TextInput(attrs={'class':'login_form-control','id':'uid','placeholder':'账号/手机号'}))
pwd = forms.CharField(widget=forms.PasswordInput(attrs={'class':'login_form-control','id':'pwd','placeholder':'密码'}))
class RegisterForm(forms.Form):
uname = forms.CharField(widget=forms.TextInput(attrs={"class":"input_uanme useblur","id":"inputid_uname","placeholder":"请输入登录账号*","data-min":"5","data-max":"10","onblur":"checkWithType('uname')"},))
pwd = forms.CharField(widget=forms.PasswordInput(attrs={"class":"input_pwd useblur","id":"inputid_pwd","placeholder":"请输入密码*","data-match":"inputid_repwd","data-min":"5","data-max":"10","onblur":"checkWithType('pwd')"}))
repwd = forms.CharField(widget=forms.PasswordInput(attrs={"class":"input_repwd useblur","id":"inputid_repwd","placeholder":"重新输入密码*","data-match":"inputid_repwd","data-min":"5","data-max":"10","onblur":"checkWithType('repwd')"}))
email = forms.CharField(widget=forms.TextInput(attrs={"class":"input_email useblur","id":"inputid_email","placeholder":"请输入邮箱","data-type":"email","onblur":"checkWithType('email')"}))
phone = forms.CharField(widget=forms.TextInput(attrs={"class":"input_phone useblur","id":"inputid_phone","placeholder":"请输入手机号码*","onblur":"checkWithType('phone')"}))
code = forms.CharField(widget=forms.TextInput(attrs={"class":"input_code useblur","id":"inputid_code","placeholder":"输入验证码*","onblur":"checkWithType('code')"}))
|
{"/cfjapp/views.py": ["/cfjapp/forms.py", "/cfjapp/models.py"], "/cfjpjc/urls.py": ["/cfjapp/views.py"], "/cfjapp/forms.py": ["/cfjapp/models.py"], "/cfjapp/admin.py": ["/cfjapp/models.py"]}
|
23,205,064
|
qikai521/cfjpjc
|
refs/heads/master
|
/cfjapp/admin.py
|
from django.contrib import admin
from .models import NewUser,Recive_Adress,ProduceModel,PgroupModel
# Register your models here.
class NewUserAdmin(admin.ModelAdmin):
list_display = ('username','password','phonenum','address')
class ProduceAdmin(admin.ModelAdmin):
list_display = ('name','price','imgURL','sortid')
class PgroupModelAdmin(admin.ModelAdmin):
pass
admin.site.register(NewUser,NewUserAdmin)
admin.site.register(ProduceModel,ProduceAdmin)
admin.site.register(PgroupModel,PgroupModelAdmin)
|
{"/cfjapp/views.py": ["/cfjapp/forms.py", "/cfjapp/models.py"], "/cfjpjc/urls.py": ["/cfjapp/views.py"], "/cfjapp/forms.py": ["/cfjapp/models.py"], "/cfjapp/admin.py": ["/cfjapp/models.py"]}
|
23,283,689
|
alejojimenez/back-end-medi-dynamo
|
refs/heads/master
|
/app.py
|
import os
import re
from flask import Flask, jsonify, request
from flask_sqlalchemy import SQLAlchemy
from flask_script import Manager
from flask_migrate import Migrate, MigrateCommand
from flask_cors import CORS
from flask_bcrypt import Bcrypt
from flask_jwt_extended import JWTManager, jwt_required, create_access_token, get_jwt_identity
from models import User, db
BASEDIR = os.path.abspath(os.path.dirname(__file__))
app = Flask(__name__)
app.config["SQLALCHEMY_DATABASE_URI"] = "mysql://root:X3#stejen@127.0.0.1:3306/medidynamo"
#+ os.path.join(BASEDIR, "medidynamo.db")
app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False
app.config["DEBUG"] = True
app.config["ENV"] = "development"
app.config["SECRET_KEY"] = "secret_key"
app.config["JWT_SECRET_KEY"] = 'encrypt'
db.init_app(app)
Migrate(app, db)
manager = Manager(app)
manager.add_command("db", MigrateCommand)
jwt = JWTManager(app)
bcrypt = Bcrypt(app)
CORS(app)
@app.route('/signup', methods=["POST"])
def signup():
## Expresion regular para validar email ##
email_reg = '^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$'
## Expresion regular para validar una contraseña ##
password_reg = '^.*(?=.{8,})(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).*$'
## Instanciar un nuevo usuario ##
user = User()
## Chequear email que recibe del Front-End
if re.search(email_reg, request.json.get("email")):
user.email = request.json.get("email")
else:
return jsonify({"msg":"Formato del Correo Invalido"}), 401
## Chequear contraseña que recibe del Front-End
if re.search(password_reg, request.json.get("password")):
password_hash = bcrypt.generate_password_hash(request.json.get("password"))
user.password = password_hash
else:
return jsonify({"msg":"Formato del Password Invalido"}), 401
user.username = request.json.get("username", None)
user.name = request.json.get("name")
db.session.add(user)
db.session.commit()
return jsonify({"success":True})
@app.route('/login', methods=["POST"])
def login():
# Validar contenido del Front
if not request.is_json:
return jsonify({"msg":"El Contenido esta Vacio"}), 400
email = request.json.get("email", None)
password = request.json.get("password", None)
# Validar datos requeridos
if not email:
return jsonify({"msg":"Falta enviar el Correo"}), 400
if not password:
return jsonify({"msg":"Falta enviar el Password"}), 400
# Consulta tabla user
user = User.query.filter_by(email=email).first()
# Validar usuario
if user is None:
return jsonify({"msg":"Usuario no Registrado"}), 404
# Validar password
if bcrypt.check_password_hash(user.password, password):
access_token = create_access_token(identity=email)
return jsonify({
"access_token": access_token,
"user": user.serialize(),
"success":True
}), 200
else:
return jsonify({"msg": "Password Invalido"}), 400
if __name__ == "__main__":
manager.run()
|
{"/app.py": ["/models.py"]}
|
23,326,664
|
kush-singh-chb/FamilyCart
|
refs/heads/main
|
/models/UserModel.py
|
import os
from uuid import uuid4
import boto3
from passlib.hash import pbkdf2_sha256 as sha256
db = boto3.resource(service_name='dynamodb', region_name='eu-west-1',
aws_access_key_id=os.environ.get("aws_access_key_id"),
aws_secret_access_key=os.environ.get("aws_secret_access_key"))
class UserModel:
__tablename__ = 'users'
id = uuid4()
username: str
email: str
firstname: str
lastname: str
password: str
eir_code: str
orders = []
usercart: str
def save_to_db(self):
res = db.Table(UserModel.__tablename__).put_item(
Item={
'id': self.id,
'email': self.username[0],
'first_name': self.firstname,
'password': self.password,
'last_name': self.lastname,
'eir_code': self.eir_code,
'orders': self.orders,
'usercart': self.usercart
}
)
print(res)
@classmethod
def find_by_username(cls, username):
response = db.Table(UserModel.__tablename__).get_item(Key={
'username': username
})
user = UserModel()
user.username = response['Item']['username'],
user.password = response['Item']['password'],
user.firstname = response['Item']['first_name'],
return user
@staticmethod
def create_user_table():
try:
table = db.create_table(
TableName=UserModel.__tablename__,
KeySchema=[
{
'AttributeName': 'email',
'KeyType': 'HASH'
}
],
AttributeDefinitions=[
{
'AttributeName': 'email',
'AttributeType': 'S'
}
],
ProvisionedThroughput={
'ReadCapacityUnits': 5,
'WriteCapacityUnits': 5
}
)
# Wait until the table exists.
table.meta.client.get_waiter('table_exists').wait(TableName='users')
except Exception as e:
print(e)
pass
@classmethod
def check_by_username(cls, email):
response = db.Table(UserModel.__tablename__).get_item(Key={
'email': email,
})
return "Item" in response
@staticmethod
def generate_hash(password):
return sha256.hash(password)
@staticmethod
def verify_hash(password, hash):
return sha256.verify(password, hash[0])
|
{"/resources.py": ["/validation.py", "/models.py"], "/run.py": ["/models.py", "/resources.py", "/models/RevokedTokenModel.py", "/resources/UnderConstruction.py", "/resources/CheckService.py", "/resources/EthnicCategory.py", "/resources/MainRoute.py", "/resources/UserLogin.py", "/resources/UserLogoutAccess.py", "/resources/UserLogoutRefresh.py", "/resources/UserRegistration.py"], "/resources/EthnicCategory.py": ["/validation.py", "/models/EthinicCategoryModel.py"], "/resources/UserLogoutAccess.py": ["/models/RevokedTokenModel.py"], "/resources/UserLogin.py": ["/validation.py", "/models/UserModel.py"], "/resources/UserLogoutRefresh.py": ["/models/RevokedTokenModel.py"], "/resources/CheckService.py": ["/validation.py"], "/resources/UserRegistration.py": ["/validation.py", "/models/UserModel.py"]}
|
23,326,665
|
kush-singh-chb/FamilyCart
|
refs/heads/main
|
/resources/EthnicCategory.py
|
from datetime import datetime
from flask_restful import Resource
import validation
from models.EthinicCategoryModel import CategoryModel
class EthnicCategory(Resource):
def post(self):
data = validation.category_create_validate().parse_args()
category = CategoryModel()
category.name = data['name'].lower()
category.createdOn = datetime.now().isoformat()
try:
category.save_to_db()
return {'message': 'Created {}'.format(category.id)}, 201
except Exception as e:
return {'message': 'Unable to Create {}'.format(e)}, 400
def get(self):
categories = CategoryModel.get_categories()
return categories, 201
class EthnicCategoryByID(Resource):
def get(self, _id):
try:
response = CategoryModel.get_ethnic_category_by_id(_id)
return response, 201
except Exception as e:
return {'message': 'Server error {}'.format(e)}, 400
|
{"/resources.py": ["/validation.py", "/models.py"], "/run.py": ["/models.py", "/resources.py", "/models/RevokedTokenModel.py", "/resources/UnderConstruction.py", "/resources/CheckService.py", "/resources/EthnicCategory.py", "/resources/MainRoute.py", "/resources/UserLogin.py", "/resources/UserLogoutAccess.py", "/resources/UserLogoutRefresh.py", "/resources/UserRegistration.py"], "/resources/EthnicCategory.py": ["/validation.py", "/models/EthinicCategoryModel.py"], "/resources/UserLogoutAccess.py": ["/models/RevokedTokenModel.py"], "/resources/UserLogin.py": ["/validation.py", "/models/UserModel.py"], "/resources/UserLogoutRefresh.py": ["/models/RevokedTokenModel.py"], "/resources/CheckService.py": ["/validation.py"], "/resources/UserRegistration.py": ["/validation.py", "/models/UserModel.py"]}
|
23,326,666
|
kush-singh-chb/FamilyCart
|
refs/heads/main
|
/resources/UserLogoutAccess.py
|
from flask_jwt_extended import (jwt_required, get_raw_jwt)
from flask_restful import Resource
from models.RevokedTokenModel import RevokedTokenModel
class UserLogoutAccess(Resource):
@jwt_required
def post(self):
jti = get_raw_jwt()['jti']
try:
revoked_token = RevokedTokenModel()
revoked_token.jti = jti
revoked_token.add()
return {'message': 'Access token has been revoked'}
except:
return {'message': 'Something went wrong'}, 500
|
{"/resources.py": ["/validation.py", "/models.py"], "/run.py": ["/models.py", "/resources.py", "/models/RevokedTokenModel.py", "/resources/UnderConstruction.py", "/resources/CheckService.py", "/resources/EthnicCategory.py", "/resources/MainRoute.py", "/resources/UserLogin.py", "/resources/UserLogoutAccess.py", "/resources/UserLogoutRefresh.py", "/resources/UserRegistration.py"], "/resources/EthnicCategory.py": ["/validation.py", "/models/EthinicCategoryModel.py"], "/resources/UserLogoutAccess.py": ["/models/RevokedTokenModel.py"], "/resources/UserLogin.py": ["/validation.py", "/models/UserModel.py"], "/resources/UserLogoutRefresh.py": ["/models/RevokedTokenModel.py"], "/resources/CheckService.py": ["/validation.py"], "/resources/UserRegistration.py": ["/validation.py", "/models/UserModel.py"]}
|
23,326,667
|
kush-singh-chb/FamilyCart
|
refs/heads/main
|
/resources/UserLogin.py
|
from flask_jwt_extended import (create_access_token, create_refresh_token)
from flask_restful import Resource
import validation
from models.UserModel import UserModel
from validation import login_validate
class UserLogin(Resource):
def post(self):
data = login_validate().parse_args()
if not validation.validate_eir(data['eircode']):
return {'message': 'Invalid eircode'}, 422
current_user = UserModel.find_by_username(data['email'])
if not current_user:
return {'message': 'User {} doesn\'t exist'.format(data['email'])}
if UserModel.verify_hash(data['password'], current_user.password):
access_token = create_access_token(identity=data['email'])
refresh_token = create_refresh_token(identity=data['email'])
return {
'message': 'Logged in as {}'.format(current_user.username[0]),
'access_token': access_token,
'refresh_token': refresh_token
}
else:
return {'message': 'Wrong credentials'}
|
{"/resources.py": ["/validation.py", "/models.py"], "/run.py": ["/models.py", "/resources.py", "/models/RevokedTokenModel.py", "/resources/UnderConstruction.py", "/resources/CheckService.py", "/resources/EthnicCategory.py", "/resources/MainRoute.py", "/resources/UserLogin.py", "/resources/UserLogoutAccess.py", "/resources/UserLogoutRefresh.py", "/resources/UserRegistration.py"], "/resources/EthnicCategory.py": ["/validation.py", "/models/EthinicCategoryModel.py"], "/resources/UserLogoutAccess.py": ["/models/RevokedTokenModel.py"], "/resources/UserLogin.py": ["/validation.py", "/models/UserModel.py"], "/resources/UserLogoutRefresh.py": ["/models/RevokedTokenModel.py"], "/resources/CheckService.py": ["/validation.py"], "/resources/UserRegistration.py": ["/validation.py", "/models/UserModel.py"]}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.