index int64 | repo_name string | branch_name string | path string | content string | import_graph string |
|---|---|---|---|---|---|
42,932 | jramcast/mgr-service | refs/heads/master | /mgr/infrastructure/models/deep/feed_forward/exporter.py | import os
import tensorflow as tf
from keras.models import Model as KerasModel
from keras import backend as K
from keras.layers import Input
from .layers import define_layers
def export():
inputs = Input(shape=(10, 128), name="embeddings")
outputs = define_layers(inputs)
model = KerasModel(inputs=inputs, outputs=outputs)
model.load_weights(get_model_file())
tf.saved_model.simple_save(
K.get_session(),
get_exported_path(),
inputs={'embeddings': model.input},
outputs={"genres": model.outputs[0]})
def get_model_file():
directory = os.path.dirname(os.path.abspath(__file__))
return os.path.join(directory, "weights", "unbal_deep_wt.h5")
def get_exported_path():
directory = os.path.dirname(os.path.abspath(__file__))
return os.path.join(directory, ".tfmodel", "1")
if __name__ == "__main__":
export()
| {"/mgr/infrastructure/models/deep/feed_forward/__init__.py": ["/mgr/infrastructure/models/deep/tensorflow.py"], "/mgr/usecases/classify.py": ["/mgr/usecases/interfaces.py", "/mgr/domain/entities.py"], "/mgr/infrastructure/audioset/vggish/cache/memory.py": ["/mgr/usecases/interfaces.py"], "/mgr/infrastructure/models/deep/lstm/layers.py": ["/mgr/infrastructure/audioset/ontology.py"], "/mgr/infrastructure/models/deep/feed_forward/exporter.py": ["/mgr/infrastructure/models/deep/feed_forward/layers.py"], "/mgr/infrastructure/models/naive_bayes/naivebayes.py": ["/mgr/usecases/interfaces.py", "/mgr/domain/entities.py", "/mgr/infrastructure/audioset/ontology.py", "/mgr/infrastructure/audioset/vggish/loader.py"], "/app.py": ["/mgr/infrastructure/server/flask.py", "/mgr/usecases/classify.py", "/mgr/infrastructure/models/naive_bayes/naivebayes.py", "/mgr/infrastructure/models/deep/feed_forward/__init__.py", "/mgr/infrastructure/models/deep/lstm/__init__.py", "/mgr/infrastructure/models/svm/svm.py", "/mgr/infrastructure/youtube.py", "/mgr/infrastructure/audioset/vggish/cache/memory.py", "/mgr/infrastructure/audioset/vggish/loader.py"], "/tests/unit/domain/entities_test.py": ["/mgr/domain/entities.py"], "/mgr/infrastructure/models/deep/feed_forward/layers.py": ["/mgr/infrastructure/audioset/ontology.py"], "/mgr/infrastructure/audioset/vggish/loader.py": ["/mgr/domain/entities.py", "/mgr/usecases/interfaces.py"], "/mgr/infrastructure/models/deep/lstm/__init__.py": ["/mgr/infrastructure/models/deep/tensorflow.py"], "/mgr/infrastructure/models/deep/tensorflow.py": ["/mgr/usecases/interfaces.py", "/mgr/infrastructure/audioset/vggish/loader.py", "/mgr/infrastructure/audioset/ontology.py"], "/mgr/usecases/interfaces.py": ["/mgr/domain/entities.py"], "/mgr/infrastructure/youtube.py": ["/mgr/usecases/interfaces.py", "/mgr/domain/entities.py"], "/tests/unit/usecases/classify_test.py": ["/mgr/usecases/interfaces.py", "/mgr/usecases/classify.py", "/mgr/domain/entities.py"], "/mgr/infrastructure/models/svm/svm.py": ["/mgr/usecases/interfaces.py", "/mgr/domain/entities.py", "/mgr/infrastructure/audioset/ontology.py", "/mgr/infrastructure/audioset/vggish/loader.py"]} |
42,933 | jramcast/mgr-service | refs/heads/master | /mgr/infrastructure/audioset/vggish/exporter.py |
import os
import tensorflow as tf
from mgr.infrastructure.audioset.vggish.model import vggish_slim
from mgr.infrastructure.audioset.vggish.model import vggish_params
flags = tf.app.flags
flags.DEFINE_string(
'wav_file', None,
'Path to a wav file. Should contain signed 16-bit PCM samples. '
'If none is provided, a synthetic sound is used.')
flags.DEFINE_string(
'checkpoint', 'data/vggish/vggish_model.ckpt',
'Path to the VGGish checkpoint file.')
FLAGS = flags.FLAGS
NUMBER_OF_SECONDS = 10
def export():
with tf.Graph().as_default(), tf.Session() as sess:
vggish_slim.define_vggish_slim(training=False)
vggish_slim.load_vggish_slim_checkpoint(sess, FLAGS.checkpoint)
features_tensor = sess.graph.get_tensor_by_name(
vggish_params.INPUT_TENSOR_NAME)
embedding_tensor = sess.graph.get_tensor_by_name(
vggish_params.OUTPUT_TENSOR_NAME)
embedding_tensor = resize_axis(
embedding_tensor,
axis=0,
new_size=NUMBER_OF_SECONDS)
tf.saved_model.simple_save(
sess,
get_exported_path(),
inputs={'features_tensor': features_tensor},
outputs={embedding_tensor.name: embedding_tensor})
def resize_axis(tensor, axis, new_size, fill_value=0):
"""
Function from YouTube-8m supporting code:
https://github.com/google/youtube-8m/blob/2c94ed449737c886175a5fff1bfba7eadc4de5ac/readers.py
Truncates or pads a tensor to new_size on on a given axis.
Truncate or extend tensor such that tensor.shape[axis] == new_size. If the
size increases, the padding will be performed at the end, using fill_value.
Args:
tensor: The tensor to be resized.
axis: An integer representing the dimension to be sliced.
new_size: An integer or 0d tensor representing the new value for
tensor.shape[axis].
fill_value: Value to use to fill any new entries in the tensor. Will be
cast to the type of tensor.
Returns:
The resized tensor.
"""
tensor = tf.convert_to_tensor(tensor)
shape = tf.unstack(tf.shape(tensor))
pad_shape = shape[:]
pad_shape[axis] = tf.maximum(0, new_size - shape[axis])
shape[axis] = tf.minimum(shape[axis], new_size)
shape = tf.stack(shape)
resized = tf.concat([
tf.slice(tensor, tf.zeros_like(shape), shape),
tf.fill(tf.stack(pad_shape), tf.cast(fill_value, tensor.dtype))
], axis)
# Update shape.
new_shape = tensor.get_shape().as_list() # A copy is being made.
new_shape[axis] = new_size
resized.set_shape(new_shape)
return resized
def get_exported_path():
directory = os.path.dirname(os.path.abspath(__file__))
return os.path.join(directory, ".tfmodel", "1")
if __name__ == "__main__":
export()
| {"/mgr/infrastructure/models/deep/feed_forward/__init__.py": ["/mgr/infrastructure/models/deep/tensorflow.py"], "/mgr/usecases/classify.py": ["/mgr/usecases/interfaces.py", "/mgr/domain/entities.py"], "/mgr/infrastructure/audioset/vggish/cache/memory.py": ["/mgr/usecases/interfaces.py"], "/mgr/infrastructure/models/deep/lstm/layers.py": ["/mgr/infrastructure/audioset/ontology.py"], "/mgr/infrastructure/models/deep/feed_forward/exporter.py": ["/mgr/infrastructure/models/deep/feed_forward/layers.py"], "/mgr/infrastructure/models/naive_bayes/naivebayes.py": ["/mgr/usecases/interfaces.py", "/mgr/domain/entities.py", "/mgr/infrastructure/audioset/ontology.py", "/mgr/infrastructure/audioset/vggish/loader.py"], "/app.py": ["/mgr/infrastructure/server/flask.py", "/mgr/usecases/classify.py", "/mgr/infrastructure/models/naive_bayes/naivebayes.py", "/mgr/infrastructure/models/deep/feed_forward/__init__.py", "/mgr/infrastructure/models/deep/lstm/__init__.py", "/mgr/infrastructure/models/svm/svm.py", "/mgr/infrastructure/youtube.py", "/mgr/infrastructure/audioset/vggish/cache/memory.py", "/mgr/infrastructure/audioset/vggish/loader.py"], "/tests/unit/domain/entities_test.py": ["/mgr/domain/entities.py"], "/mgr/infrastructure/models/deep/feed_forward/layers.py": ["/mgr/infrastructure/audioset/ontology.py"], "/mgr/infrastructure/audioset/vggish/loader.py": ["/mgr/domain/entities.py", "/mgr/usecases/interfaces.py"], "/mgr/infrastructure/models/deep/lstm/__init__.py": ["/mgr/infrastructure/models/deep/tensorflow.py"], "/mgr/infrastructure/models/deep/tensorflow.py": ["/mgr/usecases/interfaces.py", "/mgr/infrastructure/audioset/vggish/loader.py", "/mgr/infrastructure/audioset/ontology.py"], "/mgr/usecases/interfaces.py": ["/mgr/domain/entities.py"], "/mgr/infrastructure/youtube.py": ["/mgr/usecases/interfaces.py", "/mgr/domain/entities.py"], "/tests/unit/usecases/classify_test.py": ["/mgr/usecases/interfaces.py", "/mgr/usecases/classify.py", "/mgr/domain/entities.py"], "/mgr/infrastructure/models/svm/svm.py": ["/mgr/usecases/interfaces.py", "/mgr/domain/entities.py", "/mgr/infrastructure/audioset/ontology.py", "/mgr/infrastructure/audioset/vggish/loader.py"]} |
42,934 | jramcast/mgr-service | refs/heads/master | /mgr/infrastructure/audioset/ontology.py | import os
import csv
import json
dirname = os.path.dirname(os.path.abspath(__file__))
labels_file_path = os.path.join(dirname, 'class_labels_indices.csv')
ontology_file_path = os.path.join(dirname, 'ontology.json')
def read_classlabels_file():
with open(labels_file_path, newline='') as csvfile:
labels_reader = csv.DictReader(csvfile)
return list(labels_reader)
def read_ontology_file():
with open(ontology_file_path) as jsonstring:
return json.load(jsonstring)
classlabels = read_classlabels_file()
ontology = read_ontology_file()
def find_entity_by_name(name):
return next(entity for entity in ontology if entity['name'] == name)
def find_all_from_name(name):
entity = find_entity_by_name(name)
entityid = entity['id']
return traverse_ontology(entityid)
def find_children(name, drop_parent=True):
music_classes = find_all_from_name(name)
# Remove the root class
if drop_parent:
music_classes = music_classes[1:]
# Only select classes present in the dataset (not abstract)
def add_index_to_class(c):
c['index'] = get_entity_class_index(c['id'])
return c
music_classes = [add_index_to_class(c) for c in music_classes]
music_classes = [c for c in music_classes if c['index']]
return music_classes
def traverse_ontology(root_entity_id):
entity = find_entity(root_entity_id)
child_ids = entity['child_ids']
entities = [entity]
for id in child_ids:
entities += traverse_ontology(id)
return entities
def find_entity(entity_id):
return next(entity for entity in ontology if entity['id'] == entity_id)
def get_entity_class_index(entity_id):
try:
classlabel = next(cl for cl in classlabels if cl['mid'] == entity_id)
index = int(classlabel['index'])
except StopIteration:
index = None
return index
NUM_TOTAL_CLASSES = 527
MUSIC_GENRE_CLASSES = find_children('Music genre')
| {"/mgr/infrastructure/models/deep/feed_forward/__init__.py": ["/mgr/infrastructure/models/deep/tensorflow.py"], "/mgr/usecases/classify.py": ["/mgr/usecases/interfaces.py", "/mgr/domain/entities.py"], "/mgr/infrastructure/audioset/vggish/cache/memory.py": ["/mgr/usecases/interfaces.py"], "/mgr/infrastructure/models/deep/lstm/layers.py": ["/mgr/infrastructure/audioset/ontology.py"], "/mgr/infrastructure/models/deep/feed_forward/exporter.py": ["/mgr/infrastructure/models/deep/feed_forward/layers.py"], "/mgr/infrastructure/models/naive_bayes/naivebayes.py": ["/mgr/usecases/interfaces.py", "/mgr/domain/entities.py", "/mgr/infrastructure/audioset/ontology.py", "/mgr/infrastructure/audioset/vggish/loader.py"], "/app.py": ["/mgr/infrastructure/server/flask.py", "/mgr/usecases/classify.py", "/mgr/infrastructure/models/naive_bayes/naivebayes.py", "/mgr/infrastructure/models/deep/feed_forward/__init__.py", "/mgr/infrastructure/models/deep/lstm/__init__.py", "/mgr/infrastructure/models/svm/svm.py", "/mgr/infrastructure/youtube.py", "/mgr/infrastructure/audioset/vggish/cache/memory.py", "/mgr/infrastructure/audioset/vggish/loader.py"], "/tests/unit/domain/entities_test.py": ["/mgr/domain/entities.py"], "/mgr/infrastructure/models/deep/feed_forward/layers.py": ["/mgr/infrastructure/audioset/ontology.py"], "/mgr/infrastructure/audioset/vggish/loader.py": ["/mgr/domain/entities.py", "/mgr/usecases/interfaces.py"], "/mgr/infrastructure/models/deep/lstm/__init__.py": ["/mgr/infrastructure/models/deep/tensorflow.py"], "/mgr/infrastructure/models/deep/tensorflow.py": ["/mgr/usecases/interfaces.py", "/mgr/infrastructure/audioset/vggish/loader.py", "/mgr/infrastructure/audioset/ontology.py"], "/mgr/usecases/interfaces.py": ["/mgr/domain/entities.py"], "/mgr/infrastructure/youtube.py": ["/mgr/usecases/interfaces.py", "/mgr/domain/entities.py"], "/tests/unit/usecases/classify_test.py": ["/mgr/usecases/interfaces.py", "/mgr/usecases/classify.py", "/mgr/domain/entities.py"], "/mgr/infrastructure/models/svm/svm.py": ["/mgr/usecases/interfaces.py", "/mgr/domain/entities.py", "/mgr/infrastructure/audioset/ontology.py", "/mgr/infrastructure/audioset/vggish/loader.py"]} |
42,935 | jramcast/mgr-service | refs/heads/master | /mgr/infrastructure/models/naive_bayes/naivebayes.py | import joblib
import numpy as np
from typing import List
from dataclasses import dataclass
from mgr.usecases.interfaces import Model
from mgr.domain.entities import Prediction, AudioSegment
from mgr.infrastructure.audioset.ontology import MUSIC_GENRE_CLASSES
from mgr.infrastructure.audioset.vggish.loader import EmbeddingsLoader
@dataclass
class NaiveBayesInputFeatures():
pass
class NaiveBayesModel(Model):
def __init__(self, embeddings_loader: EmbeddingsLoader):
model_file = "./mgr/infrastructure/models/naive_bayes/bal_bayes.joblib"
self.model = joblib.load(model_file)
self.embeddings_loader = embeddings_loader
def preprocess(self, segments: List[AudioSegment]):
# At this point, both the full clip and
# its segments are supossed to be downloaded
embeddings = self.embeddings_loader.load_from_segments(segments)
x = np.array(embeddings)
x = x.reshape(x.shape[0], 1280)
return x
# return x.reshape(-1, 1280)
def classify(
self, features: NaiveBayesInputFeatures
) -> List[List[Prediction]]:
"""
Returns a list of list of predictions
The first list is the list of samples(segments)
The second list is the list of labels for each segment
"""
result = self.model.predict_proba(features)
predictions = []
for i, record in enumerate(result):
segment_predictions = []
predictions.append(segment_predictions)
for j, prediction in enumerate(record):
segment_predictions.append(Prediction(
MUSIC_GENRE_CLASSES[j]["name"],
result[i][j]
))
return predictions
| {"/mgr/infrastructure/models/deep/feed_forward/__init__.py": ["/mgr/infrastructure/models/deep/tensorflow.py"], "/mgr/usecases/classify.py": ["/mgr/usecases/interfaces.py", "/mgr/domain/entities.py"], "/mgr/infrastructure/audioset/vggish/cache/memory.py": ["/mgr/usecases/interfaces.py"], "/mgr/infrastructure/models/deep/lstm/layers.py": ["/mgr/infrastructure/audioset/ontology.py"], "/mgr/infrastructure/models/deep/feed_forward/exporter.py": ["/mgr/infrastructure/models/deep/feed_forward/layers.py"], "/mgr/infrastructure/models/naive_bayes/naivebayes.py": ["/mgr/usecases/interfaces.py", "/mgr/domain/entities.py", "/mgr/infrastructure/audioset/ontology.py", "/mgr/infrastructure/audioset/vggish/loader.py"], "/app.py": ["/mgr/infrastructure/server/flask.py", "/mgr/usecases/classify.py", "/mgr/infrastructure/models/naive_bayes/naivebayes.py", "/mgr/infrastructure/models/deep/feed_forward/__init__.py", "/mgr/infrastructure/models/deep/lstm/__init__.py", "/mgr/infrastructure/models/svm/svm.py", "/mgr/infrastructure/youtube.py", "/mgr/infrastructure/audioset/vggish/cache/memory.py", "/mgr/infrastructure/audioset/vggish/loader.py"], "/tests/unit/domain/entities_test.py": ["/mgr/domain/entities.py"], "/mgr/infrastructure/models/deep/feed_forward/layers.py": ["/mgr/infrastructure/audioset/ontology.py"], "/mgr/infrastructure/audioset/vggish/loader.py": ["/mgr/domain/entities.py", "/mgr/usecases/interfaces.py"], "/mgr/infrastructure/models/deep/lstm/__init__.py": ["/mgr/infrastructure/models/deep/tensorflow.py"], "/mgr/infrastructure/models/deep/tensorflow.py": ["/mgr/usecases/interfaces.py", "/mgr/infrastructure/audioset/vggish/loader.py", "/mgr/infrastructure/audioset/ontology.py"], "/mgr/usecases/interfaces.py": ["/mgr/domain/entities.py"], "/mgr/infrastructure/youtube.py": ["/mgr/usecases/interfaces.py", "/mgr/domain/entities.py"], "/tests/unit/usecases/classify_test.py": ["/mgr/usecases/interfaces.py", "/mgr/usecases/classify.py", "/mgr/domain/entities.py"], "/mgr/infrastructure/models/svm/svm.py": ["/mgr/usecases/interfaces.py", "/mgr/domain/entities.py", "/mgr/infrastructure/audioset/ontology.py", "/mgr/infrastructure/audioset/vggish/loader.py"]} |
42,936 | jramcast/mgr-service | refs/heads/master | /app.py | import os
import sys
import logging
from mgr.infrastructure.server.flask import Server
from mgr.usecases.classify import ClassifyUseCase
from mgr.infrastructure.models.naive_bayes.naivebayes import NaiveBayesModel
from mgr.infrastructure.models.deep.feed_forward import FeedForwardNetworkModel
from mgr.infrastructure.models.deep.lstm import LSTMRecurrentNeuralNetwork
from mgr.infrastructure.models.svm.svm import SVMModel
from mgr.infrastructure.youtube import (
YoutubeAudioLoader, VideoInfoCacheInMemory)
from mgr.infrastructure.audioset.vggish.cache.memory import (
InMemoryFeaturesCache
)
from mgr.infrastructure.audioset.vggish.loader import EmbeddingsLoader
from flask import request
# Tensorflow serving urls
# Models in TF are served separately with TF Serving
VGGISH_PREDICT_URL = os.environ.get(
"VGGISH_PREDICT_URL",
"http://vggish:8501/v1/models/vggish:predict")
FFN_PREDICT_URL = os.environ.get(
"FFN_PREDICT_URL",
"http://ff_network:8501/v1/models/ff_network:predict")
RNN_PREDICT_URL = os.environ.get(
"RNN_PREDICT_URL",
"http://lstm_network:8501/v1/models/lstm_network:predict")
PROXIES = [proxy.strip() for proxy in os.environ.get("PROXIES", "").split(",")]
PROXIES = [proxy for proxy in PROXIES if proxy]
logger = logging.getLogger("mgr-service")
out_hdlr = logging.StreamHandler(sys.stdout)
out_hdlr.setFormatter(logging.Formatter('%(asctime)s %(message)s'))
out_hdlr.setLevel(logging.INFO)
logger.addHandler(out_hdlr)
logger.setLevel(os.environ.get("LOG_LEVEL", "INFO"))
features_cache = InMemoryFeaturesCache()
embeddings_loader = EmbeddingsLoader(VGGISH_PREDICT_URL, features_cache)
# Models to classify
models = [
NaiveBayesModel(embeddings_loader),
FeedForwardNetworkModel(FFN_PREDICT_URL, embeddings_loader),
LSTMRecurrentNeuralNetwork(RNN_PREDICT_URL, embeddings_loader),
SVMModel(embeddings_loader)
]
# Audio downloader
youtube_cache = VideoInfoCacheInMemory()
audio_downloader = YoutubeAudioLoader(youtube_cache, logger, PROXIES)
# Use case initialization
classify = ClassifyUseCase(models, audio_downloader)
# Server and routes defintion
server = Server()
@server.route("/segment/classify")
def route_segment_classify():
return classify.run(
request.args["clip"],
round(float(request.args["from"]))
)
# Flask needs to read the app variable to start
app = server.serve()
| {"/mgr/infrastructure/models/deep/feed_forward/__init__.py": ["/mgr/infrastructure/models/deep/tensorflow.py"], "/mgr/usecases/classify.py": ["/mgr/usecases/interfaces.py", "/mgr/domain/entities.py"], "/mgr/infrastructure/audioset/vggish/cache/memory.py": ["/mgr/usecases/interfaces.py"], "/mgr/infrastructure/models/deep/lstm/layers.py": ["/mgr/infrastructure/audioset/ontology.py"], "/mgr/infrastructure/models/deep/feed_forward/exporter.py": ["/mgr/infrastructure/models/deep/feed_forward/layers.py"], "/mgr/infrastructure/models/naive_bayes/naivebayes.py": ["/mgr/usecases/interfaces.py", "/mgr/domain/entities.py", "/mgr/infrastructure/audioset/ontology.py", "/mgr/infrastructure/audioset/vggish/loader.py"], "/app.py": ["/mgr/infrastructure/server/flask.py", "/mgr/usecases/classify.py", "/mgr/infrastructure/models/naive_bayes/naivebayes.py", "/mgr/infrastructure/models/deep/feed_forward/__init__.py", "/mgr/infrastructure/models/deep/lstm/__init__.py", "/mgr/infrastructure/models/svm/svm.py", "/mgr/infrastructure/youtube.py", "/mgr/infrastructure/audioset/vggish/cache/memory.py", "/mgr/infrastructure/audioset/vggish/loader.py"], "/tests/unit/domain/entities_test.py": ["/mgr/domain/entities.py"], "/mgr/infrastructure/models/deep/feed_forward/layers.py": ["/mgr/infrastructure/audioset/ontology.py"], "/mgr/infrastructure/audioset/vggish/loader.py": ["/mgr/domain/entities.py", "/mgr/usecases/interfaces.py"], "/mgr/infrastructure/models/deep/lstm/__init__.py": ["/mgr/infrastructure/models/deep/tensorflow.py"], "/mgr/infrastructure/models/deep/tensorflow.py": ["/mgr/usecases/interfaces.py", "/mgr/infrastructure/audioset/vggish/loader.py", "/mgr/infrastructure/audioset/ontology.py"], "/mgr/usecases/interfaces.py": ["/mgr/domain/entities.py"], "/mgr/infrastructure/youtube.py": ["/mgr/usecases/interfaces.py", "/mgr/domain/entities.py"], "/tests/unit/usecases/classify_test.py": ["/mgr/usecases/interfaces.py", "/mgr/usecases/classify.py", "/mgr/domain/entities.py"], "/mgr/infrastructure/models/svm/svm.py": ["/mgr/usecases/interfaces.py", "/mgr/domain/entities.py", "/mgr/infrastructure/audioset/ontology.py", "/mgr/infrastructure/audioset/vggish/loader.py"]} |
42,937 | jramcast/mgr-service | refs/heads/master | /tests/unit/domain/entities_test.py | from mgr.domain.entities import AudioClip, AudioSegment
def test_audio_returns_the_right_number_of_segments():
length_seconds = 65
clip = AudioClip("test.wav", length_seconds)
assert len(clip.segments) == 7
def test_audio_returns_correct_segments():
length_seconds = 65
clip = AudioClip("test.wav", length_seconds)
assert clip.segments[0] == AudioSegment("test_000.wav", 0, 10)
assert clip.segments[1] == AudioSegment("test_001.wav", 10, 20)
assert clip.segments[6] == AudioSegment("test_006.wav", 60, 65)
| {"/mgr/infrastructure/models/deep/feed_forward/__init__.py": ["/mgr/infrastructure/models/deep/tensorflow.py"], "/mgr/usecases/classify.py": ["/mgr/usecases/interfaces.py", "/mgr/domain/entities.py"], "/mgr/infrastructure/audioset/vggish/cache/memory.py": ["/mgr/usecases/interfaces.py"], "/mgr/infrastructure/models/deep/lstm/layers.py": ["/mgr/infrastructure/audioset/ontology.py"], "/mgr/infrastructure/models/deep/feed_forward/exporter.py": ["/mgr/infrastructure/models/deep/feed_forward/layers.py"], "/mgr/infrastructure/models/naive_bayes/naivebayes.py": ["/mgr/usecases/interfaces.py", "/mgr/domain/entities.py", "/mgr/infrastructure/audioset/ontology.py", "/mgr/infrastructure/audioset/vggish/loader.py"], "/app.py": ["/mgr/infrastructure/server/flask.py", "/mgr/usecases/classify.py", "/mgr/infrastructure/models/naive_bayes/naivebayes.py", "/mgr/infrastructure/models/deep/feed_forward/__init__.py", "/mgr/infrastructure/models/deep/lstm/__init__.py", "/mgr/infrastructure/models/svm/svm.py", "/mgr/infrastructure/youtube.py", "/mgr/infrastructure/audioset/vggish/cache/memory.py", "/mgr/infrastructure/audioset/vggish/loader.py"], "/tests/unit/domain/entities_test.py": ["/mgr/domain/entities.py"], "/mgr/infrastructure/models/deep/feed_forward/layers.py": ["/mgr/infrastructure/audioset/ontology.py"], "/mgr/infrastructure/audioset/vggish/loader.py": ["/mgr/domain/entities.py", "/mgr/usecases/interfaces.py"], "/mgr/infrastructure/models/deep/lstm/__init__.py": ["/mgr/infrastructure/models/deep/tensorflow.py"], "/mgr/infrastructure/models/deep/tensorflow.py": ["/mgr/usecases/interfaces.py", "/mgr/infrastructure/audioset/vggish/loader.py", "/mgr/infrastructure/audioset/ontology.py"], "/mgr/usecases/interfaces.py": ["/mgr/domain/entities.py"], "/mgr/infrastructure/youtube.py": ["/mgr/usecases/interfaces.py", "/mgr/domain/entities.py"], "/tests/unit/usecases/classify_test.py": ["/mgr/usecases/interfaces.py", "/mgr/usecases/classify.py", "/mgr/domain/entities.py"], "/mgr/infrastructure/models/svm/svm.py": ["/mgr/usecases/interfaces.py", "/mgr/domain/entities.py", "/mgr/infrastructure/audioset/ontology.py", "/mgr/infrastructure/audioset/vggish/loader.py"]} |
42,938 | jramcast/mgr-service | refs/heads/master | /mgr/infrastructure/models/deep/feed_forward/layers.py | from keras.layers import (Activation, BatchNormalization, Dense, Dropout,
Flatten)
from mgr.infrastructure.audioset.ontology import MUSIC_GENRE_CLASSES
num_units = 768
drop_rate = 0.5
def define_layers(input):
# The input layer flattens the 10 seconds as a single dimension of 1280
reshape = Flatten(input_shape=(-1, 10, 128))(input)
l1 = Dense((num_units))(reshape)
l1 = BatchNormalization()(l1)
l1 = Activation('relu')(l1)
l1 = Dropout(drop_rate)(l1)
l2 = Dense(num_units)(l1)
l2 = BatchNormalization()(l2)
l2 = Activation('relu')(l2)
l2 = Dropout(drop_rate)(l2)
classes_num = len(MUSIC_GENRE_CLASSES)
output_layer = Dense(classes_num, activation='sigmoid')(l2)
return output_layer
| {"/mgr/infrastructure/models/deep/feed_forward/__init__.py": ["/mgr/infrastructure/models/deep/tensorflow.py"], "/mgr/usecases/classify.py": ["/mgr/usecases/interfaces.py", "/mgr/domain/entities.py"], "/mgr/infrastructure/audioset/vggish/cache/memory.py": ["/mgr/usecases/interfaces.py"], "/mgr/infrastructure/models/deep/lstm/layers.py": ["/mgr/infrastructure/audioset/ontology.py"], "/mgr/infrastructure/models/deep/feed_forward/exporter.py": ["/mgr/infrastructure/models/deep/feed_forward/layers.py"], "/mgr/infrastructure/models/naive_bayes/naivebayes.py": ["/mgr/usecases/interfaces.py", "/mgr/domain/entities.py", "/mgr/infrastructure/audioset/ontology.py", "/mgr/infrastructure/audioset/vggish/loader.py"], "/app.py": ["/mgr/infrastructure/server/flask.py", "/mgr/usecases/classify.py", "/mgr/infrastructure/models/naive_bayes/naivebayes.py", "/mgr/infrastructure/models/deep/feed_forward/__init__.py", "/mgr/infrastructure/models/deep/lstm/__init__.py", "/mgr/infrastructure/models/svm/svm.py", "/mgr/infrastructure/youtube.py", "/mgr/infrastructure/audioset/vggish/cache/memory.py", "/mgr/infrastructure/audioset/vggish/loader.py"], "/tests/unit/domain/entities_test.py": ["/mgr/domain/entities.py"], "/mgr/infrastructure/models/deep/feed_forward/layers.py": ["/mgr/infrastructure/audioset/ontology.py"], "/mgr/infrastructure/audioset/vggish/loader.py": ["/mgr/domain/entities.py", "/mgr/usecases/interfaces.py"], "/mgr/infrastructure/models/deep/lstm/__init__.py": ["/mgr/infrastructure/models/deep/tensorflow.py"], "/mgr/infrastructure/models/deep/tensorflow.py": ["/mgr/usecases/interfaces.py", "/mgr/infrastructure/audioset/vggish/loader.py", "/mgr/infrastructure/audioset/ontology.py"], "/mgr/usecases/interfaces.py": ["/mgr/domain/entities.py"], "/mgr/infrastructure/youtube.py": ["/mgr/usecases/interfaces.py", "/mgr/domain/entities.py"], "/tests/unit/usecases/classify_test.py": ["/mgr/usecases/interfaces.py", "/mgr/usecases/classify.py", "/mgr/domain/entities.py"], "/mgr/infrastructure/models/svm/svm.py": ["/mgr/usecases/interfaces.py", "/mgr/domain/entities.py", "/mgr/infrastructure/audioset/ontology.py", "/mgr/infrastructure/audioset/vggish/loader.py"]} |
42,939 | jramcast/mgr-service | refs/heads/master | /mgr/infrastructure/audioset/vggish/loader.py | import json
from typing import List
import requests
import numpy as np
from mgr.domain.entities import AudioSegment
from mgr.usecases.interfaces import FeaturesCache
from .model.vggish_postprocess import Postprocessor
from .model.vggish_input import wavfile_to_examples
class EmbeddingsLoader:
"""
Loads extracted embeddings from a list of audio segments
"""
def __init__(
self,
model_service_url: str,
cache: FeaturesCache
):
self.model_service_url = model_service_url
self.cache = cache
self.pproc = Postprocessor(
"data/vggish/vggish_pca_params.npz"
)
def load_from_segments(self, segments: List[AudioSegment]) -> List:
features = []
for segment in segments:
if segment.filename in self.cache:
segment_features = self.cache.get(segment.filename)
print("Embeddings extracted from cache (HIT)")
else:
segment_features = self.extract_embeddings(segment.filename)
self.cache.set(segment.filename, segment_features)
print("Embeddings extracted from VGGISH (MISS)")
features.append(segment_features)
return features
def extract_embeddings(self, filename):
example_batch = wavfile_to_examples(filename)
payload = json.dumps({"instances": example_batch.tolist()})
r = requests.post(
self.model_service_url,
data=payload,
headers={"content-type": "application/json"}
)
result = json.loads(r.text)['predictions']
postprocessed_batch = self.pproc.postprocess(np.array(result))
return np.array(postprocessed_batch)
| {"/mgr/infrastructure/models/deep/feed_forward/__init__.py": ["/mgr/infrastructure/models/deep/tensorflow.py"], "/mgr/usecases/classify.py": ["/mgr/usecases/interfaces.py", "/mgr/domain/entities.py"], "/mgr/infrastructure/audioset/vggish/cache/memory.py": ["/mgr/usecases/interfaces.py"], "/mgr/infrastructure/models/deep/lstm/layers.py": ["/mgr/infrastructure/audioset/ontology.py"], "/mgr/infrastructure/models/deep/feed_forward/exporter.py": ["/mgr/infrastructure/models/deep/feed_forward/layers.py"], "/mgr/infrastructure/models/naive_bayes/naivebayes.py": ["/mgr/usecases/interfaces.py", "/mgr/domain/entities.py", "/mgr/infrastructure/audioset/ontology.py", "/mgr/infrastructure/audioset/vggish/loader.py"], "/app.py": ["/mgr/infrastructure/server/flask.py", "/mgr/usecases/classify.py", "/mgr/infrastructure/models/naive_bayes/naivebayes.py", "/mgr/infrastructure/models/deep/feed_forward/__init__.py", "/mgr/infrastructure/models/deep/lstm/__init__.py", "/mgr/infrastructure/models/svm/svm.py", "/mgr/infrastructure/youtube.py", "/mgr/infrastructure/audioset/vggish/cache/memory.py", "/mgr/infrastructure/audioset/vggish/loader.py"], "/tests/unit/domain/entities_test.py": ["/mgr/domain/entities.py"], "/mgr/infrastructure/models/deep/feed_forward/layers.py": ["/mgr/infrastructure/audioset/ontology.py"], "/mgr/infrastructure/audioset/vggish/loader.py": ["/mgr/domain/entities.py", "/mgr/usecases/interfaces.py"], "/mgr/infrastructure/models/deep/lstm/__init__.py": ["/mgr/infrastructure/models/deep/tensorflow.py"], "/mgr/infrastructure/models/deep/tensorflow.py": ["/mgr/usecases/interfaces.py", "/mgr/infrastructure/audioset/vggish/loader.py", "/mgr/infrastructure/audioset/ontology.py"], "/mgr/usecases/interfaces.py": ["/mgr/domain/entities.py"], "/mgr/infrastructure/youtube.py": ["/mgr/usecases/interfaces.py", "/mgr/domain/entities.py"], "/tests/unit/usecases/classify_test.py": ["/mgr/usecases/interfaces.py", "/mgr/usecases/classify.py", "/mgr/domain/entities.py"], "/mgr/infrastructure/models/svm/svm.py": ["/mgr/usecases/interfaces.py", "/mgr/domain/entities.py", "/mgr/infrastructure/audioset/ontology.py", "/mgr/infrastructure/audioset/vggish/loader.py"]} |
42,940 | jramcast/mgr-service | refs/heads/master | /mgr/infrastructure/models/deep/lstm/__init__.py | from ..tensorflow import TensorFlowServingModelClient
class LSTMRecurrentNeuralNetwork(TensorFlowServingModelClient):
"""
Client to consume the LSTM model deployed with Tensorflow Serving
"""
pass
| {"/mgr/infrastructure/models/deep/feed_forward/__init__.py": ["/mgr/infrastructure/models/deep/tensorflow.py"], "/mgr/usecases/classify.py": ["/mgr/usecases/interfaces.py", "/mgr/domain/entities.py"], "/mgr/infrastructure/audioset/vggish/cache/memory.py": ["/mgr/usecases/interfaces.py"], "/mgr/infrastructure/models/deep/lstm/layers.py": ["/mgr/infrastructure/audioset/ontology.py"], "/mgr/infrastructure/models/deep/feed_forward/exporter.py": ["/mgr/infrastructure/models/deep/feed_forward/layers.py"], "/mgr/infrastructure/models/naive_bayes/naivebayes.py": ["/mgr/usecases/interfaces.py", "/mgr/domain/entities.py", "/mgr/infrastructure/audioset/ontology.py", "/mgr/infrastructure/audioset/vggish/loader.py"], "/app.py": ["/mgr/infrastructure/server/flask.py", "/mgr/usecases/classify.py", "/mgr/infrastructure/models/naive_bayes/naivebayes.py", "/mgr/infrastructure/models/deep/feed_forward/__init__.py", "/mgr/infrastructure/models/deep/lstm/__init__.py", "/mgr/infrastructure/models/svm/svm.py", "/mgr/infrastructure/youtube.py", "/mgr/infrastructure/audioset/vggish/cache/memory.py", "/mgr/infrastructure/audioset/vggish/loader.py"], "/tests/unit/domain/entities_test.py": ["/mgr/domain/entities.py"], "/mgr/infrastructure/models/deep/feed_forward/layers.py": ["/mgr/infrastructure/audioset/ontology.py"], "/mgr/infrastructure/audioset/vggish/loader.py": ["/mgr/domain/entities.py", "/mgr/usecases/interfaces.py"], "/mgr/infrastructure/models/deep/lstm/__init__.py": ["/mgr/infrastructure/models/deep/tensorflow.py"], "/mgr/infrastructure/models/deep/tensorflow.py": ["/mgr/usecases/interfaces.py", "/mgr/infrastructure/audioset/vggish/loader.py", "/mgr/infrastructure/audioset/ontology.py"], "/mgr/usecases/interfaces.py": ["/mgr/domain/entities.py"], "/mgr/infrastructure/youtube.py": ["/mgr/usecases/interfaces.py", "/mgr/domain/entities.py"], "/tests/unit/usecases/classify_test.py": ["/mgr/usecases/interfaces.py", "/mgr/usecases/classify.py", "/mgr/domain/entities.py"], "/mgr/infrastructure/models/svm/svm.py": ["/mgr/usecases/interfaces.py", "/mgr/domain/entities.py", "/mgr/infrastructure/audioset/ontology.py", "/mgr/infrastructure/audioset/vggish/loader.py"]} |
42,941 | jramcast/mgr-service | refs/heads/master | /mgr/infrastructure/models/deep/tensorflow.py | import json
from typing import List
import requests
import numpy as np
from mgr.usecases.interfaces import Model, AudioSegment, Prediction
from mgr.infrastructure.audioset.vggish.loader import EmbeddingsLoader
from mgr.infrastructure.audioset.ontology import MUSIC_GENRE_CLASSES
class TensorFlowServingModelClient(Model):
"""
Client class to consume models deployed with Tensorflow Serving
"""
def __init__(
self,
model_service_url: str,
embeddings_loader: EmbeddingsLoader
):
self.model_service_url = model_service_url
self.embeddings_loader = embeddings_loader
def preprocess(self, segments: List[AudioSegment]):
# At this point, both the full clip and its segments
# are supossed to be downloaded
embeddings = self.embeddings_loader.load_from_segments(segments)
x = np.array(embeddings)
return x
def classify(
self, embeddings: np.ndarray
) -> List[List[Prediction]]:
"""
Returns a list of list of predictions
The first list is the list of samples(segments)
The second list is the list of labels for each segment
"""
payload = json.dumps({"instances": embeddings.tolist()})
r = requests.post(
self.model_service_url,
data=payload,
headers={"content-type": "application/json"}
)
result = json.loads(r.text)['predictions']
predictions = []
for i, record in enumerate(result):
segment_predictions = []
predictions.append(segment_predictions)
for j, prediction in enumerate(record):
segment_predictions.append(Prediction(
MUSIC_GENRE_CLASSES[j]["name"],
result[i][j]
))
return predictions
| {"/mgr/infrastructure/models/deep/feed_forward/__init__.py": ["/mgr/infrastructure/models/deep/tensorflow.py"], "/mgr/usecases/classify.py": ["/mgr/usecases/interfaces.py", "/mgr/domain/entities.py"], "/mgr/infrastructure/audioset/vggish/cache/memory.py": ["/mgr/usecases/interfaces.py"], "/mgr/infrastructure/models/deep/lstm/layers.py": ["/mgr/infrastructure/audioset/ontology.py"], "/mgr/infrastructure/models/deep/feed_forward/exporter.py": ["/mgr/infrastructure/models/deep/feed_forward/layers.py"], "/mgr/infrastructure/models/naive_bayes/naivebayes.py": ["/mgr/usecases/interfaces.py", "/mgr/domain/entities.py", "/mgr/infrastructure/audioset/ontology.py", "/mgr/infrastructure/audioset/vggish/loader.py"], "/app.py": ["/mgr/infrastructure/server/flask.py", "/mgr/usecases/classify.py", "/mgr/infrastructure/models/naive_bayes/naivebayes.py", "/mgr/infrastructure/models/deep/feed_forward/__init__.py", "/mgr/infrastructure/models/deep/lstm/__init__.py", "/mgr/infrastructure/models/svm/svm.py", "/mgr/infrastructure/youtube.py", "/mgr/infrastructure/audioset/vggish/cache/memory.py", "/mgr/infrastructure/audioset/vggish/loader.py"], "/tests/unit/domain/entities_test.py": ["/mgr/domain/entities.py"], "/mgr/infrastructure/models/deep/feed_forward/layers.py": ["/mgr/infrastructure/audioset/ontology.py"], "/mgr/infrastructure/audioset/vggish/loader.py": ["/mgr/domain/entities.py", "/mgr/usecases/interfaces.py"], "/mgr/infrastructure/models/deep/lstm/__init__.py": ["/mgr/infrastructure/models/deep/tensorflow.py"], "/mgr/infrastructure/models/deep/tensorflow.py": ["/mgr/usecases/interfaces.py", "/mgr/infrastructure/audioset/vggish/loader.py", "/mgr/infrastructure/audioset/ontology.py"], "/mgr/usecases/interfaces.py": ["/mgr/domain/entities.py"], "/mgr/infrastructure/youtube.py": ["/mgr/usecases/interfaces.py", "/mgr/domain/entities.py"], "/tests/unit/usecases/classify_test.py": ["/mgr/usecases/interfaces.py", "/mgr/usecases/classify.py", "/mgr/domain/entities.py"], "/mgr/infrastructure/models/svm/svm.py": ["/mgr/usecases/interfaces.py", "/mgr/domain/entities.py", "/mgr/infrastructure/audioset/ontology.py", "/mgr/infrastructure/audioset/vggish/loader.py"]} |
42,942 | jramcast/mgr-service | refs/heads/master | /mgr/usecases/interfaces.py | import abc
from typing import List, TypeVar, Generic
from ..domain.entities import AudioClip, Prediction, AudioSegment
class Model(abc.ABC):
@property
def name(self):
return self.__class__.__name__
@abc.abstractclassmethod
def preprocess(self, segments: List[AudioSegment]):
raise NotImplementedError()
@abc.abstractmethod
def classify(self) -> List[List[Prediction]]:
raise NotImplementedError()
class AudioLoader(abc.ABC):
@abc.abstractmethod
def load(self, uri) -> AudioClip:
pass
@abc.abstractmethod
def load_segment(self, uri, from_second) -> AudioSegment:
pass
# Todo, have only 1 cache class
class FeaturesCache(abc.ABC):
@abc.abstractmethod
def get(self, key: str):
pass
@abc.abstractmethod
def set(self, key: str, entry):
pass
@abc.abstractmethod
def __contains__(self, key: str) -> bool:
pass
T = TypeVar('T')
class Cache(abc.ABC, Generic[T]):
@abc.abstractmethod
def get(self, key: str) -> T:
pass
@abc.abstractmethod
def set(self, key: str, entry: T):
pass
@abc.abstractmethod
def __contains__(self, key: str) -> bool:
pass
| {"/mgr/infrastructure/models/deep/feed_forward/__init__.py": ["/mgr/infrastructure/models/deep/tensorflow.py"], "/mgr/usecases/classify.py": ["/mgr/usecases/interfaces.py", "/mgr/domain/entities.py"], "/mgr/infrastructure/audioset/vggish/cache/memory.py": ["/mgr/usecases/interfaces.py"], "/mgr/infrastructure/models/deep/lstm/layers.py": ["/mgr/infrastructure/audioset/ontology.py"], "/mgr/infrastructure/models/deep/feed_forward/exporter.py": ["/mgr/infrastructure/models/deep/feed_forward/layers.py"], "/mgr/infrastructure/models/naive_bayes/naivebayes.py": ["/mgr/usecases/interfaces.py", "/mgr/domain/entities.py", "/mgr/infrastructure/audioset/ontology.py", "/mgr/infrastructure/audioset/vggish/loader.py"], "/app.py": ["/mgr/infrastructure/server/flask.py", "/mgr/usecases/classify.py", "/mgr/infrastructure/models/naive_bayes/naivebayes.py", "/mgr/infrastructure/models/deep/feed_forward/__init__.py", "/mgr/infrastructure/models/deep/lstm/__init__.py", "/mgr/infrastructure/models/svm/svm.py", "/mgr/infrastructure/youtube.py", "/mgr/infrastructure/audioset/vggish/cache/memory.py", "/mgr/infrastructure/audioset/vggish/loader.py"], "/tests/unit/domain/entities_test.py": ["/mgr/domain/entities.py"], "/mgr/infrastructure/models/deep/feed_forward/layers.py": ["/mgr/infrastructure/audioset/ontology.py"], "/mgr/infrastructure/audioset/vggish/loader.py": ["/mgr/domain/entities.py", "/mgr/usecases/interfaces.py"], "/mgr/infrastructure/models/deep/lstm/__init__.py": ["/mgr/infrastructure/models/deep/tensorflow.py"], "/mgr/infrastructure/models/deep/tensorflow.py": ["/mgr/usecases/interfaces.py", "/mgr/infrastructure/audioset/vggish/loader.py", "/mgr/infrastructure/audioset/ontology.py"], "/mgr/usecases/interfaces.py": ["/mgr/domain/entities.py"], "/mgr/infrastructure/youtube.py": ["/mgr/usecases/interfaces.py", "/mgr/domain/entities.py"], "/tests/unit/usecases/classify_test.py": ["/mgr/usecases/interfaces.py", "/mgr/usecases/classify.py", "/mgr/domain/entities.py"], "/mgr/infrastructure/models/svm/svm.py": ["/mgr/usecases/interfaces.py", "/mgr/domain/entities.py", "/mgr/infrastructure/audioset/ontology.py", "/mgr/infrastructure/audioset/vggish/loader.py"]} |
42,943 | jramcast/mgr-service | refs/heads/master | /mgr/infrastructure/youtube.py | import os
import logging
import subprocess as sp
from dataclasses import dataclass
from typing import List
import pafy
from ..usecases.interfaces import AudioLoader, Cache
from ..domain.entities import AudioClip, AudioSegment
@dataclass
class VideoInfo:
"""
Necessary info to download audio files
"""
id: str
audio_url: str
length: int
class YoutubeAudioLoader(AudioLoader):
logger: logging.Logger
def __init__(
self,
cache: Cache[VideoInfo],
logger: logging.Logger,
proxies: List[str] = [],
max_retries=2
):
self.cache = cache
self.logger = logger
self.proxies = [None] + proxies # First is direct download (no proxy)
self.max_retries = max_retries
self.current_proxy_idx = 0
self.current_proxy = None
def load(self, uri) -> AudioClip:
"""
Downloads a full youtube clip and splits it in segments
"""
videoinfo = self._get_videoinfo(uri)
filepath = _download_raw_audio(videoinfo, self.current_proxy)
return AudioClip(filepath, videoinfo.length)
def load_segment(self, uri, from_second, duration=10):
"""
Downloads a segment from a youtube clip
"""
videoinfo = self._get_videoinfo(uri)
filepath = _download_raw_audio_segment(
videoinfo, from_second, duration, self.current_proxy)
return AudioSegment(filepath, from_second, from_second + duration)
def _get_videoinfo(self, uri: str) -> VideoInfo:
videoinfo = self.cache.get(uri)
if videoinfo is None:
self.logger.info(
"Video info retrieved from youtube (MISS): %s", uri)
videoinfo = self._load_videoinfo_with_retry(uri)
self.cache.set(uri, videoinfo)
else:
self.logger.info("Video info retrieved from cache (HIT): %s", uri)
return videoinfo
def _load_videoinfo_with_retry(self, uri: str, retry=0) -> VideoInfo:
self.current_proxy_idx += retry
proxy_idx = self.current_proxy_idx % len(self.proxies)
proxy = self.proxies[proxy_idx]
self.current_proxy = proxy
if proxy:
youtube_dl_opts = {"proxy": proxy}
else:
youtube_dl_opts = {}
try:
video = pafy.new(uri, basic=False, ydl_opts=youtube_dl_opts)
self.logger.info(
"Downloading video: %s. Proxy: %s. Retry %d",
uri,
proxy,
retry
)
audio_url = _get_audio_url(video)
return VideoInfo(
video.videoid,
audio_url,
video.length
)
except Exception as err:
if retry + 1 < self.max_retries:
return self._load_videoinfo_with_retry(uri, retry + 1)
else:
raise err
def _get_audio_url(video):
best_audio = video.getbestaudio()
best_audio_url = best_audio.url
return best_audio_url
def _download_raw_audio(videoinfo: VideoInfo, proxy=None):
# Set output settings
audio_codec = 'pcm_s16le'
audio_container = 'wav'
# Get output video and audio filepaths
base_path = './.tmp/'
basename_fmt = videoinfo.id
audio_filepath = os.path.join(
base_path, basename_fmt + '.' + audio_container
)
# Download the audio
audio_dl_args = [
'ffmpeg',
'-ss', str(0), # The beginning of the trim window
'-i', videoinfo.audio_url, # Specify the input video URL
'-t', str(videoinfo.length), # Specify the duration of the output
'-y', # Override file if exists
'-vn', # Suppress the video stream
'-ac', '2', # Set the number of channels
'-sample_fmt', 's16', # Specify the bit depth
'-acodec', audio_codec, # Specify the output encoding
'-ar', '44100', # Specify the audio sample rate
audio_filepath
]
proc = sp.Popen(audio_dl_args, stdout=sp.PIPE, stderr=sp.PIPE)
stdout, stderr = proc.communicate()
if proc.returncode != 0:
print(stderr)
else:
print("Downloaded audio to " + audio_filepath)
SEGMENT_SECONDS = 10
# for i in range(math.floor(video.length / SEGMENT_SECONDS)):
# start = i * SEGMENT_SECONDS
# end = start + SEGMENT_SECONDS
basename_segment_fmt = "{}_%03d".format(videoinfo.id)
segment_audio_filepath = os.path.join(
base_path, basename_segment_fmt + '.' + audio_container
)
# Download the audio
audio_dl_args = [
'ffmpeg',
'-i', audio_filepath, # Specify the input video URL
'-f', 'segment', # Segment the file
'-y', # Override file if exists
'-segment_time', str(SEGMENT_SECONDS), # Specify the segment duration
'-c', 'copy', # Specify the output encoding
segment_audio_filepath
]
env = os.environ.copy()
if proxy:
env["http_proxy"] = proxy
proc = sp.Popen(audio_dl_args, stdout=sp.PIPE, stderr=sp.PIPE, env=env)
stdout, stderr = proc.communicate()
if proc.returncode != 0:
print("ERROR", stderr)
else:
print("Splitted" + segment_audio_filepath)
return audio_filepath
def _download_raw_audio_segment(
videoinfo: VideoInfo, from_second, duration, proxy=None
):
# Set output settings
audio_codec = 'pcm_s16le'
audio_container = 'wav'
# Get output video and audio filepaths
base_path = './.tmp/'
basename_fmt = "{}_from_{}".format(videoinfo.id, from_second)
audio_filepath = os.path.join(
base_path, basename_fmt + '.' + audio_container
)
if os.path.exists(audio_filepath):
print(
"Segment file exists in disk %s. Skipping download",
videoinfo.id)
return audio_filepath
# Download the audio
audio_dl_args = [
'ffmpeg',
'-ss', str(from_second), # The beginning of the trim window
'-i', videoinfo.audio_url, # Specify the input video URL
'-t', str(duration), # Specify the duration of the output
'-y', # Override file if exists
'-vn', # Suppress the video stream
'-ac', '2', # Set the number of channels
'-sample_fmt', 's16', # Specify the bit depth
'-acodec', audio_codec, # Specify the output encoding
'-ar', '44100', # Specify the audio sample rate
audio_filepath
]
env = os.environ.copy()
if proxy:
env["http_proxy"] = proxy
proc = sp.Popen(audio_dl_args, stdout=sp.PIPE, stderr=sp.PIPE, env=env)
stdout, stderr = proc.communicate()
if proc.returncode != 0:
print(stderr)
else:
print("Downloaded audio to " + audio_filepath)
return audio_filepath
class VideoInfoCacheInMemory(Cache[VideoInfo]):
def __init__(self):
self.storage = {}
def get(self, key: str) -> VideoInfo:
return self.storage.get(key)
def set(self, key: str, entry: VideoInfo):
self.storage[key] = entry
def __contains__(self, key: str) -> bool:
return key in self.storage
| {"/mgr/infrastructure/models/deep/feed_forward/__init__.py": ["/mgr/infrastructure/models/deep/tensorflow.py"], "/mgr/usecases/classify.py": ["/mgr/usecases/interfaces.py", "/mgr/domain/entities.py"], "/mgr/infrastructure/audioset/vggish/cache/memory.py": ["/mgr/usecases/interfaces.py"], "/mgr/infrastructure/models/deep/lstm/layers.py": ["/mgr/infrastructure/audioset/ontology.py"], "/mgr/infrastructure/models/deep/feed_forward/exporter.py": ["/mgr/infrastructure/models/deep/feed_forward/layers.py"], "/mgr/infrastructure/models/naive_bayes/naivebayes.py": ["/mgr/usecases/interfaces.py", "/mgr/domain/entities.py", "/mgr/infrastructure/audioset/ontology.py", "/mgr/infrastructure/audioset/vggish/loader.py"], "/app.py": ["/mgr/infrastructure/server/flask.py", "/mgr/usecases/classify.py", "/mgr/infrastructure/models/naive_bayes/naivebayes.py", "/mgr/infrastructure/models/deep/feed_forward/__init__.py", "/mgr/infrastructure/models/deep/lstm/__init__.py", "/mgr/infrastructure/models/svm/svm.py", "/mgr/infrastructure/youtube.py", "/mgr/infrastructure/audioset/vggish/cache/memory.py", "/mgr/infrastructure/audioset/vggish/loader.py"], "/tests/unit/domain/entities_test.py": ["/mgr/domain/entities.py"], "/mgr/infrastructure/models/deep/feed_forward/layers.py": ["/mgr/infrastructure/audioset/ontology.py"], "/mgr/infrastructure/audioset/vggish/loader.py": ["/mgr/domain/entities.py", "/mgr/usecases/interfaces.py"], "/mgr/infrastructure/models/deep/lstm/__init__.py": ["/mgr/infrastructure/models/deep/tensorflow.py"], "/mgr/infrastructure/models/deep/tensorflow.py": ["/mgr/usecases/interfaces.py", "/mgr/infrastructure/audioset/vggish/loader.py", "/mgr/infrastructure/audioset/ontology.py"], "/mgr/usecases/interfaces.py": ["/mgr/domain/entities.py"], "/mgr/infrastructure/youtube.py": ["/mgr/usecases/interfaces.py", "/mgr/domain/entities.py"], "/tests/unit/usecases/classify_test.py": ["/mgr/usecases/interfaces.py", "/mgr/usecases/classify.py", "/mgr/domain/entities.py"], "/mgr/infrastructure/models/svm/svm.py": ["/mgr/usecases/interfaces.py", "/mgr/domain/entities.py", "/mgr/infrastructure/audioset/ontology.py", "/mgr/infrastructure/audioset/vggish/loader.py"]} |
42,944 | jramcast/mgr-service | refs/heads/master | /tests/unit/usecases/classify_test.py | from mgr.usecases.interfaces import Model
from mgr.usecases.classify import ClassifyUseCase
from mgr.usecases.interfaces import AudioLoader
from mgr.domain.entities import (Prediction, AudioClip, AudioSegment)
def test_predict_returns_predictions():
models = [FakeModel()]
usecase = ClassifyUseCase(models, FakeAudioLoader())
inputdata = "youtube.com/1234"
result = usecase.run(inputdata, from_second=10)
assert result == {
"FakeModel": {
"labels": [{
"name": "ball",
"score": 0.84
}],
"segment": {
"fromSecond": 10,
"toSecond": 20,
"mediaUri": "youtube.com/1234"
}
}
}
class FakeAudioLoader(AudioLoader):
def load(self, uri):
return AudioClip("test.wav", 60)
def load_segment(self, uri, from_second):
return AudioSegment("test_000.wav", start=from_second, stop=20)
class FakeModel(Model):
def preprocess(self, clip: AudioClip):
return []
def classify(self, data):
return [[Prediction("ball", 0.84)]]
| {"/mgr/infrastructure/models/deep/feed_forward/__init__.py": ["/mgr/infrastructure/models/deep/tensorflow.py"], "/mgr/usecases/classify.py": ["/mgr/usecases/interfaces.py", "/mgr/domain/entities.py"], "/mgr/infrastructure/audioset/vggish/cache/memory.py": ["/mgr/usecases/interfaces.py"], "/mgr/infrastructure/models/deep/lstm/layers.py": ["/mgr/infrastructure/audioset/ontology.py"], "/mgr/infrastructure/models/deep/feed_forward/exporter.py": ["/mgr/infrastructure/models/deep/feed_forward/layers.py"], "/mgr/infrastructure/models/naive_bayes/naivebayes.py": ["/mgr/usecases/interfaces.py", "/mgr/domain/entities.py", "/mgr/infrastructure/audioset/ontology.py", "/mgr/infrastructure/audioset/vggish/loader.py"], "/app.py": ["/mgr/infrastructure/server/flask.py", "/mgr/usecases/classify.py", "/mgr/infrastructure/models/naive_bayes/naivebayes.py", "/mgr/infrastructure/models/deep/feed_forward/__init__.py", "/mgr/infrastructure/models/deep/lstm/__init__.py", "/mgr/infrastructure/models/svm/svm.py", "/mgr/infrastructure/youtube.py", "/mgr/infrastructure/audioset/vggish/cache/memory.py", "/mgr/infrastructure/audioset/vggish/loader.py"], "/tests/unit/domain/entities_test.py": ["/mgr/domain/entities.py"], "/mgr/infrastructure/models/deep/feed_forward/layers.py": ["/mgr/infrastructure/audioset/ontology.py"], "/mgr/infrastructure/audioset/vggish/loader.py": ["/mgr/domain/entities.py", "/mgr/usecases/interfaces.py"], "/mgr/infrastructure/models/deep/lstm/__init__.py": ["/mgr/infrastructure/models/deep/tensorflow.py"], "/mgr/infrastructure/models/deep/tensorflow.py": ["/mgr/usecases/interfaces.py", "/mgr/infrastructure/audioset/vggish/loader.py", "/mgr/infrastructure/audioset/ontology.py"], "/mgr/usecases/interfaces.py": ["/mgr/domain/entities.py"], "/mgr/infrastructure/youtube.py": ["/mgr/usecases/interfaces.py", "/mgr/domain/entities.py"], "/tests/unit/usecases/classify_test.py": ["/mgr/usecases/interfaces.py", "/mgr/usecases/classify.py", "/mgr/domain/entities.py"], "/mgr/infrastructure/models/svm/svm.py": ["/mgr/usecases/interfaces.py", "/mgr/domain/entities.py", "/mgr/infrastructure/audioset/ontology.py", "/mgr/infrastructure/audioset/vggish/loader.py"]} |
42,945 | jramcast/mgr-service | refs/heads/master | /mgr/infrastructure/models/svm/svm.py | import joblib
import numpy as np
from typing import List
from mgr.usecases.interfaces import Model
from mgr.domain.entities import Prediction, AudioSegment
from mgr.infrastructure.audioset.ontology import MUSIC_GENRE_CLASSES
from mgr.infrastructure.audioset.vggish.loader import EmbeddingsLoader
class SVMModel(Model):
def __init__(self, embeddings_loader: EmbeddingsLoader):
model_file = "./mgr/infrastructure/models/svm/bal_svm.joblib"
self.model = joblib.load(model_file)
self.embeddings_loader = embeddings_loader
def preprocess(self, segments: List[AudioSegment]):
# At this point, both the full clip and its segments are supossed to be downloaded
embeddings = self.embeddings_loader.load_from_segments(segments)
x = np.array(embeddings)
x = x.reshape(x.shape[0], 1280)
print("x shape", x.shape)
return x
# return x.reshape(-1, 1280)
def classify(
self, features: np.ndarray
) -> List[List[Prediction]]:
"""
Returns a list of list of predictions
The first list is the list of samples(segments)
The second list is the list of labels for each segment
"""
result = self.model.decision_function(features)
predictions = []
for i, record in enumerate(result):
segment_predictions = []
predictions.append(segment_predictions)
for j, prediction in enumerate(record):
segment_predictions.append(Prediction(
MUSIC_GENRE_CLASSES[j]["name"],
result[i][j]
))
return predictions
| {"/mgr/infrastructure/models/deep/feed_forward/__init__.py": ["/mgr/infrastructure/models/deep/tensorflow.py"], "/mgr/usecases/classify.py": ["/mgr/usecases/interfaces.py", "/mgr/domain/entities.py"], "/mgr/infrastructure/audioset/vggish/cache/memory.py": ["/mgr/usecases/interfaces.py"], "/mgr/infrastructure/models/deep/lstm/layers.py": ["/mgr/infrastructure/audioset/ontology.py"], "/mgr/infrastructure/models/deep/feed_forward/exporter.py": ["/mgr/infrastructure/models/deep/feed_forward/layers.py"], "/mgr/infrastructure/models/naive_bayes/naivebayes.py": ["/mgr/usecases/interfaces.py", "/mgr/domain/entities.py", "/mgr/infrastructure/audioset/ontology.py", "/mgr/infrastructure/audioset/vggish/loader.py"], "/app.py": ["/mgr/infrastructure/server/flask.py", "/mgr/usecases/classify.py", "/mgr/infrastructure/models/naive_bayes/naivebayes.py", "/mgr/infrastructure/models/deep/feed_forward/__init__.py", "/mgr/infrastructure/models/deep/lstm/__init__.py", "/mgr/infrastructure/models/svm/svm.py", "/mgr/infrastructure/youtube.py", "/mgr/infrastructure/audioset/vggish/cache/memory.py", "/mgr/infrastructure/audioset/vggish/loader.py"], "/tests/unit/domain/entities_test.py": ["/mgr/domain/entities.py"], "/mgr/infrastructure/models/deep/feed_forward/layers.py": ["/mgr/infrastructure/audioset/ontology.py"], "/mgr/infrastructure/audioset/vggish/loader.py": ["/mgr/domain/entities.py", "/mgr/usecases/interfaces.py"], "/mgr/infrastructure/models/deep/lstm/__init__.py": ["/mgr/infrastructure/models/deep/tensorflow.py"], "/mgr/infrastructure/models/deep/tensorflow.py": ["/mgr/usecases/interfaces.py", "/mgr/infrastructure/audioset/vggish/loader.py", "/mgr/infrastructure/audioset/ontology.py"], "/mgr/usecases/interfaces.py": ["/mgr/domain/entities.py"], "/mgr/infrastructure/youtube.py": ["/mgr/usecases/interfaces.py", "/mgr/domain/entities.py"], "/tests/unit/usecases/classify_test.py": ["/mgr/usecases/interfaces.py", "/mgr/usecases/classify.py", "/mgr/domain/entities.py"], "/mgr/infrastructure/models/svm/svm.py": ["/mgr/usecases/interfaces.py", "/mgr/domain/entities.py", "/mgr/infrastructure/audioset/ontology.py", "/mgr/infrastructure/audioset/vggish/loader.py"]} |
42,951 | pawncouncil/belt | refs/heads/master | /apps/beltApp/models.py | from __future__ import unicode_literals
from django.db import models
from datetime import datetime
import re, bcrypt
EMAIL_REGEX = re.compile(r'^[a-zA-Z0-9.+_-]+@[a-zA-Z0-9._-]+\.[a-zA-Z]+$')
# This is all the validation
class UserManager(models.Manager):
def register(self, postData):
errors = {}
if len(postData['full_name']) < 2:
errors['full_name'] ='Please input full name.'
if len(postData['username']) < 2:
errors['uername']= 'Please input a username.'
if len(postData['password']) < 8:
errors['password'] ='Password must be at least 8 characters.'
if postData['password'] != postData['passwordconf']:
errors['passwordconf'] ='Passwords must match.'
if len(errors) > 0:
status = {
'errors': errors,
'valid': False
}
return status
else:
hashed_password = bcrypt.hashpw(postData['password'].encode(), bcrypt.gensalt())
user = User.objects.create(
full_name = postData['full_name'],
username = postData['username'],
password = hashed_password)
status = {
'user': user,
'valid': True
}
return status
def login(self, postData):
errors = {}
user = User.objects.filter(username = postData['username'])
status = {
'verified' : False,
'errors' : errors,
}
errors['username'] = 'Please enter a valid username and password.'
print(errors['username'])
if len(user) > 0 and bcrypt.checkpw(postData['password'].encode(), user[0].password.encode()):
status['user'] = user[0]
status['verified'] = True
return status
class User(models.Model):
full_name = models.CharField(max_length=255)
username = models.CharField(max_length=255)
password = models.CharField(max_length=255)
created_at = models.DateTimeField(auto_now_add = True)
updated_at = models.DateTimeField(auto_now = True)
objects = UserManager()
def __repr__(self):
return "<User object: {} {}>".format(self.full_name, self.username)
class TripManager(models.Manager):
def createTrip(self, postData, user_id):
now = datetime.now()
errors = {}
status = {
'valid' : True
}
if len(postData['destination']) < 2:
errors['destinaion'] ='Please provide a destination.'
if len(postData['description']) < 2:
errors['description']= 'Please provide a description.'
if len(postData['trip_start']) < 2:
errors['trip_start'] ='Please provide departure date.'
if len(postData['trip_end']) < 2:
errors['trip_end'] ='Please provide return date.'
# else:
# trip_start = datetime.strptime(postData['trip_start'], %Y-%m-%d)
if len(errors) > 0:
status = {
'errors': errors,
'valid': False
}
return status
else:
user = User.objects.get(id=user_id)
trip = Trip.objects.create(
destination = postData['destination'],
description = postData['description'],
trip_start = postData['trip_start'],
trip_end = postData['trip_end'],
creater = user,
)
trip.attendees.add(user)
trip.save()
return status
def join(self, trip_id, user_id):
user = User.objects.get(id=user_id)
trip = Trip.objects.get(id=trip_id)
trip.attendees.add(user)
trip.save()
def remove(self, trip_id, user_id):
user = User.objects.get(id=user_id)
trip = Trip.objects.get(id=trip_id)
trip.attendees.remove(user)
trip.save()
class Trip(models.Model):
destination = models.CharField(max_length=100)
description = models.CharField(max_length=255)
trip_start = models.DateField()
trip_end = models.DateField()
creater = models.ForeignKey(User, related_name="trip_creater", null=True)
attendees = models.ManyToManyField(User, related_name="attending_trips")
created_at = models.DateTimeField(auto_now_add = True)
updated_at = models.DateTimeField(auto_now = True)
objects = TripManager()
def __repr__(self):
return "<Trip object: {} {} {} {}>".format(self.destination, self.description, self.trip_start, self.trip_end) | {"/apps/beltApp/views.py": ["/apps/beltApp/models.py"]} |
42,952 | pawncouncil/belt | refs/heads/master | /apps/beltApp/views.py | from django.shortcuts import render, HttpResponse, redirect
from django.contrib import messages
from .models import *
def index(request):
return render(request, 'beltApp/index.html')
def register(request):
status = User.objects.register(request.POST)
if status['valid']==False:
for key, value in status['errors'].items():
messages.error(request, value)
return redirect('/')
else:
request.session['user_id'] = status['user'].id
return redirect('/main')
def login(request):
status = User.objects.login(request.POST)
if status['verified'] == False:
for error, value in status['errors'].items():
messages.error(request, value)
return redirect('/')
else:
request.session['user_id'] = status['user'].id
return redirect('/main')
def logout(request):
if 'user_id' not in request.session:
return redirect('/')
request.session.clear()
return redirect('/')
def main(request):
if 'user_id' not in request.session:
return redirect('/')
user = User.objects.get(id = request.session['user_id'])
context = {
'user' : user,
'schedule' : Trip.objects.filter(attendees=request.session['user_id']),
'others_trips' : Trip.objects.exclude(attendees=request.session['user_id'])
}
return render(request, 'beltApp/main.html', context)
def add(request):
if 'user_id' not in request.session:
return redirect('/')
return render(request, 'beltApp/add.html')
def createTrip(request):
if 'user_id' not in request.session:
return redirect('/')
status = Trip.objects.createTrip(request.POST, request.session['user_id'])
if status['valid']==False:
for key, value in status['errors'].items():
messages.error(request, value)
return redirect('/add')
else:
return redirect('/main')
def join(request, trip_id):
if 'user_id' not in request.session:
return redirect('/')
Trip.objects.join(user_id=request.session['user_id'], trip_id=trip_id)
return redirect('/main')
def remove(request, trip_id):
if 'user_id' not in request.session:
return redirect('/')
Trip.objects.remove(user_id=request.session['user_id'], trip_id=trip_id)
return redirect('/main')
def destination(request, trip_id):
if 'user_id' not in request.session:
return redirect('/')
trip = Trip.objects.get(id=trip_id)
context = {
'destination' : trip,
'attendees' : trip.attendees.exclude(id = trip.creater.id)
}
return render(request, 'beltApp/destination.html', context)
def delete(request, trip_id):
if 'user_id' not in request.session:
return redirect('/')
t = Trip.objects.get(id = trip_id)
t.delete()
return redirect('/main') | {"/apps/beltApp/views.py": ["/apps/beltApp/models.py"]} |
42,983 | Cmilla9/solo-project | refs/heads/main | /search/views.py | from django.shortcuts import render
from django.db.models import Q
from food_truck_hub_app.models import BusinessUser
# def searchfood(request):
# if request.method == 'POST':
# query= request.GET.get('q')
# print('in other app')
# submitbutton= request.GET.get('submit')
# if query is not None:
# lookups= Q(food_category__icontains=query)
# results= BusinessUser.objects.filter(lookups).distinct()
# context={'results': results,
# 'submitbutton': submitbutton}
# return render(request, 'search.html', context)
# else:
# return render(request, 'search.html')
# else:
# return render(request, 'search.html')
def searchfood(request):
print("in search app")
if request.method == 'POST':
query= request.POST.get('q')
# submitbutton= request.GET.get('submit')
# print(query)
print("incorrect function")
if query is not None:
# lookups= Q(food_category__icontains=query)
# results= BusinessUser.objects.filter(lookups).distinct()
results= BusinessUser.objects.filter(food_category=query)
# context={'results': results,
# 'submitbutton': submitbutton}
context={'results': results
}
return render(request,'search.html', context)
else:
return render(request, 'search.html')
else:
return render(request, 'search.html')
# Create your views here.
| {"/search/views.py": ["/food_truck_hub_app/models.py"], "/food_truck_hub_app/views.py": ["/food_truck_hub_app/models.py"], "/search/urls.py": ["/search/views.py"]} |
42,984 | Cmilla9/solo-project | refs/heads/main | /food_truck_hub_app/apps.py | from django.apps import AppConfig
class FoodTruckHubAppConfig(AppConfig):
name = 'food_truck_hub_app'
| {"/search/views.py": ["/food_truck_hub_app/models.py"], "/food_truck_hub_app/views.py": ["/food_truck_hub_app/models.py"], "/search/urls.py": ["/search/views.py"]} |
42,985 | Cmilla9/solo-project | refs/heads/main | /food_truck_hub_app/views.py | from django.shortcuts import render, redirect
from .models import User, UserManager, BusinessUser, BusinessUserManager
from django.contrib import messages
# from django.db.models import Q
import bcrypt
def index(request):
if request.method == "GET":
businessusers = BusinessUser.objects.all()
context = {
'businessusers': businessusers,
}
return render(request,'index.html', context)
else:
user = None if 'user_id' not in request.session else User.objects.get(id=request.session['user_id'])
if not user:
return redirect('/')
user = User.objects.get(id = request.session['user_id'])
businessusers = BusinessUser.objects.all()
context = {
'businessusers': businessusers,
'user': user,
}
return render(request, 'index.html', context)
def register(request):
if request.method == 'GET':
return render(request, 'register.html')
else:
errors = User.objects.validate(request.POST)
if len(errors) > 0:
for key, value in errors.items():
messages.error(request, value)
return redirect('/')
else:
password = request.POST['password']
pw_hash = bcrypt.hashpw(password.encode(), bcrypt.gensalt()).decode()
User.objects.create(
first_name = request.POST['first_name'],
last_name = request.POST['last_name'],
email = request.POST['email'],
password = pw_hash,
)
messages.success(request, "You have successfully registered!")
return redirect('/register')
def sign_in(request):
if request.method == "GET":
return render(request, 'sign_in.html')
else:
user = User.objects.filter(email=request.POST['email'])
if len(user) > 0:
if bcrypt.checkpw(request.POST['password'].encode(), user[0].password.encode()):
request.session['user_id'] = user[0].id
return redirect('/')
else:
messages.error(request, "Incorrect Password.")
return redirect('/login')
else:
messages.error(request, "This email hasn't been registered.")
return redirect('/login')
def register_business(request):
if request.method == "GET":
return render(request, 'register_business.html')
else:
errors = BusinessUser.objects.business_validate(request.POST)
if len(errors) > 0:
for key, value in errors.items():
messages.error(request, value)
return redirect('/')
else:
password = request.POST['password']
pw_hash = bcrypt.hashpw(password.encode(), bcrypt.gensalt()).decode()
BusinessUser.objects.create(
business_name = request.POST['business_name'],
description = request.POST['description'],
email = request.POST['email'],
food_category = request.POST['food_category'],
phone_number = request.POST['phone_number'],
password = pw_hash,
)
messages.success(request, "You have successfully registered!")
return redirect('/register_business')
def business_login(request):
if request.method == "GET":
return render(request, 'sign_in.html')
else:
businessuser = BusinessUser.objects.filter(email=request.POST['email'])
if len(businessuser) > 0:
if bcrypt.checkpw(request.POST['password'].encode(), businessuser[0].password.encode()):
request.session['businessuser_id'] = businessuser[0].id
return redirect(f'/business_profile/{businessuser[0].id}')
else:
messages.error(request, "Incorrect Password.")
return redirect('/login')
else:
messages.error(request, "This email hasn't been registered.")
return redirect('/login')
def logout(request):
request.session.clear()
return redirect('/')
# def search(request):
# user = None if 'user_id' not in request.session else User.objects.get(id=request.session['user_id'])
# if not user:
# return redirect('/')
# user = User.objects.get(id = request.session['user_id'])
# context = {
# 'user': user,
# }
# return render(request, 'search.html', context)
def business_profile(request, businessuser_id):
# businessuser = None if 'businessuser_id' not in request.session else BusinessUser.objects.get(id=request.session['businessuser_id'])
# if not businessuser:
# return redirect(f'/business_profile/{businessuser_id}')
businessuser = BusinessUser.objects.get(id=f'{businessuser_id}')
context = {
'businessuser': businessuser
}
return render(request, 'business_profile.html', context)
def update_business(request, businessuser_id):
businessuser = None if 'businessuser_id' not in request.session else BusinessUser.objects.get(id=request.session['businessuser_id'])
if not businessuser:
return redirect('/')
if request.method == "POST":
errors = BusinessUser.objects.business_update(request.POST)
if len(errors) > 0:
for key, value in errors.items():
messages.error(request, value)
return redirect(f'/business_profile/{businessuser_id}')
else:
businessuser = BusinessUser.objects.get(id=businessuser_id)
businessuser.business_name = request.POST['business_name']
businessuser.description = request.POST['description']
businessuser.current_location = request.POST['current_location']
businessuser.email = request.POST['email']
businessuser.phone_number = request.POST['phone_number']
businessuser.food_category = request.POST['food_category']
businessuser.save()
return redirect(f'/business_profile/{businessuser.id}')
def searchfood(request):
print('in main app')
if request.method == 'POST':
query= request.POST['q']
# submitbutton= request.GET.get('submit')
print(query)
if query is not None:
# lookups= Q(food_category__icontains=query)
# results= BusinessUser.objects.filter(lookups).distinct()
results= BusinessUser.objects.filter(food_category=query)
print(results)
context={
'results': results
}
return render(request,'search.html', context)
else:
return render(request, 'search.html')
else:
return render(request, 'search.html')
| {"/search/views.py": ["/food_truck_hub_app/models.py"], "/food_truck_hub_app/views.py": ["/food_truck_hub_app/models.py"], "/search/urls.py": ["/search/views.py"]} |
42,986 | Cmilla9/solo-project | refs/heads/main | /food_truck_hub_app/migrations/0002_businessuser_current_location.py | # Generated by Django 2.2 on 2021-03-21 15:58
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('food_truck_hub_app', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='businessuser',
name='current_location',
field=models.CharField(default='23 Woodsworth AVE Redwood City CA 94086', max_length=255),
preserve_default=False,
),
]
| {"/search/views.py": ["/food_truck_hub_app/models.py"], "/food_truck_hub_app/views.py": ["/food_truck_hub_app/models.py"], "/search/urls.py": ["/search/views.py"]} |
42,987 | Cmilla9/solo-project | refs/heads/main | /food_truck_hub_app/urls.py | from django.urls import path
from . import views
urlpatterns = [
path('', views.index),
path('register', views.register),
path('login', views.sign_in),
path('register_business', views.register_business),
path('logout', views.logout),
path('search', views.searchfood),
path('business_profile/<int:businessuser_id>', views.business_profile),
path('business_login', views.business_login),
path('business_profile/update_business/<int:businessuser_id>', views.update_business),
] | {"/search/views.py": ["/food_truck_hub_app/models.py"], "/food_truck_hub_app/views.py": ["/food_truck_hub_app/models.py"], "/search/urls.py": ["/search/views.py"]} |
42,988 | Cmilla9/solo-project | refs/heads/main | /search/urls.py | from django.conf.urls import url
from django.contrib import admin
from .views import searchfood
urlpatterns = [
url(r'^$', searchfood, name='searchfood'),
] | {"/search/views.py": ["/food_truck_hub_app/models.py"], "/food_truck_hub_app/views.py": ["/food_truck_hub_app/models.py"], "/search/urls.py": ["/search/views.py"]} |
42,989 | Cmilla9/solo-project | refs/heads/main | /food_truck_hub_app/models.py | from django.db import models
import re
# Create your models here.
EMAIL_REGEX = re.compile(r'^[a-zA-Z0-9.+_-]+@[a-zA-Z0-9._-]+\.[a-zA-Z]+$')
class UserManager(models.Manager):
def validate(self, postData):
errors = {}
if len(postData['first_name']) < 3:
errors['first_name'] = "First Name should be at least 3 letters long."
if len(postData['last_name']) < 3:
errors['first_name'] = "Last Name should be at least 3 letters long."
if not EMAIL_REGEX.match(postData['email']):
errors['email'] = 'Invalid email address!'
if len(postData['password']) < 8:
errors['password'] ='Password should be at least 8 characters or more.'
if postData['password'] != postData['confirm_pw']:
errors['password'] = 'Passwords need to match.'
return errors
class User(models.Model):
first_name = models.CharField(max_length=255)
last_name = models.CharField(max_length=255)
email = models.CharField(max_length=255)
password = models.CharField(max_length=25)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
objects = UserManager()
class BusinessUserManager(models.Manager):
def business_validate(self, postData):
errors = {}
if len(postData['business_name']) < 3:
errors['business_name'] = "Business Name should be at least 3 letters long."
if len(postData['description']) < 5:
errors['description'] = "Description should be 5 characters or more."
if not EMAIL_REGEX.match(postData['email']):
errors['email'] = 'Invalid email address!'
if len(postData['password']) < 8:
errors['password'] ='Password should be at least 8 characters or more.'
if postData['password'] != postData['confirm_pw']:
errors['password'] = 'Passwords need to match.'
return errors
def business_update(self, postData):
errors = {}
if len(postData['business_name']) < 3:
errors['business_name'] = "Business Name should be at least 3 letters long."
if len(postData['description']) < 5:
errors['description'] = "Description should be 5 characters or more."
if not EMAIL_REGEX.match(postData['email']):
errors['email'] = 'Invalid email address!'
return errors
class BusinessUser(models.Model):
business_name = models.CharField(max_length=255)
description = models.CharField(max_length=255)
email = models.CharField(max_length=255)
food_category = models.CharField(max_length=255)
phone_number = models.CharField(max_length=255)
password = models.CharField(max_length=25)
current_location = models.CharField(max_length=255)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
objects = BusinessUserManager() | {"/search/views.py": ["/food_truck_hub_app/models.py"], "/food_truck_hub_app/views.py": ["/food_truck_hub_app/models.py"], "/search/urls.py": ["/search/views.py"]} |
43,001 | akarsh-23/wissen | refs/heads/main | /wissen/org/migrations/0006_auto_20210313_1644.py | # Generated by Django 3.1.7 on 2021-03-13 11:14
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('org', '0005_auto_20210313_1635'),
]
operations = [
migrations.AddField(
model_name='testimonial',
name='designation',
field=models.CharField(default=1, max_length=30),
preserve_default=False,
),
migrations.AddField(
model_name='testimonial',
name='email',
field=models.EmailField(default='asd@yahoo.com', max_length=254),
preserve_default=False,
),
migrations.AddField(
model_name='testimonial',
name='phone',
field=models.CharField(default=1, max_length=10),
preserve_default=False,
),
]
| {"/wissen/registrations/admin.py": ["/wissen/registrations/models.py"], "/wissen/org/admin.py": ["/wissen/org/models.py"], "/wissen/registrations/forms.py": ["/wissen/registrations/models.py"], "/wissen/org/views.py": ["/wissen/org/forms.py", "/wissen/org/models.py"], "/wissen/org/forms.py": ["/wissen/org/models.py"], "/wissen/registrations/views.py": ["/wissen/registrations/forms.py", "/wissen/registrations/utils.py"], "/wissen/org/urls.py": ["/wissen/org/views.py"]} |
43,002 | akarsh-23/wissen | refs/heads/main | /wissen/registrations/admin.py | from django.contrib import admin
from .models import *
# Register your models here.
class RegistrationAdmin(admin.ModelAdmin):
list_display = ['event','name','email','phone','registrationNo','college','course']
admin.site.register(Registration, RegistrationAdmin)
| {"/wissen/registrations/admin.py": ["/wissen/registrations/models.py"], "/wissen/org/admin.py": ["/wissen/org/models.py"], "/wissen/registrations/forms.py": ["/wissen/registrations/models.py"], "/wissen/org/views.py": ["/wissen/org/forms.py", "/wissen/org/models.py"], "/wissen/org/forms.py": ["/wissen/org/models.py"], "/wissen/registrations/views.py": ["/wissen/registrations/forms.py", "/wissen/registrations/utils.py"], "/wissen/org/urls.py": ["/wissen/org/views.py"]} |
43,003 | akarsh-23/wissen | refs/heads/main | /wissen/registrations/utils.py | def createCertificate(request):
pass | {"/wissen/registrations/admin.py": ["/wissen/registrations/models.py"], "/wissen/org/admin.py": ["/wissen/org/models.py"], "/wissen/registrations/forms.py": ["/wissen/registrations/models.py"], "/wissen/org/views.py": ["/wissen/org/forms.py", "/wissen/org/models.py"], "/wissen/org/forms.py": ["/wissen/org/models.py"], "/wissen/registrations/views.py": ["/wissen/registrations/forms.py", "/wissen/registrations/utils.py"], "/wissen/org/urls.py": ["/wissen/org/views.py"]} |
43,004 | akarsh-23/wissen | refs/heads/main | /wissen/org/models.py | from django.db import models
class Contact(models.Model):
name = models.CharField(max_length=30)
email = models.EmailField(max_length=254)
phone = models.CharField(max_length=10)
subject = models.CharField(max_length=50)
message = models.TextField(max_length=500)
class Subscriber(models.Model):
email = models.EmailField(max_length=254, primary_key=True)
class Team(models.Model):
name = models.CharField(max_length=30)
email = models.EmailField(max_length=254, primary_key=True)
phone = models.CharField(max_length=10)
designation = models.CharField(max_length=30)
description = models.CharField(max_length=255, blank=True)
image = models.FileField(upload_to='Team/')
uploaded_at = models.DateTimeField(auto_now_add=True)
class Event(models.Model):
name = models.CharField(max_length=100, primary_key=True)
description = models.TextField(max_length=1000)
image = models.FileField(upload_to='Event/')
category = models.CharField(max_length=100)
uploaded_at = models.DateTimeField(auto_now_add=True)
status = models.BooleanField()
class Testimonial(models.Model):
name = models.CharField(max_length=30)
email = models.EmailField(max_length=254, primary_key=True)
phone = models.CharField(max_length=10)
designation = models.CharField(max_length=30)
description = models.CharField(max_length=255, blank=True)
image = models.FileField(upload_to='Testimonial/')
uploaded_at = models.DateTimeField(auto_now_add=True)
# class Content(models.Model):
# aboutus = models.TextField(max_length=500)
# whatwedo = models.TextField(max_length=500)
# technicalevents = models.TextField(max_length=500)
# culturalevents = models.TextField(max_length=500)
# socialevents = models.TextField(max_length=500)
# talkshows = models.TextField(max_length=500)
# events = models.TextField(max_length=500)
# meettheteam = models.TextField(max_length=500) | {"/wissen/registrations/admin.py": ["/wissen/registrations/models.py"], "/wissen/org/admin.py": ["/wissen/org/models.py"], "/wissen/registrations/forms.py": ["/wissen/registrations/models.py"], "/wissen/org/views.py": ["/wissen/org/forms.py", "/wissen/org/models.py"], "/wissen/org/forms.py": ["/wissen/org/models.py"], "/wissen/registrations/views.py": ["/wissen/registrations/forms.py", "/wissen/registrations/utils.py"], "/wissen/org/urls.py": ["/wissen/org/views.py"]} |
43,005 | akarsh-23/wissen | refs/heads/main | /wissen/org/migrations/0005_auto_20210313_1635.py | # Generated by Django 3.1.7 on 2021-03-13 11:05
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('org', '0004_event'),
]
operations = [
migrations.CreateModel(
name='Testimonial',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=30)),
('description', models.CharField(blank=True, max_length=255)),
('image', models.FileField(upload_to='Testimonial/')),
('uploaded_at', models.DateTimeField(auto_now_add=True)),
],
),
migrations.RenameField(
model_name='event',
old_name='document',
new_name='image',
),
migrations.RenameField(
model_name='team',
old_name='document',
new_name='image',
),
migrations.RemoveField(
model_name='event',
name='email',
),
migrations.RemoveField(
model_name='event',
name='phone',
),
migrations.AddField(
model_name='team',
name='designation',
field=models.CharField(default=1, max_length=30),
preserve_default=False,
),
]
| {"/wissen/registrations/admin.py": ["/wissen/registrations/models.py"], "/wissen/org/admin.py": ["/wissen/org/models.py"], "/wissen/registrations/forms.py": ["/wissen/registrations/models.py"], "/wissen/org/views.py": ["/wissen/org/forms.py", "/wissen/org/models.py"], "/wissen/org/forms.py": ["/wissen/org/models.py"], "/wissen/registrations/views.py": ["/wissen/registrations/forms.py", "/wissen/registrations/utils.py"], "/wissen/org/urls.py": ["/wissen/org/views.py"]} |
43,006 | akarsh-23/wissen | refs/heads/main | /wissen/org/admin.py | from django.contrib import admin
from .models import Contact, Subscriber, Team, Event, Testimonial
# Register your models here.
admin.site.register(Contact)
admin.site.register(Subscriber)
admin.site.register(Team)
admin.site.register(Event)
admin.site.register(Testimonial)
| {"/wissen/registrations/admin.py": ["/wissen/registrations/models.py"], "/wissen/org/admin.py": ["/wissen/org/models.py"], "/wissen/registrations/forms.py": ["/wissen/registrations/models.py"], "/wissen/org/views.py": ["/wissen/org/forms.py", "/wissen/org/models.py"], "/wissen/org/forms.py": ["/wissen/org/models.py"], "/wissen/registrations/views.py": ["/wissen/registrations/forms.py", "/wissen/registrations/utils.py"], "/wissen/org/urls.py": ["/wissen/org/views.py"]} |
43,007 | akarsh-23/wissen | refs/heads/main | /wissen/registrations/forms.py | from django.forms import ModelForm
from .models import *
from django import forms
class RegistrationForm(ModelForm):
class Meta:
model = Registration
fields = ['event','name', 'email', 'phone', 'registrationNo', 'college', 'course']
widgets = {
'event': forms.TextInput(attrs={'class': 'form-control','placeholder': 'Event*', 'type':'hidden'}),
'name': forms.TextInput(attrs={'class': 'form-control','placeholder': 'Name*'}),
'email': forms.EmailInput(attrs={'class': 'form-control','placeholder': 'Email*'}),
'phone': forms.NumberInput(attrs={'class': 'form-control','placeholder': 'Phone*', 'type':'tel'}),
'registrationNo': forms.NumberInput(attrs={'class': 'form-control','placeholder': 'Registration No.'}),
'college': forms.TextInput(attrs={'class': 'form-control','placeholder': 'College*'}),
'course': forms.TextInput(attrs={'class': 'form-control','placeholder': 'Course*'}),
} | {"/wissen/registrations/admin.py": ["/wissen/registrations/models.py"], "/wissen/org/admin.py": ["/wissen/org/models.py"], "/wissen/registrations/forms.py": ["/wissen/registrations/models.py"], "/wissen/org/views.py": ["/wissen/org/forms.py", "/wissen/org/models.py"], "/wissen/org/forms.py": ["/wissen/org/models.py"], "/wissen/registrations/views.py": ["/wissen/registrations/forms.py", "/wissen/registrations/utils.py"], "/wissen/org/urls.py": ["/wissen/org/views.py"]} |
43,008 | akarsh-23/wissen | refs/heads/main | /wissen/org/views.py | from django.conf import settings
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import redirect, render
from django.views.decorators.csrf import csrf_exempt
from .forms import (ContactForm, EventForm, SubscriberForm, TeamForm,
TestimonialForm)
from .models import Event, Team
def home(request):
contact_form = ContactForm()
subscriber_form = SubscriberForm()
context = {'ContactForm': contact_form,
'SubscriberForm': subscriber_form,
}
return render(request, 'home.html', context)
def event(request):
try:
if request.GET.get('Category'):
subscriber_form = SubscriberForm()
context = {
'media_url': settings.MEDIA_URL,
'upcomingevents': Event.objects.filter(status=True),
'pastevents': Event.objects.filter(status=False, category=request.GET.get('Category', None)),
'categories': Event.objects.values('category').distinct(),
'SubscriberForm': subscriber_form,
}
return render(request, 'events.html', context)
else:
subscriber_form = SubscriberForm()
context = {
'media_url': settings.MEDIA_URL,
'upcomingevents': Event.objects.filter(status=True),
'pastevents': Event.objects.filter(status=False),
'categories': Event.objects.values('category').distinct(),
'SubscriberForm': subscriber_form,
}
return render(request, 'events.html', context)
except:
return redirect('../?error=Something went worng!')
def contactFormView(request):
try:
if request.method == 'POST':
# create a form instance and populate it with data from the request:
contact_form = ContactForm(request.POST)
# check whether it's valid:
if contact_form.is_valid():
# process the data in form.cleaned_data as required
new_contact = contact_form.save()
new_contact.save()
# redirect to a new URL:
return HttpResponseRedirect('../ThankYou')
else:
raise Exception
else:
raise Exception
except:
return HttpResponseRedirect('../')
def subscriberFormView(request):
try:
if request.method == 'POST':
# create a form instance and populate it with data from the request:
subscriber_form = SubscriberForm(request.POST)
# check whether it's valid:
if subscriber_form.is_valid():
# process the data in form.cleaned_data as required
new_subscriber = subscriber_form.save()
new_subscriber.save()
# redirect to a new URL:
return HttpResponseRedirect('../ThankYou')
else:
raise Exception
else:
raise Exception
except:
return HttpResponseRedirect('../')
def thankYouView(request):
subscriber_form = SubscriberForm()
context = {'SubscriberForm': subscriber_form }
return render(request, 'thanks.html', context) | {"/wissen/registrations/admin.py": ["/wissen/registrations/models.py"], "/wissen/org/admin.py": ["/wissen/org/models.py"], "/wissen/registrations/forms.py": ["/wissen/registrations/models.py"], "/wissen/org/views.py": ["/wissen/org/forms.py", "/wissen/org/models.py"], "/wissen/org/forms.py": ["/wissen/org/models.py"], "/wissen/registrations/views.py": ["/wissen/registrations/forms.py", "/wissen/registrations/utils.py"], "/wissen/org/urls.py": ["/wissen/org/views.py"]} |
43,009 | akarsh-23/wissen | refs/heads/main | /wissen/registrations/migrations/0001_initial.py | # Generated by Django 3.2.3 on 2021-05-22 08:09
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Event',
fields=[
('event', models.CharField(max_length=50, primary_key=True, serialize=False)),
('status', models.BooleanField()),
('image', models.FileField(upload_to='Events/')),
],
),
migrations.CreateModel(
name='Registrations',
fields=[
('event', models.CharField(max_length=50)),
('name', models.CharField(max_length=50)),
('email', models.EmailField(max_length=254, primary_key=True, serialize=False)),
('phone', models.BigIntegerField()),
('registrationNo', models.BigIntegerField(blank=True)),
('college', models.CharField(max_length=50)),
('course', models.CharField(max_length=50)),
],
),
]
| {"/wissen/registrations/admin.py": ["/wissen/registrations/models.py"], "/wissen/org/admin.py": ["/wissen/org/models.py"], "/wissen/registrations/forms.py": ["/wissen/registrations/models.py"], "/wissen/org/views.py": ["/wissen/org/forms.py", "/wissen/org/models.py"], "/wissen/org/forms.py": ["/wissen/org/models.py"], "/wissen/registrations/views.py": ["/wissen/registrations/forms.py", "/wissen/registrations/utils.py"], "/wissen/org/urls.py": ["/wissen/org/views.py"]} |
43,010 | akarsh-23/wissen | refs/heads/main | /wissen/org/migrations/0014_auto_20210523_2245.py | # Generated by Django 3.2.3 on 2021-05-23 17:15
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('org', '0013_auto_20210522_2051'),
]
operations = [
migrations.AlterField(
model_name='contact',
name='message',
field=models.TextField(max_length=500),
),
migrations.AlterField(
model_name='event',
name='description',
field=models.TextField(max_length=1000),
),
]
| {"/wissen/registrations/admin.py": ["/wissen/registrations/models.py"], "/wissen/org/admin.py": ["/wissen/org/models.py"], "/wissen/registrations/forms.py": ["/wissen/registrations/models.py"], "/wissen/org/views.py": ["/wissen/org/forms.py", "/wissen/org/models.py"], "/wissen/org/forms.py": ["/wissen/org/models.py"], "/wissen/registrations/views.py": ["/wissen/registrations/forms.py", "/wissen/registrations/utils.py"], "/wissen/org/urls.py": ["/wissen/org/views.py"]} |
43,011 | akarsh-23/wissen | refs/heads/main | /wissen/org/migrations/0008_delete_payment.py | # Generated by Django 3.1.7 on 2021-03-18 10:15
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('org', '0007_content_payment'),
]
operations = [
migrations.DeleteModel(
name='Payment',
),
]
| {"/wissen/registrations/admin.py": ["/wissen/registrations/models.py"], "/wissen/org/admin.py": ["/wissen/org/models.py"], "/wissen/registrations/forms.py": ["/wissen/registrations/models.py"], "/wissen/org/views.py": ["/wissen/org/forms.py", "/wissen/org/models.py"], "/wissen/org/forms.py": ["/wissen/org/models.py"], "/wissen/registrations/views.py": ["/wissen/registrations/forms.py", "/wissen/registrations/utils.py"], "/wissen/org/urls.py": ["/wissen/org/views.py"]} |
43,012 | akarsh-23/wissen | refs/heads/main | /wissen/org/migrations/0015_alter_event_name.py | # Generated by Django 3.2.3 on 2021-05-23 17:24
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('org', '0014_auto_20210523_2245'),
]
operations = [
migrations.AlterField(
model_name='event',
name='name',
field=models.CharField(max_length=100, primary_key=True, serialize=False),
),
]
| {"/wissen/registrations/admin.py": ["/wissen/registrations/models.py"], "/wissen/org/admin.py": ["/wissen/org/models.py"], "/wissen/registrations/forms.py": ["/wissen/registrations/models.py"], "/wissen/org/views.py": ["/wissen/org/forms.py", "/wissen/org/models.py"], "/wissen/org/forms.py": ["/wissen/org/models.py"], "/wissen/registrations/views.py": ["/wissen/registrations/forms.py", "/wissen/registrations/utils.py"], "/wissen/org/urls.py": ["/wissen/org/views.py"]} |
43,013 | akarsh-23/wissen | refs/heads/main | /wissen/registrations/models.py | from django.db import models
# Create your models here.
class Registration(models.Model):
event = models.CharField(max_length=50)
name = models.CharField(max_length=50)
email = models.EmailField(primary_key=True)
phone = models.BigIntegerField()
registrationNo = models.BigIntegerField(blank=True)
college = models.CharField(max_length=50)
course = models.CharField(max_length=50) | {"/wissen/registrations/admin.py": ["/wissen/registrations/models.py"], "/wissen/org/admin.py": ["/wissen/org/models.py"], "/wissen/registrations/forms.py": ["/wissen/registrations/models.py"], "/wissen/org/views.py": ["/wissen/org/forms.py", "/wissen/org/models.py"], "/wissen/org/forms.py": ["/wissen/org/models.py"], "/wissen/registrations/views.py": ["/wissen/registrations/forms.py", "/wissen/registrations/utils.py"], "/wissen/org/urls.py": ["/wissen/org/views.py"]} |
43,014 | akarsh-23/wissen | refs/heads/main | /wissen/org/migrations/0007_content_payment.py | # Generated by Django 3.1.7 on 2021-03-18 10:13
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('org', '0006_auto_20210313_1644'),
]
operations = [
migrations.CreateModel(
name='Content',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('aboutus', models.TextField(max_length=500)),
('whatwedo', models.TextField(max_length=500)),
('technicalevents', models.TextField(max_length=500)),
('culturalevents', models.TextField(max_length=500)),
('socialevents', models.TextField(max_length=500)),
('talkshows', models.TextField(max_length=500)),
('events', models.TextField(max_length=500)),
('meettheteam', models.TextField(max_length=500)),
],
),
migrations.CreateModel(
name='Payment',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('amount', models.CharField(max_length=30)),
],
),
]
| {"/wissen/registrations/admin.py": ["/wissen/registrations/models.py"], "/wissen/org/admin.py": ["/wissen/org/models.py"], "/wissen/registrations/forms.py": ["/wissen/registrations/models.py"], "/wissen/org/views.py": ["/wissen/org/forms.py", "/wissen/org/models.py"], "/wissen/org/forms.py": ["/wissen/org/models.py"], "/wissen/registrations/views.py": ["/wissen/registrations/forms.py", "/wissen/registrations/utils.py"], "/wissen/org/urls.py": ["/wissen/org/views.py"]} |
43,015 | akarsh-23/wissen | refs/heads/main | /wissen/org/migrations/0009_auto_20210320_0019.py | # Generated by Django 3.1.7 on 2021-03-19 18:49
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('org', '0008_delete_payment'),
]
operations = [
migrations.DeleteModel(
name='Content',
),
migrations.AlterField(
model_name='event',
name='name',
field=models.CharField(blank=True, max_length=30),
),
]
| {"/wissen/registrations/admin.py": ["/wissen/registrations/models.py"], "/wissen/org/admin.py": ["/wissen/org/models.py"], "/wissen/registrations/forms.py": ["/wissen/registrations/models.py"], "/wissen/org/views.py": ["/wissen/org/forms.py", "/wissen/org/models.py"], "/wissen/org/forms.py": ["/wissen/org/models.py"], "/wissen/registrations/views.py": ["/wissen/registrations/forms.py", "/wissen/registrations/utils.py"], "/wissen/org/urls.py": ["/wissen/org/views.py"]} |
43,016 | akarsh-23/wissen | refs/heads/main | /wissen/org/upload.py | import datetime,os
from pathlib import Path
def upload(file, folder):
date_time = datetime.datetime.now()
base_dir = Path(__file__).resolve().parent.parent
location = 'wissen\\static\\assets\\img\\uploaded\\' + folder + date_time
final_location = os.join(base_dir, location)
with open(final_location, 'wb+') as destination:
for chunk in file.chunks():
destination.write(chunk)
# folder = 'Events'
# base_dir = Path(__file__).resolve().parent.parent
# location = 'wissen\\static\\assets\\img\\uploaded\\' + folder
# final_location = os.path.join(base_dir, location)
# print(final_location) | {"/wissen/registrations/admin.py": ["/wissen/registrations/models.py"], "/wissen/org/admin.py": ["/wissen/org/models.py"], "/wissen/registrations/forms.py": ["/wissen/registrations/models.py"], "/wissen/org/views.py": ["/wissen/org/forms.py", "/wissen/org/models.py"], "/wissen/org/forms.py": ["/wissen/org/models.py"], "/wissen/registrations/views.py": ["/wissen/registrations/forms.py", "/wissen/registrations/utils.py"], "/wissen/org/urls.py": ["/wissen/org/views.py"]} |
43,017 | akarsh-23/wissen | refs/heads/main | /wissen/org/forms.py | from django.forms import ModelForm
from .models import Contact, Subscriber, Team, Event, Testimonial
from django import forms
class ContactForm(ModelForm):
class Meta:
model = Contact
fields = ['name', 'email', 'phone', 'subject', 'message']
widgets = {
'name': forms.TextInput(attrs={'class': 'form-control','placeholder': 'Name'}),
'email': forms.EmailInput(attrs={'class': 'form-control','placeholder': 'Email'}),
'phone': forms.NumberInput(attrs={'class': 'form-control','placeholder': 'Phone'}),
'subject': forms.TextInput(attrs={'class': 'form-control','placeholder': 'Subject'}),
'message': forms.Textarea(attrs={'class': 'form-control','placeholder': 'Message'}),
}
class SubscriberForm(ModelForm):
class Meta:
model = Subscriber
fields = ['email']
widgets = {
'email': forms.EmailInput(attrs={'class': 'form-control','placeholder': 'example@email.com'}),
}
class TeamForm(forms.ModelForm):
class Meta:
model = Team
fields = ['name', 'email', 'phone', 'description', 'designation', 'image']
widgets = {
'name': forms.TextInput(attrs={'class': 'form-control','placeholder': 'Name'}),
'email': forms.EmailInput(attrs={'class': 'form-control','placeholder': 'Email'}),
'phone': forms.NumberInput(attrs={'class': 'form-control','placeholder': 'Phome'}),
'designation': forms.TextInput(attrs={'class': 'form-control','placeholder': 'Name'}),
'description': forms.TextInput(attrs={'class': 'form-control','placeholder': 'Name'}),
'image': forms.FileInput(attrs={'class': 'form-control','placeholder': 'Email'}),
}
class EventForm(forms.ModelForm):
class Meta:
model = Event
fields = ['name', 'description', 'image']
widgets = {
'name': forms.TextInput(attrs={'class': 'form-control','placeholder': 'Name'}),
'description': forms.Textarea(attrs={'class': 'form-control','placeholder': 'Description'}),
'image': forms.FileInput(attrs={'class': 'form-control','placeholder': 'Email'}),
}
class TestimonialForm(forms.ModelForm):
class Meta:
model = Testimonial
fields = ['name', 'email', 'phone', 'designation', 'description', 'image']
widgets = {
'name': forms.TextInput(attrs={'class': 'form-control','placeholder': 'Name'}),
'email': forms.EmailInput(attrs={'class': 'form-control','placeholder': 'Email'}),
'phone': forms.NumberInput(attrs={'class': 'form-control','placeholder': 'Phome'}),
'designation': forms.TextInput(attrs={'class': 'form-control','placeholder': 'Name'}),
'description': forms.TextInput(attrs={'class': 'form-control','placeholder': 'Name'}),
'image': forms.FileInput(attrs={'class': 'form-control','placeholder': 'Email'}),
} | {"/wissen/registrations/admin.py": ["/wissen/registrations/models.py"], "/wissen/org/admin.py": ["/wissen/org/models.py"], "/wissen/registrations/forms.py": ["/wissen/registrations/models.py"], "/wissen/org/views.py": ["/wissen/org/forms.py", "/wissen/org/models.py"], "/wissen/org/forms.py": ["/wissen/org/models.py"], "/wissen/registrations/views.py": ["/wissen/registrations/forms.py", "/wissen/registrations/utils.py"], "/wissen/org/urls.py": ["/wissen/org/views.py"]} |
43,018 | akarsh-23/wissen | refs/heads/main | /wissen/registrations/views.py | from django.shortcuts import redirect, render
from django.conf import settings
from .forms import *
from org import models
from .utils import *
def home(request):
try:
if request.method == "GET" and request.GET.get('Event'):
event = models.Event.objects.get(name=request.GET.get('Event'))
if event:
if event.status:
registrationForm = RegistrationForm({'event': request.GET.get('Event')})
context = {
'media_url' : settings.MEDIA_URL,
'RegistrationForm' : registrationForm,
'image' : event.image,
}
return render(request, 'registration/registrations.html', context=context)
else:
registrationForm = RegistrationForm({'event': request.GET.get('Event')})
context = {
'media_url' : settings.MEDIA_URL,
'error' : 'Registration Closed!',
'image' : event.image,
}
return render(request, 'registration/geterror.html', context=context)
elif request.method == "POST":
registrationForm = RegistrationForm(request.POST)
event = models.Event.objects.get(name=request.POST.get('event'))
if registrationForm.is_valid():
newresponse = registrationForm.save()
newresponse.save()
return redirect('../ThankYou')
else:
registrationForm = RegistrationForm(request.POST)
context = {
'media_url' : settings.MEDIA_URL,
'RegistrationForm' : registrationForm,
'image' : event.image,
}
return render(request, 'registration/posterror.html', context=context)
except:
return redirect('../Events')
def certificate(request):
try:
if request.method == "POST":
try:
response = createCertificate(request)
return response
except:
return redirect('/NotRegistered')
else:
return render(request, 'registration/certificate.html')
except:
return | {"/wissen/registrations/admin.py": ["/wissen/registrations/models.py"], "/wissen/org/admin.py": ["/wissen/org/models.py"], "/wissen/registrations/forms.py": ["/wissen/registrations/models.py"], "/wissen/org/views.py": ["/wissen/org/forms.py", "/wissen/org/models.py"], "/wissen/org/forms.py": ["/wissen/org/models.py"], "/wissen/registrations/views.py": ["/wissen/registrations/forms.py", "/wissen/registrations/utils.py"], "/wissen/org/urls.py": ["/wissen/org/views.py"]} |
43,019 | akarsh-23/wissen | refs/heads/main | /wissen/registrations/migrations/0003_auto_20210522_1349.py | # Generated by Django 3.2.3 on 2021-05-22 08:19
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('registrations', '0002_rename_event_events'),
]
operations = [
migrations.RenameModel(
old_name='Events',
new_name='Event',
),
migrations.RenameModel(
old_name='Registrations',
new_name='Registration',
),
]
| {"/wissen/registrations/admin.py": ["/wissen/registrations/models.py"], "/wissen/org/admin.py": ["/wissen/org/models.py"], "/wissen/registrations/forms.py": ["/wissen/registrations/models.py"], "/wissen/org/views.py": ["/wissen/org/forms.py", "/wissen/org/models.py"], "/wissen/org/forms.py": ["/wissen/org/models.py"], "/wissen/registrations/views.py": ["/wissen/registrations/forms.py", "/wissen/registrations/utils.py"], "/wissen/org/urls.py": ["/wissen/org/views.py"]} |
43,020 | akarsh-23/wissen | refs/heads/main | /wissen/org/migrations/0010_auto_20210522_1339.py | # Generated by Django 3.2.3 on 2021-05-22 08:09
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('org', '0009_auto_20210320_0019'),
]
operations = [
migrations.RemoveField(
model_name='event',
name='id',
),
migrations.RemoveField(
model_name='subscriber',
name='id',
),
migrations.RemoveField(
model_name='team',
name='id',
),
migrations.RemoveField(
model_name='testimonial',
name='id',
),
migrations.AlterField(
model_name='event',
name='name',
field=models.CharField(blank=True, max_length=30, primary_key=True, serialize=False),
),
migrations.AlterField(
model_name='subscriber',
name='email',
field=models.EmailField(max_length=254, primary_key=True, serialize=False),
),
migrations.AlterField(
model_name='team',
name='email',
field=models.EmailField(max_length=254, primary_key=True, serialize=False),
),
migrations.AlterField(
model_name='testimonial',
name='email',
field=models.EmailField(max_length=254, primary_key=True, serialize=False),
),
]
| {"/wissen/registrations/admin.py": ["/wissen/registrations/models.py"], "/wissen/org/admin.py": ["/wissen/org/models.py"], "/wissen/registrations/forms.py": ["/wissen/registrations/models.py"], "/wissen/org/views.py": ["/wissen/org/forms.py", "/wissen/org/models.py"], "/wissen/org/forms.py": ["/wissen/org/models.py"], "/wissen/registrations/views.py": ["/wissen/registrations/forms.py", "/wissen/registrations/utils.py"], "/wissen/org/urls.py": ["/wissen/org/views.py"]} |
43,021 | akarsh-23/wissen | refs/heads/main | /wissen/org/migrations/0013_auto_20210522_2051.py | # Generated by Django 3.2.3 on 2021-05-22 15:21
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('org', '0012_event_status'),
]
operations = [
migrations.RemoveField(
model_name='event',
name='id',
),
migrations.AlterField(
model_name='event',
name='description',
field=models.CharField(max_length=255),
),
migrations.AlterField(
model_name='event',
name='name',
field=models.CharField(max_length=30, primary_key=True, serialize=False),
),
]
| {"/wissen/registrations/admin.py": ["/wissen/registrations/models.py"], "/wissen/org/admin.py": ["/wissen/org/models.py"], "/wissen/registrations/forms.py": ["/wissen/registrations/models.py"], "/wissen/org/views.py": ["/wissen/org/forms.py", "/wissen/org/models.py"], "/wissen/org/forms.py": ["/wissen/org/models.py"], "/wissen/registrations/views.py": ["/wissen/registrations/forms.py", "/wissen/registrations/utils.py"], "/wissen/org/urls.py": ["/wissen/org/views.py"]} |
43,022 | akarsh-23/wissen | refs/heads/main | /wissen/org/urls.py | from django.contrib import admin
from django.urls import path
from django.conf import settings
from django.conf.urls.static import static
from .views import *
urlpatterns = [
path('', home, name='home'),
path('Home/', home, name='home'),
path('form/contact', contactFormView, name='ContactForm'),
path('form/subscriber', subscriberFormView, name='SubscriberForm'),
path('ThankYou/', thankYouView, name='ThankYou'),
path('Events/', event, name='events'),
]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
# if settings.DEBUG:
# urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
# path('form/testimonial', views.testimonialFormView, name='testimonialFormUpload'),
# path('form/team', views.teamFormView, name='teamFormUpload'),
# path('form/event', views.eventFormView, name='eventFormUpload'),
# path('Team/', views.team, name='events'),
# path('Blog/', views.blog, name='blog'), | {"/wissen/registrations/admin.py": ["/wissen/registrations/models.py"], "/wissen/org/admin.py": ["/wissen/org/models.py"], "/wissen/registrations/forms.py": ["/wissen/registrations/models.py"], "/wissen/org/views.py": ["/wissen/org/forms.py", "/wissen/org/models.py"], "/wissen/org/forms.py": ["/wissen/org/models.py"], "/wissen/registrations/views.py": ["/wissen/registrations/forms.py", "/wissen/registrations/utils.py"], "/wissen/org/urls.py": ["/wissen/org/views.py"]} |
43,023 | akarsh-23/wissen | refs/heads/main | /wissen/org/migrations/0011_auto_20210522_1342.py | # Generated by Django 3.2.3 on 2021-05-22 08:12
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('org', '0010_auto_20210522_1339'),
]
operations = [
migrations.AddField(
model_name='event',
name='id',
field=models.AutoField(auto_created=True, default=1, primary_key=True, serialize=False, verbose_name='ID'),
preserve_default=False,
),
migrations.AlterField(
model_name='event',
name='name',
field=models.CharField(blank=True, max_length=30),
),
]
| {"/wissen/registrations/admin.py": ["/wissen/registrations/models.py"], "/wissen/org/admin.py": ["/wissen/org/models.py"], "/wissen/registrations/forms.py": ["/wissen/registrations/models.py"], "/wissen/org/views.py": ["/wissen/org/forms.py", "/wissen/org/models.py"], "/wissen/org/forms.py": ["/wissen/org/models.py"], "/wissen/registrations/views.py": ["/wissen/registrations/forms.py", "/wissen/registrations/utils.py"], "/wissen/org/urls.py": ["/wissen/org/views.py"]} |
43,025 | darkfox140/python_test_trening | refs/heads/main | /bdd/contact_steps.py | from pytest_bdd import given, when, then
from model.contact import NewContact
import random
@given('a contact list', target_fixture="contact_list")
def contact_list(db):
return db.get_contact_list()
@given('a contact with <last_name>, <first_name> and <address1>', target_fixture="new_contact")
def new_contact(last_name, first_name, address1):
return NewContact(last_name=last_name, first_name=first_name, address1=address1)
@when('I add the contact to the list')
def add_new_contact(app, new_contact):
app.contact.create_new_contact(new_contact)
@then('the new contact list is equal to the old list with the added contact')
def verify_contact_added(db, contact_list, new_contact):
old_contacts = contact_list
new_contacts = db.get_contact_list()
old_contacts.append(new_contact)
assert sorted(old_contacts, key=NewContact.id_or_max) == sorted(new_contacts, key=NewContact.id_or_max)
@given('a non empty contact list', target_fixture="non_empty_contact_list")
def non_empty_contact_list(db, app):
if len(db.get_group_list()) == 0:
app.contact.create_new_contact(NewContact(last_name="test name"))
return db.get_contact_list()
@given('a random contact from the list', target_fixture="random_contact")
def random_contact(non_empty_contact_list):
return random.choice(non_empty_contact_list)
@when('I delete the contact from the list')
def delete_group(app, random_contact):
app.contact.delete_contact_by_id(random_contact.id)
@then('the new contact list is equal to the old list without the deleted contact')
def verify_group_added(app, db, non_empty_contact_list, random_contact, check_ui):
old_contacs = non_empty_contact_list
new_contacts = db.get_contact_list()
assert len(old_contacs) - 1 == len(new_contacts)
old_contacs.remove(random_contact)
assert old_contacs == new_contacts
if check_ui:
assert sorted(new_contacts, key=NewContact.id_or_max) == sorted(app.get_contact_list(), key=NewContact.id_or_max)
| {"/bdd/contact_steps.py": ["/model/contact.py"], "/fixture/contact.py": ["/model/contact.py"], "/test/test_delete_contact.py": ["/model/contact.py"], "/test/test_add_some_contact_to_group.py": ["/model/contact.py"], "/test/test_delete_contact_from_group.py": ["/model/contact.py"], "/fixture/db.py": ["/model/contact.py"], "/generator/contact.py": ["/model/contact.py"], "/test/test_add_new_contact.py": ["/model/contact.py"], "/test/test_phones.py": ["/model/contact.py"], "/data/contacts.py": ["/model/contact.py"], "/test/test_info_contact.py": ["/model/contact.py"], "/test/test_modification_contact.py": ["/model/contact.py"]} |
43,026 | darkfox140/python_test_trening | refs/heads/main | /fixture/contact.py | from selenium.webdriver.support.ui import Select
from selenium.webdriver.common.by import By
from model.contact import NewContact
import re
class ContactHelper:
def __init__(self, app):
self.app = app
def open_add_new(self):
browser = self.app.browser
browser.find_element(By.LINK_TEXT, "add new").click()
def create_new_contact(self, contact):
browser = self.app.browser
self.open_add_new()
self.fill_contact_form(contact)
self.submit_enter()
self.open_home()
self.contact_cashe = None
def submit_enter(self):
browser = self.app.browser
browser.find_element(By.XPATH, "//form/input[21]").click()
def fill_contact_form(self, contact):
browser = self.app.browser
self.change_field_contact_value("firstname", contact.first_name)
self.change_field_contact_value("middlename", contact.middle_name)
self.change_field_contact_value("lastname", contact.last_name)
self.change_field_contact_value("nickname", contact.nick_name)
self.change_field_contact_value("title", contact.tittle)
self.change_field_contact_value("company", contact.company)
self.change_field_contact_value("address", contact.address1)
# Telephone
self.change_field_contact_value("home", contact.home_phone)
self.change_field_contact_value("mobile", contact.mobile_phone)
self.change_field_contact_value("work", contact.work_phone)
self.change_field_contact_value("fax", contact.fax)
# Email and homepage
self.change_field_contact_value("email", contact.email1)
self.change_field_contact_value("email2", contact.email2)
self.change_field_contact_value("email3", contact.email3)
self.change_field_contact_value("homepage", contact.homepage)
# Birthday
self.select_day("bday", contact.bday)
self.select_month("bmonth", contact.bmonth)
self.change_field_contact_value("byear", contact.byear)
# Anniversary
self.select_day("aday", contact.aday)
self.select_month("amonth", contact.amonth)
self.change_field_contact_value("ayear", contact.ayear)
# Secondary
self.change_field_contact_value("address2", contact.address2)
self.change_field_contact_value("phone2", contact.phone2)
self.change_field_contact_value("notes", contact.notes)
def select_month(self, insert_month, month):
browser = self.app.browser
if month is not None:
Select(browser.find_element(By.NAME, insert_month)).select_by_visible_text(month)
browser.find_element(By.NAME, insert_month).click()
def select_day(self, insert_the_day, number):
browser = self.app.browser
if number is not None:
Select(browser.find_element(By.NAME, insert_the_day)).select_by_visible_text(number)
browser.find_element(By.NAME, insert_the_day).click()
def change_field_contact_value(self, field_name, text):
browser = self.app.browser
if text is not None:
browser.find_element(By.NAME, field_name).clear()
browser.find_element(By.NAME, field_name).send_keys(text)
def modification_first_contact(self):
self.modification_contact_by_index(0)
def modification_contact_by_index(self, index, new_contact_form):
browser = self.app.browser
self.open_home()
self.open_contact_to_edit_by_index(index)
self.fill_contact_form(new_contact_form)
self.button_update_click()
self.open_home()
self.contact_cashe = None
def modification_contact_by_id(self, id, new_contact_form):
browser = self.app.browser
self.open_home()
self.open_contact_to_edit_by_id(id)
self.fill_contact_form(new_contact_form)
self.button_update_click()
self.open_home()
self.contact_cashe = None
def button_update_click(self):
browser = self.app.browser
browser.find_element(By.XPATH, "//form[1]/input[22]").click()
def open_contact_to_edit_by_index(self, index):
browser = self.app.browser
self.open_home()
contact_elem = browser.find_elements(By.NAME, "entry")[index]
cells = contact_elem.find_elements(By.TAG_NAME, "td")[7]
cells.find_element(By.TAG_NAME, "a").click()
def open_contact_to_edit_by_id(self, id):
browser = self.app.browser
self.open_home()
browser.find_element(By.CSS_SELECTOR, "input[value='%s']" % id)
cells = browser.find_elements(By.TAG_NAME, "td")[7]
cells.find_element(By.TAG_NAME, "a").click()
def open_contact_view_index(self, index):
browser = self.app.browser
self.open_home()
contact_elem = browser.find_elements(By.NAME, "entry")[index]
cells = contact_elem.find_elements(By.TAG_NAME, "td")[6]
cells.find_element(By.CSS_SELECTOR, "#maintable a img").click()
def delete_first_contact(self):
self.delete_contact_by_index(0)
def delete_contact_by_index(self, index):
browser = self.app.browser
self.open_home()
self.select_contact_by_index(index)
self.button_delete_click()
browser.switch_to_alert().accept()
browser.find_element(By.CSS_SELECTOR, "div.msgbox")
self.open_home()
self.contact_cashe = None
def button_delete_click(self):
browser = self.app.browser
browser.find_element(By.XPATH, "//input[@value='Delete']").click()
def delete_contact_by_id(self, id):
browser = self.app.browser
self.open_home()
self.select_contact_by_id(id)
self.button_delete_click()
browser.switch_to_alert().accept()
browser.find_element(By.CSS_SELECTOR, "div.msgbox")
self.open_home()
self.contact_cashe = None
def select_contact_by_index(self, index):
browser = self.app.browser
browser.find_elements(By.NAME, "selected[]")[index].click()
def select_contact_by_id(self, id):
browser = self.app.browser
browser.find_element(By.CSS_SELECTOR, "input[value='%s']" % id).click()
def select_first_contact(self):
browser = self.app.browser
browser.find_element(By.NAME, "selected[]").click()
def open_home(self):
browser = self.app.browser
if not (browser.current_url.endswith("/index.php") and
len(browser.find_elements(By.XPATH, "//form[2]/div[1]/input")) > 0):
browser.find_element(By.LINK_TEXT, "home").click()
def count(self):
browser = self.app.browser
self.open_home()
return len(browser.find_elements(By.NAME, "selected[]"))
contact_cashe = None # Кеширование списка контактов, сбрасывается после добавления\удаления\модификации
def get_contact_list(self):
if self.contact_cashe is None:
browser = self.app.browser
self.open_home()
self.contact_cashe = []
for elements in browser.find_elements(By.NAME, "entry"):
cells = elements.find_elements(By.TAG_NAME, "td") # Данная точка найтёт текст
id = cells[0].find_element(By.TAG_NAME, "input").get_attribute("value")
last_text = cells[1].text
first_text = cells[2].text
address = cells[3].text
all_email = cells[4].text
all_phones = cells[5].text
self.contact_cashe.append(NewContact(last_name=last_text, first_name=first_text, address1=address,
all_phones_from_home_page=all_phones,
all_email_from_home_page=all_email, id=id, ))
return list(self.contact_cashe)
def get_contact_info_from_edit_page(self, index):
browser = self.app.browser
self.open_contact_to_edit_by_index(index)
firstname = browser.find_element(By.NAME, "firstname").get_attribute("value")
lastname = browser.find_element(By.NAME, "lastname").get_attribute("value")
address = browser.find_element(By.NAME, "address").text
email1 = browser.find_element(By.NAME, "email").get_attribute("value")
email2 = browser.find_element(By.NAME, "email2").get_attribute("value")
email3 = browser.find_element(By.NAME, "email3").get_attribute("value")
homephone = browser.find_element(By.NAME, "home").get_attribute("value")
mobilephone = browser.find_element(By.NAME, "mobile").get_attribute("value")
workphone = browser.find_element(By.NAME, "work").get_attribute("value")
secondaryphone = browser.find_element(By.NAME, "phone2").get_attribute("value")
id = browser.find_element(By.NAME, "id").get_attribute("value")
return NewContact(first_name=firstname, last_name=lastname, address1=address, email1=email1, email2=email2,
email3=email3, home_phone=homephone, mobile_phone=mobilephone, work_phone=workphone,
phone2=secondaryphone, id=id)
def get_contact_from_view_page(self, index):
browser = self.app.browser
self.open_contact_view_index(index)
text = browser.find_element(By.ID, "content").text
homephone = re.search("H: (.*)", text).group(1)
mobilephone = re.search("M: (.*)", text).group(1)
workphone = re.search("W: (.*)", text).group(1)
secondaryphone = re.search("P: (.*)", text).group(1)
return NewContact(home_phone=homephone, mobile_phone=mobilephone, work_phone=workphone,
phone2=secondaryphone, id=id)
def add_contact_to_group_by_id(self, contact_id, group_id, group_name):
browser = self.app.browser
self.open_home()
self.select_contact_by_id(contact_id)
browser.find_element(By.NAME, "to_group").click()
browser.find_element(By.XPATH, "(//option[@value=%s])[2]" % group_id).click()
browser.find_element(By.NAME, "add").click()
browser.find_element(By.LINK_TEXT, 'group page "%s"' % group_name).click()
def delete_contact_from_group(self, group_id, contact_id):
browser = self.app.browser
self.open_home()
browser.find_element(By.NAME, "group").click()
browser.find_element(By.XPATH, "//option[@value=%s]" % group_id).click()
self.select_contact_by_id(contact_id)
browser.find_element(By.NAME, "remove").click()
browser.find_element(By.CSS_SELECTOR, "div.msgbox") | {"/bdd/contact_steps.py": ["/model/contact.py"], "/fixture/contact.py": ["/model/contact.py"], "/test/test_delete_contact.py": ["/model/contact.py"], "/test/test_add_some_contact_to_group.py": ["/model/contact.py"], "/test/test_delete_contact_from_group.py": ["/model/contact.py"], "/fixture/db.py": ["/model/contact.py"], "/generator/contact.py": ["/model/contact.py"], "/test/test_add_new_contact.py": ["/model/contact.py"], "/test/test_phones.py": ["/model/contact.py"], "/data/contacts.py": ["/model/contact.py"], "/test/test_info_contact.py": ["/model/contact.py"], "/test/test_modification_contact.py": ["/model/contact.py"]} |
43,027 | darkfox140/python_test_trening | refs/heads/main | /test/test_delete_contact.py | from model.contact import NewContact
import random
def test_delete_some_contact(app, db, check_ui):
if app.contact.count() == 0:
app.contact.create_new_contact(NewContact(first_name="Victor", middle_name="Ivan", last_name="Petrov",
nick_name="Fox140", tittle="test", company="testcompany", address1="Moscow",
home_phone="8(495)2154536", mobile_phone="+79168956384",
work_phone="8-499-9576135", fax="No", email1="testemail1@facegmail.com",
email2="testemail2@facegmail.com", email3="testemail3@facegmail.com",
homepage="testhomepage.ru", bday="14", bmonth="August", byear="1987",
aday="24", amonth="October", ayear="2014", address2="Moscow, Lenina 2",
phone2="8 456 9535956", notes="Test Moscow information"))
old_contact = db.get_contact_list()
contact = random.choice(old_contact)
app.contact.delete_contact_by_id(contact.id)
new_contact = db.get_contact_list()
assert len(old_contact) - 1 == len(new_contact)
old_contact.remove(contact)
assert old_contact == new_contact
if check_ui:
assert sorted(new_contact, key=NewContact.id_or_max) == \
sorted(app.contact.get_contact_list(), key=NewContact.id_or_max)
'''def test_delete_some_contact(app):
if app.contact.count() == 0:
app.contact.create_new_contact(NewContact(first_name="Victor", middle_name="Ivan", last_name="Petrov",
nick_name="Fox140", tittle="test", company="testcompany", address1="Moscow",
home_phone="8(495)2154536", mobile_phone="+79168956384",
work_phone="8-499-9576135", fax="No", email1="testemail1@facegmail.com",
email2="testemail2@facegmail.com", email3="testemail3@facegmail.com",
homepage="testhomepage.ru", bday="14", bmonth="August", byear="1987",
aday="24", amonth="October", ayear="2014", address2="Moscow, Lenina 2",
phone2="8 456 9535956", notes="Test Moscow information"))
old_contact = app.contact.get_contact_list()
index = randrange(len(old_contact))
app.contact.delete_contact_by_index(index)
new_contact = app.contact.get_contact_list()
assert len(old_contact) - 1 == len(new_contact)
old_contact[index:index+1] = []
assert old_contact == new_contact'''
| {"/bdd/contact_steps.py": ["/model/contact.py"], "/fixture/contact.py": ["/model/contact.py"], "/test/test_delete_contact.py": ["/model/contact.py"], "/test/test_add_some_contact_to_group.py": ["/model/contact.py"], "/test/test_delete_contact_from_group.py": ["/model/contact.py"], "/fixture/db.py": ["/model/contact.py"], "/generator/contact.py": ["/model/contact.py"], "/test/test_add_new_contact.py": ["/model/contact.py"], "/test/test_phones.py": ["/model/contact.py"], "/data/contacts.py": ["/model/contact.py"], "/test/test_info_contact.py": ["/model/contact.py"], "/test/test_modification_contact.py": ["/model/contact.py"]} |
43,028 | darkfox140/python_test_trening | refs/heads/main | /fixture/group.py | from selenium.webdriver.common.by import By
from model.group import Group
class GroupHelper:
def __init__(self, app):
self.app = app
def open_groups_page(self):
browser = self.app.browser
if not (browser.current_url.endswith("/group.php") and len(browser.find_elements(By.NAME, "new")) > 0):
browser.find_element(By.LINK_TEXT, "groups").click()
def create_group(self, group):
browser = self.app.browser
self.open_groups_page()
# init group creation
browser.find_element(By.NAME, "new").click()
# fill group form
self.fill_group_form(group)
# submit group creation
browser.find_element(By.NAME, "submit").click()
self.return_to_groups_page()
self.group_cashe = None
def fill_group_form(self, group):
browser = self.app.browser
self.change_field_value("group_name", group.name)
self.change_field_value("group_header", group.header)
self.change_field_value("group_footer", group.footer)
def change_field_value(self, field_name, text):
browser = self.app.browser
if text is not None:
browser.find_element(By.NAME, field_name).clear()
browser.find_element(By.NAME, field_name).send_keys(text)
def delete_first_group(self):
self.delete_group_by_index(0)
def delete_group_by_index(self, index):
browser = self.app.browser
self.open_groups_page()
self.select_group_by_index(index)
browser.find_element(By.NAME, "delete").click()
self.return_to_groups_page()
self.group_cashe = None
def delete_group_by_id(self, id):
browser = self.app.browser
self.open_groups_page()
self.select_group_by_id(id)
browser.find_element(By.NAME, "delete").click()
self.return_to_groups_page()
self.group_cashe = None
def modification_first_group(self):
self.modification_group_by_index(0)
def modification_group_by_index(self, index, new_group_date):
browser = self.app.browser
self.open_groups_page()
self.select_group_by_index(index)
# Open modification form
browser.find_element(By.XPATH, "//form/input[3]").click()
# fill group form
self.fill_group_form(new_group_date)
# Submit modification
browser.find_element(By.XPATH, "//form/input[3]").click()
self.return_to_groups_page()
self.group_cashe = None
def modification_group_by_id(self, id, new_group_date):
browser = self.app.browser
self.open_groups_page()
self.select_group_by_id(id)
# Open modification form
browser.find_element(By.XPATH, "//form/input[3]").click()
# fill group form
self.fill_group_form(new_group_date)
# Submit modification
browser.find_element(By.XPATH, "//form/input[3]").click()
self.return_to_groups_page()
self.group_cashe = None
def select_first_group(self):
browser = self.app.browser
browser.find_element(By.NAME, "selected[]").click()
def select_group_by_index(self, index):
browser = self.app.browser
browser.find_elements(By.NAME, "selected[]")[index].click()
def select_group_by_id(self, id):
browser = self.app.browser
browser.find_element(By.CSS_SELECTOR, "input[value='%s']" % id).click()
def return_to_groups_page(self):
browser = self.app.browser
browser.find_element(By.LINK_TEXT, "group page").click()
def count(self):
browser = self.app.browser
self.open_groups_page()
return len(browser.find_elements(By.NAME, "selected[]"))
group_cashe = None
def get_group_list(self):
if self.group_cashe is None:
browser = self.app.browser
self.open_groups_page()
self.group_cashe = []
for element in browser.find_elements(By.CSS_SELECTOR, "span.group"):
text = element.text
id = element.find_element(By.NAME, "selected[]").get_attribute("value")
self.group_cashe.append(Group(name=text, id=id))
return list(self.group_cashe)
| {"/bdd/contact_steps.py": ["/model/contact.py"], "/fixture/contact.py": ["/model/contact.py"], "/test/test_delete_contact.py": ["/model/contact.py"], "/test/test_add_some_contact_to_group.py": ["/model/contact.py"], "/test/test_delete_contact_from_group.py": ["/model/contact.py"], "/fixture/db.py": ["/model/contact.py"], "/generator/contact.py": ["/model/contact.py"], "/test/test_add_new_contact.py": ["/model/contact.py"], "/test/test_phones.py": ["/model/contact.py"], "/data/contacts.py": ["/model/contact.py"], "/test/test_info_contact.py": ["/model/contact.py"], "/test/test_modification_contact.py": ["/model/contact.py"]} |
43,029 | darkfox140/python_test_trening | refs/heads/main | /model/contact.py | from sys import maxsize
class NewContact:
def __init__(self, first_name=None, middle_name=None, last_name=None, nick_name=None, tittle=None, company=None,
address1=None, home_phone=None, mobile_phone=None, work_phone=None, fax=None, email1=None, email2=None,
email3=None, homepage=None, bday=None, bmonth=None, byear=None, aday=None, amonth=None, ayear=None,
address2=None, phone2=None, notes=None, id=None, all_phones_from_home_page=None,
all_email_from_home_page=None):
self.first_name = first_name
self.middle_name = middle_name
self.last_name = last_name
self.nick_name = nick_name
self.tittle = tittle
self.company = company
self.address1 = address1
self.home_phone = home_phone
self.mobile_phone = mobile_phone
self.work_phone = work_phone
self.fax = fax
self.email1 = email1
self.email2 = email2
self.email3 = email3
self.homepage = homepage
self.bday = bday
self.bmonth = bmonth
self.byear = byear
self.aday = aday
self.amonth = amonth
self.ayear = ayear
self.address2 = address2
self.phone2 = phone2
self.notes = notes
self.id = id
self.all_phones_from_home_page = all_phones_from_home_page
self.all_email_from_home_page = all_email_from_home_page
def __repr__(self):
return "%s:%s:%s:%s:%s:%s:%s:%s:%s:%s:%s:%s:%s:%s:%s:%s:%s:%s:%s" % \
(self.id, self.first_name, self.middle_name, self.last_name, self.nick_name, self.tittle, self.company,
self.address1, self.home_phone, self.mobile_phone, self.work_phone, self.fax, self.email1, self.email2,
self.email3, self.homepage, self.address2, self.phone2, self.notes)
def __eq__(self, other):
return (self.id is None or other.id is None or self.id == other.id) and self.first_name == other.first_name \
and self.last_name == other.last_name
def id_or_max(self):
if self.id:
return int(self.id)
else:
return maxsize
| {"/bdd/contact_steps.py": ["/model/contact.py"], "/fixture/contact.py": ["/model/contact.py"], "/test/test_delete_contact.py": ["/model/contact.py"], "/test/test_add_some_contact_to_group.py": ["/model/contact.py"], "/test/test_delete_contact_from_group.py": ["/model/contact.py"], "/fixture/db.py": ["/model/contact.py"], "/generator/contact.py": ["/model/contact.py"], "/test/test_add_new_contact.py": ["/model/contact.py"], "/test/test_phones.py": ["/model/contact.py"], "/data/contacts.py": ["/model/contact.py"], "/test/test_info_contact.py": ["/model/contact.py"], "/test/test_modification_contact.py": ["/model/contact.py"]} |
43,030 | darkfox140/python_test_trening | refs/heads/main | /test/test_add_some_contact_to_group.py | from model.contact import NewContact
from model.group import Group
import random
def test_add_contact_to_group(app, orm):
if len(app.contact.get_contact_list()) == 0:
app.contact.create_new_contact(NewContact(first_name="Red21", last_name="Gena"))
if len(app.group.get_group_list()) == 0:
app.group.create(Group(name="name33", header="headre23"))
all_contacts = orm.get_contact_list()
contact = random.choice(all_contacts)
group_without_contacts = orm.get_groups_not_containing_contact(contact)
if len(group_without_contacts) == 0:
app.group.create(Group(name="name45", header="header90"))
group_without_contacts = orm.get_groups_not_containing_contact(contact)
group = random.choice(group_without_contacts)
app.contact.add_contact_to_group_by_id(contact.id, group.id, group.name)
contacts_in_group = orm.get_contacts_in_group(group)
assert contact in contacts_in_group
| {"/bdd/contact_steps.py": ["/model/contact.py"], "/fixture/contact.py": ["/model/contact.py"], "/test/test_delete_contact.py": ["/model/contact.py"], "/test/test_add_some_contact_to_group.py": ["/model/contact.py"], "/test/test_delete_contact_from_group.py": ["/model/contact.py"], "/fixture/db.py": ["/model/contact.py"], "/generator/contact.py": ["/model/contact.py"], "/test/test_add_new_contact.py": ["/model/contact.py"], "/test/test_phones.py": ["/model/contact.py"], "/data/contacts.py": ["/model/contact.py"], "/test/test_info_contact.py": ["/model/contact.py"], "/test/test_modification_contact.py": ["/model/contact.py"]} |
43,031 | darkfox140/python_test_trening | refs/heads/main | /test/test_modification_group.py | from model.group import Group
import random
def test_modification_group_name(app, db, check_ui):
if app.group.count() == 0:
app.group.create_group(Group(name="test name"))
old_groups = db.get_group_list()
group = random.choice(old_groups)
mod_group = Group(name="Клуб")
app.group.modification_group_by_id(group.id, mod_group)
assert len(old_groups) == app.group.count()
new_groups = db.get_group_list()
assert len(old_groups) == len(new_groups)
if check_ui:
assert sorted(old_groups, key=Group.id_or_max) == sorted(app.group.get_group_list(), key=Group.id_or_max)
| {"/bdd/contact_steps.py": ["/model/contact.py"], "/fixture/contact.py": ["/model/contact.py"], "/test/test_delete_contact.py": ["/model/contact.py"], "/test/test_add_some_contact_to_group.py": ["/model/contact.py"], "/test/test_delete_contact_from_group.py": ["/model/contact.py"], "/fixture/db.py": ["/model/contact.py"], "/generator/contact.py": ["/model/contact.py"], "/test/test_add_new_contact.py": ["/model/contact.py"], "/test/test_phones.py": ["/model/contact.py"], "/data/contacts.py": ["/model/contact.py"], "/test/test_info_contact.py": ["/model/contact.py"], "/test/test_modification_contact.py": ["/model/contact.py"]} |
43,032 | darkfox140/python_test_trening | refs/heads/main | /test/test_delete_contact_from_group.py | from model.contact import NewContact
from model.group import Group
import random
def test_delete_contact_from_group(app, orm):
if len(app.contact.get_contact_list()) == 0:
app.contact.create_new_contact(NewContact(first_name="Red21", last_name="Gena"))
if len(app.group.get_group_list()) == 0:
app.group.create(Group(name="name33", header="headre23"))
all_groups = orm.get_group_list()
all_contacts = orm.get_contact_list()
contact = random.choice(all_contacts)
group_with_contact = orm.get_groups_containing_contact(contact)
if len(group_with_contact) == 0:
group = random.choice(all_groups)
app.contact.add_contact_to_group_by_id(contact.id, group.id, group.name)
group_with_contact = orm.get_groups_containing_contact(contact)
group = random.choice(group_with_contact)
app.contact.delete_contact_from_group(group.id, contact.id)
contacts_not_in_group = orm.get_contacts_not_in_group(group)
assert contact in contacts_not_in_group
| {"/bdd/contact_steps.py": ["/model/contact.py"], "/fixture/contact.py": ["/model/contact.py"], "/test/test_delete_contact.py": ["/model/contact.py"], "/test/test_add_some_contact_to_group.py": ["/model/contact.py"], "/test/test_delete_contact_from_group.py": ["/model/contact.py"], "/fixture/db.py": ["/model/contact.py"], "/generator/contact.py": ["/model/contact.py"], "/test/test_add_new_contact.py": ["/model/contact.py"], "/test/test_phones.py": ["/model/contact.py"], "/data/contacts.py": ["/model/contact.py"], "/test/test_info_contact.py": ["/model/contact.py"], "/test/test_modification_contact.py": ["/model/contact.py"]} |
43,033 | darkfox140/python_test_trening | refs/heads/main | /fixture/db.py | import pymysql.cursors
from model.group import Group
from model.contact import NewContact
class DbFixture:
def __init__(self, host, name, user, password):
self.host = host
self.name = name
self.user = user
self.password = password
self.connection = pymysql.connect(host=host, database=name, user=user, password=password, autocommit=True)
def get_group_list(self):
list = []
cursor = self.connection.cursor()
try:
cursor.execute("select group_id, group_name, group_header, group_footer from group_list")
for row in cursor:
(id, name, header, footer) = row
list.append(Group(id=str(id), name=name, header=header, footer=footer))
finally:
cursor.close()
return list
def get_contact_list(self):
list = []
cursor = self.connection.cursor()
try:
cursor.execute("select id, firstname, middlename, lastname, nickname, company, title, address, home, "
"mobile, work, fax, email, email2, email3, homepage, address2, phone2,"
"notes from addressbook")
for row in cursor:
(id, firstname, middlename, lastname, nickname, company, title, address, home, mobile, work, fax,
email, email2, email3, homepage, address2, phone2, notes) = row
list.append(NewContact(id=str(id), first_name=firstname, middle_name=middlename, last_name=lastname,
nick_name=nickname, company=company, tittle=title, address1=address,
home_phone=home, mobile_phone=mobile, work_phone=work, fax=fax, email1=email,
email2=email2, email3=email3, homepage=homepage, address2=address2,
phone2=phone2, notes=notes))
finally:
cursor.close()
return list
def destroy(self):
self.connection.close() | {"/bdd/contact_steps.py": ["/model/contact.py"], "/fixture/contact.py": ["/model/contact.py"], "/test/test_delete_contact.py": ["/model/contact.py"], "/test/test_add_some_contact_to_group.py": ["/model/contact.py"], "/test/test_delete_contact_from_group.py": ["/model/contact.py"], "/fixture/db.py": ["/model/contact.py"], "/generator/contact.py": ["/model/contact.py"], "/test/test_add_new_contact.py": ["/model/contact.py"], "/test/test_phones.py": ["/model/contact.py"], "/data/contacts.py": ["/model/contact.py"], "/test/test_info_contact.py": ["/model/contact.py"], "/test/test_modification_contact.py": ["/model/contact.py"]} |
43,034 | darkfox140/python_test_trening | refs/heads/main | /generator/contact.py | from model.contact import NewContact
import random
import string
import os.path
import jsonpickle
import getopt
import sys
try:
opts, args = getopt.getopt(sys.argv[1:], "n:f:", ["number for contacts", "file"])
except getopt.GetoptError as err:
getopt.usage()
sys.exit(2)
n = 3
f = "data/contacts.json"
for o, a in opts:
if o == "-n":
n = int(a)
elif o == "-f":
f = a
def random_string(prefix, maxlen):
symbols = string.ascii_letters + " "
return prefix + "".join([random.choice(symbols) for i in range(random.randrange(maxlen))])
def random_phone(maxlen):
numbers = string.digits
return "".join([random.choice(numbers) for i in range(random.randrange(maxlen))])
def random_email(maxlen):
email = string.ascii_letters + string.digits
return "".join([random.choice(email) for i in range(random.randrange(maxlen))]) + "@" + \
"".join([random.choice(email) for i in range(random.randrange(maxlen))]) + ".com"
def random_symbols(prefix, max_len):
symbols = string.ascii_letters + string.digits + " "
return prefix + "".join([random.choice(symbols) for i in range(random.randrange(max_len))])
contact_date = [NewContact(first_name=random_string("First", 10), last_name=random_string("Last", 10),
middle_name=random_string("Middle", 10), nick_name=random_string("nick", 10),
company=random_string("Company", 20), tittle=random_string("Title", 20),
address1=random_symbols("Omskaya", 20), home_phone=random_phone(11),
mobile_phone=random_phone(11), work_phone=random_phone(11), fax=random_phone(11),
email1=random_email(6), email2=random_email(6), email3=random_email(6),
homepage=random_email(8), bday="15", bmonth="May", byear="1978", aday="25", amonth="June",
ayear="2007", address2=random_symbols("Lenina", 20), phone2=random_phone(11),
notes=random_symbols("Notes", 20))
for i in range(n)]
file = os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", f)
with open(file, "w") as out:
jsonpickle.set_encoder_options("simplejson", indent=2)
out.write(jsonpickle.encode(contact_date))
| {"/bdd/contact_steps.py": ["/model/contact.py"], "/fixture/contact.py": ["/model/contact.py"], "/test/test_delete_contact.py": ["/model/contact.py"], "/test/test_add_some_contact_to_group.py": ["/model/contact.py"], "/test/test_delete_contact_from_group.py": ["/model/contact.py"], "/fixture/db.py": ["/model/contact.py"], "/generator/contact.py": ["/model/contact.py"], "/test/test_add_new_contact.py": ["/model/contact.py"], "/test/test_phones.py": ["/model/contact.py"], "/data/contacts.py": ["/model/contact.py"], "/test/test_info_contact.py": ["/model/contact.py"], "/test/test_modification_contact.py": ["/model/contact.py"]} |
43,035 | darkfox140/python_test_trening | refs/heads/main | /test/test_add_new_contact.py | from model.contact import NewContact
def test_add_new_contact(app, db, json_contacts):
contact = json_contacts
old_contact = db.get_contact_list()
app.contact.create_new_contact(contact)
new_contact = db.get_contact_list()
old_contact.append(contact)
assert sorted(old_contact, key=NewContact.id_or_max) == sorted(new_contact, key=NewContact.id_or_max)
'''def test_add_new_contact(app, data_contacts):
contact = data_contacts
old_contact = app.contact.get_contact_list()
app.contact.create_new_contact(contact)
assert len(old_contact) + 1 == app.contact.count()
new_contact = app.contact.get_contact_list()
old_contact.append(contact)
assert sorted(old_contact, key=NewContact.id_or_max) == sorted(new_contact, key=NewContact.id_or_max)'''
| {"/bdd/contact_steps.py": ["/model/contact.py"], "/fixture/contact.py": ["/model/contact.py"], "/test/test_delete_contact.py": ["/model/contact.py"], "/test/test_add_some_contact_to_group.py": ["/model/contact.py"], "/test/test_delete_contact_from_group.py": ["/model/contact.py"], "/fixture/db.py": ["/model/contact.py"], "/generator/contact.py": ["/model/contact.py"], "/test/test_add_new_contact.py": ["/model/contact.py"], "/test/test_phones.py": ["/model/contact.py"], "/data/contacts.py": ["/model/contact.py"], "/test/test_info_contact.py": ["/model/contact.py"], "/test/test_modification_contact.py": ["/model/contact.py"]} |
43,036 | darkfox140/python_test_trening | refs/heads/main | /bdd/group_scenarios.py | from pytest_bdd import scenario
from .group_steps import *
@scenario('groups.feature', 'Add new group')
def test_add_new_group():
pass
@scenario('groups.feature', 'Delete a gruop')
def test_delete_group():
pass
| {"/bdd/contact_steps.py": ["/model/contact.py"], "/fixture/contact.py": ["/model/contact.py"], "/test/test_delete_contact.py": ["/model/contact.py"], "/test/test_add_some_contact_to_group.py": ["/model/contact.py"], "/test/test_delete_contact_from_group.py": ["/model/contact.py"], "/fixture/db.py": ["/model/contact.py"], "/generator/contact.py": ["/model/contact.py"], "/test/test_add_new_contact.py": ["/model/contact.py"], "/test/test_phones.py": ["/model/contact.py"], "/data/contacts.py": ["/model/contact.py"], "/test/test_info_contact.py": ["/model/contact.py"], "/test/test_modification_contact.py": ["/model/contact.py"]} |
43,037 | darkfox140/python_test_trening | refs/heads/main | /test/test_phones.py | from model.contact import NewContact
import re
def test_phones_on_home_page(app):
if app.contact.count() == 0:
app.contact.create_new_contact(NewContact(first_name="Victor", middle_name="Ivan", last_name="Petrov",
nick_name="Fox140", tittle="test", company="testcompany", address1="Moscow",
home_phone="8(495)2154536", mobile_phone="+79168956384",
work_phone="8-499-9576135", fax="No", email1="testemail1@facegmail.com",
email2="testemail2@facegmail.com", email3="testemail3@facegmail.com",
homepage="testhomepage.ru", bday="14", bmonth="August", byear="1987",
aday="24", amonth="October", ayear="2014", address2="Moscow, Lenina 2",
phone2="8 456 9535956", notes="Test Moscow information"))
contact_from_home_page = app.contact.get_contact_list()[0]
contact_from_edit_page = app.contact.get_contact_info_from_edit_page(0)
assert contact_from_home_page.all_phones_from_home_page == merge_phones_like_on_home_page(contact_from_edit_page)
def test_phones_on_contact_view_page(app):
if app.contact.count() == 0:
app.contact.create_new_contact(NewContact(first_name="Victor", middle_name="Ivan", last_name="Petrov",
nick_name="Fox140", tittle="test", company="testcompany", address1="Moscow",
home_phone="8(495)2154536", mobile_phone="+79168956384",
work_phone="8-499-9576135", fax="No", email1="testemail1@facegmail.com",
email2="testemail2@facegmail.com", email3="testemail3@facegmail.com",
homepage="testhomepage.ru", bday="14", bmonth="August", byear="1987",
aday="24", amonth="October", ayear="2014", address2="Moscow, Lenina 2",
phone2="8 456 9535956", notes="Test Moscow information"))
contact_from_view_page = app.contact.get_contact_from_view_page(0)
contact_from_edit_page = app.contact.get_contact_info_from_edit_page(0)
assert contact_from_view_page.home_phone == contact_from_edit_page.home_phone
assert contact_from_view_page.mobile_phone == contact_from_edit_page.mobile_phone
assert contact_from_view_page.work_phone == contact_from_edit_page.work_phone
assert contact_from_view_page.phone2 == contact_from_edit_page.phone2
def clear(s):
return re.sub('[() -]', "", s)
def merge_phones_like_on_home_page(contact):
return "\n".join(filter(lambda x: x != "",
map(lambda x: clear(x),
filter(lambda x: x is not None,
[contact.home_phone, contact.mobile_phone,
contact.work_phone, contact.phone2]))))
| {"/bdd/contact_steps.py": ["/model/contact.py"], "/fixture/contact.py": ["/model/contact.py"], "/test/test_delete_contact.py": ["/model/contact.py"], "/test/test_add_some_contact_to_group.py": ["/model/contact.py"], "/test/test_delete_contact_from_group.py": ["/model/contact.py"], "/fixture/db.py": ["/model/contact.py"], "/generator/contact.py": ["/model/contact.py"], "/test/test_add_new_contact.py": ["/model/contact.py"], "/test/test_phones.py": ["/model/contact.py"], "/data/contacts.py": ["/model/contact.py"], "/test/test_info_contact.py": ["/model/contact.py"], "/test/test_modification_contact.py": ["/model/contact.py"]} |
43,038 | darkfox140/python_test_trening | refs/heads/main | /data/contacts.py | from model.contact import NewContact
contact_data = [
NewContact(first_name="Victor", middle_name="Ivan", last_name="Petrov", nick_name="Fox140", tittle="test",
company="testcompany", address1="Moscow", home_phone="8(495)2154536", mobile_phone="+79168956384",
work_phone="8-499-9576135", fax="85663654556", email1="testemail1@facegmail.com",
email2="testemail2@facegmail.com", email3="testemail3@facegmail.com",homepage="testhomepage.ru",
bday="14", bmonth="August", byear="1987", aday="24", amonth="October", ayear="2014",
address2="Moscow, Lenina 2",phone2="8 456 9535956", notes="Test Moscow information"),
NewContact(first_name="Gena", middle_name="Kolya", last_name="Smirnov", nick_name="lis144", tittle="testtittle",
company="testcompany34", address1="Vladimir", home_phone="8(495)4267896", mobile_phone="+79162659698",
work_phone="8-499-2456247", fax="56575963526", email1="teste23mail1@facegmail.com",
email2="testemail2456@facegmail.com", email3="testemail3453@facegmail.com", homepage="testhomepage4.ru",
bday="15", bmonth="August", byear="1988", aday="25", amonth="October", ayear="2012",
address2="Omsk, Lenina 2",phone2="8 456 9535956", notes="Test Omsk information")
]
| {"/bdd/contact_steps.py": ["/model/contact.py"], "/fixture/contact.py": ["/model/contact.py"], "/test/test_delete_contact.py": ["/model/contact.py"], "/test/test_add_some_contact_to_group.py": ["/model/contact.py"], "/test/test_delete_contact_from_group.py": ["/model/contact.py"], "/fixture/db.py": ["/model/contact.py"], "/generator/contact.py": ["/model/contact.py"], "/test/test_add_new_contact.py": ["/model/contact.py"], "/test/test_phones.py": ["/model/contact.py"], "/data/contacts.py": ["/model/contact.py"], "/test/test_info_contact.py": ["/model/contact.py"], "/test/test_modification_contact.py": ["/model/contact.py"]} |
43,039 | darkfox140/python_test_trening | refs/heads/main | /test/test_info_contact.py | from model.contact import NewContact
from random import randrange
import re
'''def test_checking_contact_information_on_home_page(app):
if app.contact.count() == 0:
app.contact.create_new_contact(NewContact(first_name="Victor", middle_name="Ivan", last_name="Petrov",
nick_name="Fox140", tittle="test", company="testcompany", address1="Moscow",
home_phone="8(495)2154536", mobile_phone="+79168956384",
work_phone="8-499-9576135", fax="No", email1="testemail1@facegmail.com",
email2="testemail2@facegmail.com", email3="testemail3@facegmail.com",
homepage="testhomepage.ru", bday="14", bmonth="August", byear="1987",
aday="24", amonth="October", ayear="2014", address2="Moscow, Lenina 2",
phone2="8 456 9535956", notes="Test Moscow information"))
old_contact = app.contact.get_contact_list()
index = randrange(len(old_contact))
contact_from_home_page = app.contact.get_contact_list()[index]
contact_from_edit_page = app.contact.get_contact_info_from_edit_page(index)
assert contact_from_home_page.first_name == contact_from_edit_page.first_name
assert contact_from_home_page.last_name == contact_from_edit_page.last_name
assert contact_from_home_page.address1 == contact_from_edit_page.address1
assert contact_from_home_page.all_phones_from_home_page == merge_phones_like_on_home_page(contact_from_edit_page)
assert contact_from_home_page.all_email_from_home_page == merge_email_like_on_home_page(contact_from_edit_page)'''
def clear(s):
return re.sub('[() -]', "", s)
def merge_phones_like_on_home_page(contact):
return "\n".join(filter(lambda x: x != "",
map(lambda x: clear(x),
filter(lambda x: x is not None, [contact.home_phone, contact.mobile_phone,
contact.work_phone, contact.phone2]))))
def merge_email_like_on_home_page(contact):
return "\n".join(filter(lambda x: x != "",
map(lambda x: clear(x),
filter(lambda x: x is not None,
[contact.email1, contact.email2, contact.email3]))))
def test_contact_db_info_matches_ui(app, db):
ui_list = app.contact.get_contact_list()
print("ui list", ui_list)
def clean(contact):
return NewContact(id=contact.id, first_name=contact.first_name.strip(), last_name=contact.last_name.strip(),
address1=contact.address1.strip(),
all_phones_from_home_page=merge_phones_like_on_home_page(contact),
all_email_from_home_page=merge_email_like_on_home_page(contact))
db_list = map(clean, db.get_contact_list())
print("db list", db_list)
assert sorted(ui_list, key=NewContact.id_or_max) == sorted(db_list, key=NewContact.id_or_max)
| {"/bdd/contact_steps.py": ["/model/contact.py"], "/fixture/contact.py": ["/model/contact.py"], "/test/test_delete_contact.py": ["/model/contact.py"], "/test/test_add_some_contact_to_group.py": ["/model/contact.py"], "/test/test_delete_contact_from_group.py": ["/model/contact.py"], "/fixture/db.py": ["/model/contact.py"], "/generator/contact.py": ["/model/contact.py"], "/test/test_add_new_contact.py": ["/model/contact.py"], "/test/test_phones.py": ["/model/contact.py"], "/data/contacts.py": ["/model/contact.py"], "/test/test_info_contact.py": ["/model/contact.py"], "/test/test_modification_contact.py": ["/model/contact.py"]} |
43,040 | darkfox140/python_test_trening | refs/heads/main | /test/test_modification_contact.py | from model.contact import NewContact
import random
def test_modification_first_contact_address1(app, db, check_ui):
if app.contact.count() == 0:
app.contact.create_new_contact(NewContact(first_name="Victor", middle_name="Ivan", last_name="Petrov",
nick_name="Fox140", tittle="test", company="testcompany", address1="Moscow",
home_phone="8(495)2154536", mobile_phone="+79168956384",
work_phone="8-499-9576135", fax="No", email1="testemail1@facegmail.com",
email2="testemail2@facegmail.com", email3="testemail3@facegmail.com",
homepage="testhomepage.ru", bday="14", bmonth="August", byear="1987",
aday="24", amonth="October", ayear="2014", address2="Moscow, Lenina 2",
phone2="8 456 9535956", notes="Test Moscow information"))
old_contact = db.get_contact_list()
contact = random.choice(old_contact)
mod_contact = NewContact(first_name="Petya", last_name="Petrov")
app.contact.modification_contact_by_id(contact.id, mod_contact)
assert len(old_contact) == app.contact.count()
new_contacts = db.get_contact_list()
assert len(old_contact) == len(new_contacts)
if check_ui:
assert sorted(old_contact, key=NewContact.id_or_max) == \
sorted(app.group.get_group_list(), key=NewContact.id_or_max)
'''def test_modification_first_contact_birthday(app):
if app.contact.count() == 0:
app.contact.create_new_contact(NewContact(bday="01", bmonth="January", byear="2000"))
old_contact = app.contact.get_contact_list()
app.contact.modification_first_contact((NewContact(bday="24", bmonth="March", byear="1996")))
new_contact = app.contact.get_contact_list()
assert len(old_contact) == len(new_contact)
def test_modification_first_contact_birthday_anniversary(app):
if app.contact.count() == 0:
app.contact.create_new_contact(NewContact(bday="01", bmonth="January", byear="2000"))
old_contact = app.contact.get_contact_list()
app.contact.modification_first_contact((NewContact(aday="22", amonth="February", ayear="19988")))
new_contact = app.contact.get_contact_list()
assert len(old_contact) == len(new_contact)'''
| {"/bdd/contact_steps.py": ["/model/contact.py"], "/fixture/contact.py": ["/model/contact.py"], "/test/test_delete_contact.py": ["/model/contact.py"], "/test/test_add_some_contact_to_group.py": ["/model/contact.py"], "/test/test_delete_contact_from_group.py": ["/model/contact.py"], "/fixture/db.py": ["/model/contact.py"], "/generator/contact.py": ["/model/contact.py"], "/test/test_add_new_contact.py": ["/model/contact.py"], "/test/test_phones.py": ["/model/contact.py"], "/data/contacts.py": ["/model/contact.py"], "/test/test_info_contact.py": ["/model/contact.py"], "/test/test_modification_contact.py": ["/model/contact.py"]} |
43,041 | abhisek11/nimbus.ai | refs/heads/master | /sentimeter/sentimeter.py |
from secrets import Oauth_Secrets
import tweepy
from textblob import TextBlob
import pandas as pd
def primary(input_hashtag):
secrets = Oauth_Secrets() #secrets imported from secrets.py
auth = tweepy.OAuthHandler(secrets.consumer_key, secrets.consumer_secret)
auth.set_access_token(secrets.access_token, secrets.access_token_secret)
api = tweepy.API(auth)
N = 1000 #Number of Tweets
Tweets = tweepy.Cursor(api.search, q=input_hashtag).items(N)
# Tweets=tweepy.Cursor(api.search,q=input_hashtag + " -filter:retweets",rpp=5,lang="en", tweet_mode='extended').items(50)
# tweets_list = []
# for tweet in Tweets:
# temp = {}
# temp["text"] = tweet.full_text
# temp["username"] = tweet.user.screen_name
# tweets_list.append(temp)
# print("tweets::::::",tweets_list)
neg = 0.0
pos = 0.0
pos_list=[]
nev_list=[]
neut_list=[]
neg_count = 0
neutral_count = 0
pos_count = 0
# data = pd.DataFrame(data=[[tweet.text,tweet.created_at,tweet.user.screen_name,tweet.user.location,tweet.user.id,tweet.user.created_at,tweet.user.description] for tweet in Tweets],
# columns=['Tweets','date','user','location','id','join_date','profile_description'])
for tweet in Tweets:
tweet_data_dict={}
tweet_data_dict={
'text':tweet.text,
'created_at':tweet.created_at,
'screen_name':tweet.user.screen_name,
'user_location':tweet.user.location,
'user_id':tweet.user.id,
'user_created_at':tweet.user.created_at,
'tweet_user_description':tweet.user.description
}
# print(tweet.)
blob = TextBlob(tweet.text)
if blob.sentiment.polarity < 0: #Negative
neg += blob.sentiment.polarity
neg_count += 1
nev_list.append(tweet_data_dict)
elif blob.sentiment.polarity == 0: #Neutral
neutral_count += 1
neut_list.append(tweet_data_dict)
else: #Positive
pos += blob.sentiment.polarity
pos_count += 1
pos_list.append(tweet_data_dict)
print('pos_list',len(pos_list),'nev_list',len(nev_list),'neut_list',len(neut_list))
# print(nev_list)
return [['Sentiment', 'no. of tweets'],['Positive',pos_count]
,['Neutral',neutral_count],['Negative',neg_count],{'Positive_list':pos_list},
{'Negative_list':nev_list},{'Neutral_list':neut_list}] | {"/sentimeter/sentimeter.py": ["/secrets.py"]} |
43,042 | abhisek11/nimbus.ai | refs/heads/master | /secrets.py | #this file contains sensitive information like django secret key
#edit this according to your requirement
class Django_Secrets:
def __init__(self):
self.key = ''
class Oauth_Secrets:
def __init__(self):
self.consumer_key = "AMskkMrTiil0Re1iKuJcQHseH"
self.consumer_secret = "fZ0nOB4IqqYka7P70EAVkHkRFeFjTYXC1dIuUaWn3gF8YiCp9a"
self.access_token = "3135870607-MXL8UNUuZEWcgHE6wdN2kTYpqumiQWC5FVNpnUR"
self.access_token_secret = "qMtb33qKZeGyMxqYJVICOjTYNuqZUOyhIlNBIlyrJWmOW"
| {"/sentimeter/sentimeter.py": ["/secrets.py"]} |
43,043 | abhisek11/nimbus.ai | refs/heads/master | /sentimeter/views.py | from django.shortcuts import render
from django.template import loader
from django.http import HttpResponse
from .forms import userinput
from sentimeter import sentimeter
# import HTML
def index(request):
user_input = userinput()
return render(request, "index.html", {'input_hastag': user_input})
def analyse(request):
user_input = userinput(request.GET or None)
if request.GET and user_input.is_valid():
input_hastag = user_input.cleaned_data['q']
print(input_hastag)
data_all = sentimeter.primary(input_hastag)
# data = input_hastag
data=data_all[:4]
data_p_n_nu=data_all[4:]
# for req_data in data_p_n_nu:
data_positive=data_p_n_nu[0]
data_negative=data_p_n_nu[1]
data_neutral=data_p_n_nu[2]
positive_list=[[x['text'],x['screen_name'],x['created_at'],x['user_location'],x['user_id']]
for x in data_positive['Positive_list'] ]
negative_list=[[x['text'],x['screen_name'],x['created_at'],x['user_location'],x['user_id']]
for x in data_negative['Negative_list'] ]
neutral_list=[[x['text'],x['screen_name'],x['created_at'],x['user_location'],x['user_id']]
for x in data_neutral['Neutral_list'] ]
print("data_positive",data_negative)
# image=request.build_absolute_uri('/sentimeter/static/media/abg1.png'.url)
# print('image',image)
return render(request, "result.html", {'data': data,'data_positive':positive_list,
'data_negative':negative_list,'data_neutral':neutral_list,'input_hastag': input_hastag})
return render(request, "index.html", {'input_hastag': user_input})
| {"/sentimeter/sentimeter.py": ["/secrets.py"]} |
43,044 | IR3b00t/Facial_Recognition | refs/heads/master | /src/sendMail.py | import smtplib
import json
import os
from email.mime.text import MIMEText as text
from src.log import *
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
'''
Function to send mail
message = the message you want to send
subject = the subject of your message
config is loaded from a JSON. (will change in futur)
'''
def sendMail(message, subject):
print(message)
# Load the mail server configuration ( user mailconfig.json template )
with open(BASE_DIR + '/config/mailconfig.json') as config_json:
config = json.load(config_json)
HOST = config['mail']['HOST']
MY_ADRESS = config['mail']['USER']
PASSWD = config['mail']['PASSWD']
PORT = config['mail']['PORT']
# Load contact list ( use contact.json template )
with open(BASE_DIR + '/config/contact.json') as contact_json:
contacts = json.load(contact_json)
for contact in contacts:
CONTACT_NAME = contacts[contact]['NAME']
CONTACT_ADRESS = contacts[contact]['ADRESS']
# Add server info and start SSL/TLS
s = smtplib.SMTP(host=HOST, port=PORT)
s.starttls()
try:
# Try to log to the mail server
s.login(MY_ADRESS, PASSWD)
except smtplib.SMTPAuthenticationError:
writeLogFile(
'mail', 'critical', 'FAILED: Server retuned bad username or password')
break
except smtplib.SMTPException:
writeLogFile(
'mail', 'critical', 'FAILED: SERVER ABOUT TO DESTROY HUMANITY')
break
# Let's configure the mail
message_to_send = text(message)
message_to_send['From'] = MY_ADRESS
message_to_send['To'] = CONTACT_ADRESS
message_to_send['Subject'] = subject
# Send the mail or not obviously
if not s.sendmail(MY_ADRESS, CONTACT_ADRESS, message_to_send.as_string()):
writeLogFile('mail', 'info', 'The mail has been sent')
else:
print('An error occured. Check log !')
s.quit()
| {"/src/sendMail.py": ["/src/log.py"], "/main.py": ["/src/sendMail.py", "/src/log.py"]} |
43,045 | IR3b00t/Facial_Recognition | refs/heads/master | /main.py |
import os
import pickle
import sys
import time
import datetime
from threading import Thread
import cv2
import imutils
import numpy as np
from src.sendMail import *
from src.log import *
class Detection(Thread):
def __init__(self):
Thread.__init__(self)
self.state = True
'''
CASCADE CONFIGURATION
You can add here any cascade configuration you want to use. I only use FACE and EYES for now
'''
self.FACE_CASCADE = cv2.CascadeClassifier(
cv2.data.haarcascades + 'haarcascade_frontalface_default.xml')
self.EYES_CASCADE = cv2.CascadeClassifier(
cv2.data.haarcascades + 'haarcascade_eye.xml')
# Device used for video input
self.camera = cv2.VideoCapture(0)
self.BASE_DIR = os.path.dirname(os.path.abspath(__file__))
self.flag = 0
self.date = datetime.datetime.now()
def run(self):
# CONF RECOGNITION
RECOGNIZER = cv2.face.LBPHFaceRecognizer_create()
RECOGNIZER.read(self.BASE_DIR + "/src/trainner.yml")
hog = cv2.HOGDescriptor()
hog.setSVMDetector(cv2.HOGDescriptor_getDefaultPeopleDetector())
labels = {"person_name": 1}
with open(self.BASE_DIR + "/src/lables.pickle", 'rb') as f:
og_labels = pickle.load(f)
labels = {v: k for k, v in og_labels.items()}
# Camera resolution
self.camera.set(cv2.CAP_PROP_FRAME_WIDTH, 1280)
self.camera.set(cv2.CAP_PROP_FRAME_HEIGHT, 720)
# camera FPS
self.camera.set(cv2.CAP_PROP_FPS, 30)
# FONCTIONS
def FaceDetection(frame, gray):
faces = self.FACE_CASCADE.detectMultiScale(
gray, scaleFactor=1.3, minNeighbors=4)
for(x, y, z, h) in faces:
color_face = (0, 200, 0) # BGR 0-255
stroke = 2
end_coord_x = x + z
end_coord_y = y + h
cv2.rectangle(frame, (x, y), (end_coord_x, end_coord_y),
color_face, stroke)
FacialRecognition(faces, gray, frame)
def FacialRecognition(faces, gray, frame):
for(x, y, z, h) in faces:
roi_gray = gray[y:y+h, x:x+z]
# reconaissance
id_, conf = RECOGNIZER.predict(roi_gray)
if conf < 98:
print(labels[id_])
font = cv2.FONT_HERSHEY_SIMPLEX
name = labels[id_]
color = (255, 0, 0)
stroke = 1
cv2.putText(frame, name, (x, y), font, 1,
color, stroke, cv2.LINE_AA)
self.flag = 0
else:
# Do something when a person has been detected but not reconized
print(' Unkown person detected')
self.flag += 1
if self.flag == 5:
print('Flag at 5')
sendMail('Unkown person detected in your house !',
'Unkown person detected')
self.flag = 0
while(self.state == True):
# capture frame par frame
ret, frame = self.camera.read()
# Conversion to Grey shape
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
FaceDetection(frame, gray)
# Display frame
cv2.imshow('Reconaissance faciale', frame)
cv2.namedWindow('Reconaissance faciale', cv2.WINDOW_OPENGL)
if cv2.waitKey(20) & 0xFF == ord('q'):
break
# When done, we stop capturing and release camera
self.camera.release()
cv2.destroyAllWindows()
def stop(self):
self.state = False
# Starting detection thread
detection = Detection()
detection.start()
| {"/src/sendMail.py": ["/src/log.py"], "/main.py": ["/src/sendMail.py", "/src/log.py"]} |
43,046 | IR3b00t/Facial_Recognition | refs/heads/master | /src/face-train.py | import os
import cv2
from PIL import Image
import numpy as np
import pickle
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
IMAGE_DIR = os.path.join(BASE_DIR, "images")
FACE_CASCADE = cv2.CascadeClassifier(
cv2.data.haarcascades + 'haarcascade_frontalface_alt2.xml')
RECOGNIZER = cv2.face.LBPHFaceRecognizer_create()
current_id = 0
label_ids = {}
y_label = []
x_train = []
# recupérer les images dans leurs dossiers
for root, dirs, files in os.walk(IMAGE_DIR):
for file in files:
if file.endswith("png") or file.endswith('jpg') or file.endswith('jpeg'):
path = os.path.join(root, file)
label = os.path.basename(root).replace(' ', '-').lower()
#print(label, path)
if not label in label_ids:
label_ids[label] = current_id
current_id += 1
id_ = label_ids[label]
# print(label_ids)
pil_image = Image.open(path).convert("L") # convertir en gris
size = (560, 560)
final_image = pil_image.resize(size, Image.ANTIALIAS)
image_array = np.array(final_image, "uint8")
# print(image_array)
faces = FACE_CASCADE.detectMultiScale(
image_array, scaleFactor=1.1, minNeighbors=1, minSize=(1, 1))
for(x, y, z, h) in faces:
roi = image_array[y:y+h, x:x+z]
x_train.append(roi)
y_label.append(id_)
with open("lables.pickle", 'wb') as f:
pickle.dump(label_ids, f)
RECOGNIZER.train(x_train, np.array(y_label))
RECOGNIZER.save("trainner.yml")
| {"/src/sendMail.py": ["/src/log.py"], "/main.py": ["/src/sendMail.py", "/src/log.py"]} |
43,047 | IR3b00t/Facial_Recognition | refs/heads/master | /src/log.py | import logging
from logging.handlers import RotatingFileHandler
import os
from os import path
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
LOG_DIR = "/output/log/"
'''
This function is to check if the file already exist in the directory config. If exist, we
do nothing else we create the file.
logName = the name of the log that need to be check
'''
def checkLogFileExist(logName):
if not path.exists(BASE_DIR+LOG_DIR+logName+".txt"):
logFile = open(BASE_DIR+LOG_DIR+logName+'.txt', 'x')
logFile.close()
'''
This function is used for write log.
logName = describe the name of the log to write and what the log is for.
level = level of log to be used. 4 levels used: INFO, DEBUG, WARNING, CRITICAL
message = the messsage who come with the level. Not limited in caractere.
It describe the action done before logging.
'''
def writeLogFile(logName, level, message):
# We check if file already exist or ifd we need to create it
checkLogFileExist(logName)
# Creation of the 'logger' which permit to write down the log
logger = logging.getLogger()
logger.setLevel(logging.DEBUG)
formatter = logging.Formatter(
'%(asctime)s :: %(levelname)s :: %(message)s')
log_handler = RotatingFileHandler(
BASE_DIR+LOG_DIR+logName+".txt", 'a', 5000000, 1)
log_handler.setLevel(logging.DEBUG)
log_handler.setFormatter(formatter)
logger.addHandler(log_handler)
# here we write the log depending on it's level
try:
if level is 'info':
logger.info(message)
except level is 'debug':
logger.debug(message)
except level is 'warning':
logger.warning(message)
except level is 'critical':
logger.critical(message)
| {"/src/sendMail.py": ["/src/log.py"], "/main.py": ["/src/sendMail.py", "/src/log.py"]} |
43,049 | ashwin1609/iAttend-Facial-Recognition-App | refs/heads/main | /register.py |
import sys
from PyQt5.QtCore import Qt
from PyQt5.QtGui import QFont
from PyQt5.QtWidgets import QLineEdit
from PyQt5.QtWidgets import QPushButton
from PyQt5.QtMultimedia import *
from PyQt5.QtMultimediaWidgets import *
from PyQt5.QtWidgets import *
import os
# Register Page
class RegisterWindow(QMainWindow):
def __init__(self):
super().__init__()
self.height = 525
self.width = 750
self.setWindowTitle("Register")
self.setStyleSheet("background : #006699;")
def initUI(self):
# text box
self.nameLabel = QLabel(self)
self.nameLabel.setText('ENTER YOUR INFO :')
self.nameLabel.resize(215,40)
self.nameLabel.setFont(QFont('Times', 13))
self.nameLabel.move(270,80)
self.textbox = QLineEdit(self)
self.textbox.resize(250, 40)
self.textbox.move(200, 10)
# # log in button
# self.login_button = QPushButton(self)
# self.login_button.setText('LOG IN')
# self.login_button.move(445, 735)
# self.login_button.resize(100, 40)
# self.login_button.setStyleSheet("background-color: #b3e6ff;")
# #self.login_button.click.connect(self,openLogin)
#shadow effect for the label
shadow = QGraphicsDropShadowEffect()
shadow.setBlurRadius(15)
self.nameLabel.setGraphicsEffect(shadow)
self.textbox.setStyleSheet("background-color: #b3e6ff;"
"border-style: outset;"
"border-width: 2px;"
"border-color: beige;")
capture_button = QAction("CAPTURE", self)
capture_button.triggered.connect(self.click_photo)
capture_button.setFont(QFont('Times', 10))
# camera code
# finds available camera
self.available_cameras = QCameraInfo.availableCameras()
camera_selector = QComboBox()
camera_selector.addItems([camera.description()
for camera in self.available_cameras])
camera_selector.currentIndexChanged.connect(self.select_camera)
if not self.available_cameras:
capture_button.setDisabled(True)
camera_selector.setDisabled(True)
self.viewfinder = QLabel()
self.viewfinder.setText("No cameras were found")
self.viewfinder.setAlignment(Qt.AlignCenter)
self.setCentralWidget(self.viewfinder)
#sys.exit()
else:
#change image path
self.save_path = "img/images"
self.viewfinder = QCameraViewfinder()
self.setCentralWidget(self.viewfinder)
self.select_camera(0)
self.viewfinder.show()
# creating a tool bar
toolbar = QToolBar("Camera Tool Bar")
self.addToolBar(toolbar)
toolbar.addAction(capture_button)
toolbar.setStyleSheet("background :#FCDBA9;")
toolbar.setFixedHeight(60)
toolbar.addWidget(camera_selector)
toolbar.addWidget(self.nameLabel)
toolbar.addWidget(self.textbox)
def select_camera(self, i):
self.camera = QCamera(self.available_cameras[i])
self.camera.setViewfinder(self.viewfinder)
self.camera.setCaptureMode(QCamera.CaptureStillImage)
self.camera.start()
self.capture = QCameraImageCapture(self.camera)
self.current_camera_name = self.available_cameras[i].description()
def click_photo(self):
#mypath = os.path.join(self.save_path, "%s.jpg" % (self.textbox.text()))
#change images folder path
self.capture.capture(f'D:\Projects\Group\iAttend\img\images\{self.textbox.text()}.jpg')
self.textbox.clear()
if __name__ == "__main__":
app = QApplication(sys.argv)
win2 = RegisterWindow()
sys.exit(app.exec_())
| {"/login.py": ["/main.py"], "/home.py": ["/register.py", "/login.py"]} |
43,050 | ashwin1609/iAttend-Facial-Recognition-App | refs/heads/main | /main.py | import numpy as np
import cv2
import face_recognition
import os
from datetime import date
import datetime, time
images = []
known_names = []
encodings = []
names_list = []
def face_recog(img):
if not img.any():
placeholder_img = cv2.imread('img/placeholder.jpg')
font = cv2.FONT_HERSHEY_SIMPLEX
scale = 1.5
message = "Webcam not detected"
text_size = cv2.getTextSize(message, font, scale, 2)[0]
text_x = (placeholder_img.shape[1] - text_size[0]) / 2
text_y = (placeholder_img.shape[0] + text_size[1]) / 2
cv2.putText(placeholder_img, message, (int(text_x), int(text_y)), font, scale, (255, 255, 255), 2)
resized_img = cv2.resize(placeholder_img, (750, 525))
return resized_img
else:
# Grab a frame of video
cap_img = img
# Finds all the faces and their encodings in the current frame of video
cap_face_loc = face_recognition.face_locations(cap_img)
cap_face_enc = face_recognition.face_encodings(cap_img, cap_face_loc)
# i and j represent each single face encoding and face location
for i,j in zip(cap_face_enc, cap_face_loc):
comparison = face_recognition.compare_faces(encodings, i)
distances = face_recognition.face_distance(encodings, i)
#print(distance)
smallest_distance = np.argmin(distances)
top, right, bottom, left = j
color = (255, 0, 0)
color2 = (0, 0, 255)
font = cv2.FONT_HERSHEY_PLAIN
if comparison[smallest_distance]:
student_name = names_list[smallest_distance].upper()
for i in os.listdir('img/images'):
student_number = known_names[smallest_distance][1]
#makes rectangle with the name on each located face
cv2.rectangle(cap_img,(left,top),(right,bottom), color , cv2.LINE_4)
cv2.putText(cap_img, student_name,(left+8, top -8), font , 1, color2, 2)
takeAttendance(student_name,student_number)
resized_img = cv2.resize(cap_img, (750, 525))
return resized_img
def getImages(path):
known_images = os.listdir(path)
j = 0
for i in known_images:
img = cv2.imread(f'{path}/{i}')
images.append(img)
known_names.append(os.path.splitext(i)[0].split("_"))
names_list.append(known_names[j][0])
j+=1
#print(names_list)
return names_list
def getEncodings(images):
encodedList = []
for img in images:
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
encoded = face_recognition.face_encodings(img)[0]
encodedList.append(encoded)
encodings = encodedList
return encodedList
def takeAttendance(student_name,student_number):
file = open('attendance_list.csv', 'r+')
data = file.readlines()
names = []
for i in data:
line_list = i.split(',')
names.append(line_list[0])
# if student_name not in names:
x = datetime.datetime.now()
file.writelines(f'\n{student_name},{student_number},{x.strftime("%a %b %d")},{x.strftime("%X")}')
#getImages('img/images')
#encodings = getEncodings(images)
#print('Encoding Complete!')
#face_recog()
| {"/login.py": ["/main.py"], "/home.py": ["/register.py", "/login.py"]} |
43,051 | ashwin1609/iAttend-Facial-Recognition-App | refs/heads/main | /login.py |
import sys
import time
import cv2
import numpy as np
from PyQt5.QtCore import Qt
from PyQt5.QtGui import QFont
from PyQt5.QtWidgets import QLineEdit
from PyQt5.QtWidgets import QPushButton
from PyQt5.QtMultimedia import *
from PyQt5.QtMultimediaWidgets import *
from PyQt5.QtWidgets import *
from PyQt5 import QtGui, QtWidgets, QtCore
import main
import os
class WorkerThread(QtCore.QObject):
def __init__(self, updatefunc):
super().__init__()
self.update = updatefunc
@QtCore.pyqtSlot()
def run(self):
while True:
# Long running task ...
self.update()
time.sleep(1)
# Register Page
class LoginWindow(QMainWindow):
def __init__(self):
super().__init__()
self.setWindowTitle("Login")
self.initUI()
self.setStyleSheet("background : #006699;")
self.height = 525
self.width = 750
def initUI(self):
self.image_frame = QLabel(self)
self.image_frame.setAlignment(Qt.AlignCenter)
self.image_frame.resize(750, 525)
self.layout = QVBoxLayout()
self.layout.addWidget(self.image_frame)
self.setLayout(self.layout)
main.getImages('img/images')
main.encodings = main.getEncodings(main.images)
def start(self):
self.cap = cv2.VideoCapture(0, cv2.CAP_DSHOW)
self.worker = WorkerThread(lambda: self.display())
self.workerThread = QtCore.QThread()
self.workerThread.started.connect(self.worker.run)
self.worker.moveToThread(self.workerThread)
self.workerThread.start()
def display(self):
# if not self.cap.isOpened():
#self.cap.open(0)
ret, cam_img = self.cap.read()
uiImage = main.face_recog(cam_img)
# number of bytes per line (total size of image / height in px)
bytesWidth = uiImage.size * uiImage.itemsize / uiImage.shape[0]
self.image = QtGui.QImage(uiImage.data, 750, 525, bytesWidth, QtGui.QImage.Format_BGR888)
self.image_frame.setPixmap(QtGui.QPixmap.fromImage(self.image))
self.show()
if __name__ == "__main__":
app = QApplication(sys.argv)
win2 = LoginWindow()
sys.exit(app.exec_()) | {"/login.py": ["/main.py"], "/home.py": ["/register.py", "/login.py"]} |
43,052 | ashwin1609/iAttend-Facial-Recognition-App | refs/heads/main | /home.py | import time
from PyQt5 import QtWidgets, QtCore
from PyQt5.QtCore import pyqtSlot, QObject, pyqtSignal
from PyQt5.QtGui import QPixmap
from PyQt5.QtWidgets import QPushButton
from PyQt5.QtWidgets import *
from register import RegisterWindow
from login import LoginWindow
def goToRegister(stacked_widget, registerPage):
stacked_widget.setCurrentIndex(1)
registerPage.initUI()
def goToLogin(stacked_widget, loginPage):
stacked_widget.setCurrentIndex(2)
loginPage.start()
def goToHome(stacked_widget):
stacked_widget.setCurrentIndex(0)
# Main Page
class HomeWindow(QMainWindow):
def __init__(self):
super().__init__()
self.title = "App"
self.InitUI()
self.height = 525
self.width = 750
def InitUI(self):
self.setAutoFillBackground(True)
self.setWindowTitle("iAttend App")
self.setStyleSheet("QMainWindow {\n"
" background-color: #006699;\n}\n"
"QPushButton {\n"
" background-color: #b3e6ff; border: 1px solid black;\n"
" border-radius: 5px; font: bold 16px;\n }\n"
"QTextBrowser {\n"
" background-color: #b3e6ff;; border: 1px solid black;\n"
" border-radius: 5px; font-size: 10pt; font-weight:400; font-style:normal; \n" "}")
# Logo
self.logo = QLabel(self)
self.pixmap = QPixmap('logo/iAttend.png')
self.logo.setPixmap(self.pixmap)
self.logo.resize(200, 200)
self.logo.move(270, 10)
# Message Box
self.message = QtWidgets.QTextBrowser(self)
self.message.resize(500, 90)
self.message.move(130, 220)
self.message.setText("Welcome to iAttend, a facial recognition based attendance system created by group 23. "
"Please click the register button, add your name and student number ('name_studentnumber') click the capture button to take a picture and save your name."
" Once the registration is completed, click the login button to take your attendance.")
# Register Button
self.register = QPushButton(self)
self.register.resize(271, 71)
self.register.move(90, 380)
self.register.setText("REGISTER")
# Log In button
self.login = QPushButton(self)
self.login.resize(271, 71)
self.login.move(400, 380)
self.login.setText("LOG IN")
if __name__ == "__main__":
import sys
app = QApplication(sys.argv)
homeWindow = HomeWindow()
registerWindow = RegisterWindow()
loginWindow = LoginWindow()
widget = QStackedWidget()
widget.addWidget(homeWindow)
widget.addWidget(registerWindow)
widget.addWidget(loginWindow)
# set up the navigation buttons
homeWindow.register.clicked.connect(lambda: goToRegister(widget, registerWindow))
homeWindow.login.clicked.connect(lambda: goToLogin(widget, loginWindow))
widget.setFixedSize(750, 525)
widget.show()
sys.exit(app.exec_())
| {"/login.py": ["/main.py"], "/home.py": ["/register.py", "/login.py"]} |
43,053 | ashwin1609/iAttend-Facial-Recognition-App | refs/heads/main | /test.py | import numpy as np
import cv2
import face_recognition
#image path
path = 'images\messi.jpg'
img1 = cv2.imread(path)
path2 = r'D:\Projects\Group\iAttend\images\123.png'
test_img1 = cv2.imread(path2)
#returns an array of bounding box of the test face
face_Location = face_recognition.face_locations(test_img1)[0]
#returns a list of 128-dimensional face encodings for each face in the images
face_Encoding = face_recognition.face_encodings(img1)[0]
face_Encoding2 = face_recognition.face_encodings(test_img1)[0]
#A list of tuples of found face locations in css (top, right, bottom, left) order
start_point = (face_Location[3], face_Location[0])
end_point = (face_Location[1], face_Location[2])
color = (255, 0, 0)
#makes rectangle on located face
cv2.rectangle(test_img1,start_point,end_point, color , cv2.LINE_4)
#comparing known face (in the list) with the test face
comparison = face_recognition.compare_faces([face_Encoding], face_Encoding2)
distance = face_recognition.face_distance([face_Encoding],face_Encoding2)
print(comparison, distance)
#Displaying images
cv2.imshow('Lionel Messi', img1)
cv2.imshow('Messi Test', test_img1)
cv2.waitKey(0)
| {"/login.py": ["/main.py"], "/home.py": ["/register.py", "/login.py"]} |
43,072 | sxTrp/mirco | refs/heads/master | /tasks/dms_worker.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 18-12-24 上午10:38
# @Author : ShaoXin
# @Summary :
# @Software: PyCharm
from time import sleep
from celery import Celery
from tools.logger import code_log
tags_task = Celery('tags')
tags_task.config_from_object('config.celery_config')
@tags_task.task
def dms_work(params):
code_log.error(f'begin worker {params}')
sleep(5)
code_log.error(f'end worker {params}')
| {"/tasks/dms_worker.py": ["/tools/logger.py"], "/config/celery_config.py": ["/config/zk_config.py"], "/tools/logger.py": ["/config/pj_config.py"], "/config/zk_config.py": ["/config/pj_config.py"], "/consumer/dms_consumer.py": ["/tools/logger.py", "/tools/redis_cli.py", "/tasks/dms_worker.py"], "/consumer/tmp_pd_one.py": ["/tools/redis_cli.py"]} |
43,073 | sxTrp/mirco | refs/heads/master | /config/celery_config.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 18-12-24 上午10:42
# @Author : ShaoXin
# @Summary :
# @Software: PyCharm
from config.zk_config import master_name, celery_broker, broker_password
CELERY_TIMEZONE = 'Asia/Shanghai'
BROKER_TRANSPORT_OPTIONS = {'master_name': master_name}
BROKER_URL = celery_broker
BROKER_PASSWORD = broker_password
CELERYD_HIJACK_ROOT_LOGGER = False # 禁用celery日志
TASK_SERIALIZER = 'json',
CELERY_ACCEPT_CONTENT = ['json'], # Ignore other content
CELERY_RESULT_SERIALIZER = 'json'
| {"/tasks/dms_worker.py": ["/tools/logger.py"], "/config/celery_config.py": ["/config/zk_config.py"], "/tools/logger.py": ["/config/pj_config.py"], "/config/zk_config.py": ["/config/pj_config.py"], "/consumer/dms_consumer.py": ["/tools/logger.py", "/tools/redis_cli.py", "/tasks/dms_worker.py"], "/consumer/tmp_pd_one.py": ["/tools/redis_cli.py"]} |
43,074 | sxTrp/mirco | refs/heads/master | /tools/logger.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 18-8-8 上午10:49
# @Author : ShaoXin
# @Summary : 日志工具
# @Software: PyCharm
import os
from logging import config, getLogger
from config.pj_config import BASEDIR, LOG_PATH
os.environ.setdefault('log_path', LOG_PATH)
config.fileConfig(os.path.join(BASEDIR, 'conf', "logging.ini"))
code_log = getLogger()
if __name__ == '__main__':
code_log.info("Here is a very exciting log message, just for you")
| {"/tasks/dms_worker.py": ["/tools/logger.py"], "/config/celery_config.py": ["/config/zk_config.py"], "/tools/logger.py": ["/config/pj_config.py"], "/config/zk_config.py": ["/config/pj_config.py"], "/consumer/dms_consumer.py": ["/tools/logger.py", "/tools/redis_cli.py", "/tasks/dms_worker.py"], "/consumer/tmp_pd_one.py": ["/tools/redis_cli.py"]} |
43,075 | sxTrp/mirco | refs/heads/master | /config/zk_config.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 18-12-24 上午10:01
# @Author : ShaoXin
# @Summary : 加载zk配置文件
# @Software: PyCharm
import json
from config.pj_config import ZK_HOSTS, PROJECT_NAME, ENV
from kazoo.client import KazooClient
class ZkConnectException(Exception):
pass
try:
zk = KazooClient(hosts=ZK_HOSTS)
zk.start()
except Exception as e:
raise ZkConnectException("ZK cannot connect, please contact xxx to resolve it.")
def get_config_by_env(name, is_json=False):
data = zk.get(f"/{PROJECT_NAME}/{ENV.lower()}/{name}")[0].decode('utf8')
return json.loads(data) if is_json else data
master_name = get_config_by_env("celery/master_name")
celery_broker = get_config_by_env("celery/celery_broker")
broker_password = get_config_by_env("celery/broker_password")
if __name__ == '__main__':
pass
| {"/tasks/dms_worker.py": ["/tools/logger.py"], "/config/celery_config.py": ["/config/zk_config.py"], "/tools/logger.py": ["/config/pj_config.py"], "/config/zk_config.py": ["/config/pj_config.py"], "/consumer/dms_consumer.py": ["/tools/logger.py", "/tools/redis_cli.py", "/tasks/dms_worker.py"], "/consumer/tmp_pd_one.py": ["/tools/redis_cli.py"]} |
43,076 | sxTrp/mirco | refs/heads/master | /consumer/dms_consumer.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 18-12-24 上午10:17
# @Author : ShaoXin
# @Summary :
# @Software: PyCharm
import json
from tools.logger import code_log
from tools.redis_cli import redis_cli
from redis.exceptions import TimeoutError
from tasks.dms_worker import dms_work
while 1:
try:
a = redis_cli.blpop('dms')
code_log.info(f'receive task {a}')
dms_work.delay(str(a))
except TimeoutError as e:
print('block timeout, there is nothing!')
| {"/tasks/dms_worker.py": ["/tools/logger.py"], "/config/celery_config.py": ["/config/zk_config.py"], "/tools/logger.py": ["/config/pj_config.py"], "/config/zk_config.py": ["/config/pj_config.py"], "/consumer/dms_consumer.py": ["/tools/logger.py", "/tools/redis_cli.py", "/tasks/dms_worker.py"], "/consumer/tmp_pd_one.py": ["/tools/redis_cli.py"]} |
43,077 | sxTrp/mirco | refs/heads/master | /config/pj_config.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 18-12-24 上午10:02
# @Author : ShaoXin
# @Summary : 项目配置文件
# @Software: PyCharm
import os
BASEDIR = os.path.dirname(os.path.abspath(os.path.dirname(__file__)))
PROJECT_NAME = BASEDIR.split(os.path.sep)[-1]
ENV = os.environ.get('{project_name}_ENV'.format(project_name=PROJECT_NAME.upper()), 'LOCAL') # PROD/UAT/DEV/LOCAL
ZK_HOSTS = '10.10.1.80:2181,10.10.1.81:2182,10.10.1.82:2182' if ENV == 'LOCAL' else os.environ.get('ZK_HOSTS')
LOG_PATH = os.path.join(BASEDIR, 'logs')
if not os.path.exists(LOG_PATH):
os.mkdir(LOG_PATH)
os.environ.setdefault('log_path', LOG_PATH) # logging.int使用
if __name__ == '__main__':
print(PROJECT_NAME)
| {"/tasks/dms_worker.py": ["/tools/logger.py"], "/config/celery_config.py": ["/config/zk_config.py"], "/tools/logger.py": ["/config/pj_config.py"], "/config/zk_config.py": ["/config/pj_config.py"], "/consumer/dms_consumer.py": ["/tools/logger.py", "/tools/redis_cli.py", "/tasks/dms_worker.py"], "/consumer/tmp_pd_one.py": ["/tools/redis_cli.py"]} |
43,078 | sxTrp/mirco | refs/heads/master | /tools/redis_cli.py | import json
from redis.sentinel import Sentinel
redis_cli_conf = {
"host-port": "10.10.1.82-26379,10.10.1.81-26379,10.10.1.80-26379",
"pw": "bycx321!",
"db": "27",
"expire_time": 43200
}
class RedisException(Exception):
pass
class Cache(object):
def __init__(self, conf):
self.conf = conf
sentinel = self.get_sentinel_connect()
if sentinel:
self.master = sentinel.master_for('mymaster', socket_timeout=5)
self.slave = sentinel.slave_for('mymaster', socket_timeout=2)
self.cache_key_prefix = '{pj_name}_'.format(pj_name='ts')
self.expire_time = conf['expire_time']
def get_sentinel_connect(self):
sentinel_host_info = self.parse_redis_conf(self.conf['host-port'])
try:
connect = Sentinel(sentinel_host_info, socket_timeout=2, password=redis_cli_conf['pw'],
decode_responses=True, db=self.conf['db'])
except RedisException:
connect = None
return connect
@staticmethod
def parse_redis_conf(host_str):
"""
将redis地址拼接成数组
:param host_str:
:return:
"""
result = []
for item in host_str.split(','):
tmp_lst = item.split('-')
host = str(tmp_lst[0].strip())
post = int(tmp_lst[1].strip())
result.append((host, post))
return result
def rpush(self, v, key='dms'):
new_key = self.cache_key_prefix + key
self.master.rpush(new_key, json.dumps(v))
def lpop(self, key='dms'):
new_key = self.cache_key_prefix + key
result = self.master.lpop(new_key)
if result:
result = json.loads(result)
return result
def blpop(self, key='dms'):
new_key = self.cache_key_prefix + key
result = self.master.blpop(new_key)
return result
def expire(self, key, seconds):
"""
设置过期时间
:param key:
:param seconds:
:return:
"""
new_key = self.cache_key_prefix + key
self.master.expire(new_key, seconds)
def flush(self):
keys_lst = self.slave.keys(self.cache_key_prefix + '*')
for key in keys_lst:
self.master.delete(key)
redis_cli = Cache(redis_cli_conf)
if __name__ == '__main__':
# redis_cli.rpush('1111111')
# redis_cli.rpush('222')
# redis_cli.rpush('333')
print(redis_cli.blpop())
| {"/tasks/dms_worker.py": ["/tools/logger.py"], "/config/celery_config.py": ["/config/zk_config.py"], "/tools/logger.py": ["/config/pj_config.py"], "/config/zk_config.py": ["/config/pj_config.py"], "/consumer/dms_consumer.py": ["/tools/logger.py", "/tools/redis_cli.py", "/tasks/dms_worker.py"], "/consumer/tmp_pd_one.py": ["/tools/redis_cli.py"]} |
43,079 | sxTrp/mirco | refs/heads/master | /consumer/tmp_pd_one.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 18-12-21 下午2:55
# @Author : ShaoXin
# @Summary :
# @Software: PyCharm
from tools.redis_cli import redis_cli
for i in range(10):
redis_cli.rpush(i)
| {"/tasks/dms_worker.py": ["/tools/logger.py"], "/config/celery_config.py": ["/config/zk_config.py"], "/tools/logger.py": ["/config/pj_config.py"], "/config/zk_config.py": ["/config/pj_config.py"], "/consumer/dms_consumer.py": ["/tools/logger.py", "/tools/redis_cli.py", "/tasks/dms_worker.py"], "/consumer/tmp_pd_one.py": ["/tools/redis_cli.py"]} |
43,080 | sxTrp/mirco | refs/heads/master | /tools/common.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 18-12-27 下午1:20
# @Author : ShaoXin
# @Summary :
# @Software: PyCharm
import threading
class KThread(threading.Thread):
def __init__(self, *args, **kwargs):
threading.Thread.__init__(self, *args, **kwargs)
self.killed = False
def start(self):
"""Start the thread."""
self.__run_backup = self.run
self.run = self.__run # Force the Thread to install our trace.
threading.Thread.start(self)
def __run(self):
"""Hacked run function, which installs the
trace."""
sys.settrace(self.globaltrace)
self.__run_backup()
self.run = self.__run_backup
def globaltrace(self, frame, why, arg):
if why == 'call':
return self.localtrace
else:
return None
def localtrace(self, frame, why, arg):
if self.killed:
if why == 'line':
raise SystemExit()
return self.localtrace
def kill(self):
self.killed = True
def time_limit(interval, callback_return):
"""
函数超时换回
:param interval:超时时间
:param callback_return:超时返回结果
:return:
"""
def to_do(func):
def _new_func(old_func, result, old_func_args, old_func_kwargs):
result.append(old_func(*old_func_args, **old_func_kwargs))
def deco(*args, **kwargs):
result = []
new_kwargs = { # create new args for _new_func, because we want to get the func return val to result list
'old_func': func,
'result': result,
'old_func_args': args,
'old_func_kwargs': kwargs
}
thd = KThread(target=_new_func, args=(), kwargs=new_kwargs)
thd.start()
thd.join(interval)
alive = thd.isAlive()
thd.kill() # kill the child thread
if alive:
print('func %s run time out of %s' % (func.func_name, interval))
return callback_return
else:
return result[0]
return deco
return to_do
if __name__ == '__main__':
pass
| {"/tasks/dms_worker.py": ["/tools/logger.py"], "/config/celery_config.py": ["/config/zk_config.py"], "/tools/logger.py": ["/config/pj_config.py"], "/config/zk_config.py": ["/config/pj_config.py"], "/consumer/dms_consumer.py": ["/tools/logger.py", "/tools/redis_cli.py", "/tasks/dms_worker.py"], "/consumer/tmp_pd_one.py": ["/tools/redis_cli.py"]} |
43,173 | dianavintila/ACID | refs/heads/master | /acid_detectors/utils.py | import fnmatch
import ntpath
import sys
import os
sys.path.append("androguard-acid/")
sys.path.append("../androguard-acid/")
import androguard.core.bytecodes.dvm as dvm
__author__ = "jorgeblasco and Liam O'Reilly"
def should_analyze(class_name,include_support=None):
if include_support:
return True
elif 'Landroid/support' in class_name:
return None
elif 'Ljavassist' in class_name:
return None
elif 'Lcom/google/android' in class_name:
return None
else:
return True
def track_method_call_action(method, index, intent_variable):
action = ""
while index > 0:
ins = method.get_instruction(index)
#print "1---"+ins.get_name()+" "+ins.get_output()
if (intent_variable in ins.get_output() and ins.get_op_value() in [12] ):#12 is move-result-object
ins2 = method.get_instruction(index-1)
#print "2---"+ins2.get_name()+" "+ins.get_output()
if len(ins2.get_output().split(","))==2:
action = ins2.get_output().split(",")[1] + action
elif len(ins2.get_output().split(","))==3 and intent_variable == ins2.get_output().split(",")[0]:
action = ins2.get_output().split(",")[2] + action
elif intent_variable in ins.get_output() and ins.get_name()=="new-instance":
index = 0
action = ins.get_output().split(",")[1] + action
index -= 1
return action
def get_path_of_method(class_name,method_name, path_list,d):
for p in path_list:
src_class_name, src_method_name, src_descriptor = p.get_src(d.get_class_manager())
if src_method_name == method_name and src_class_name == class_name:
return p
return None
def is_path_of_method_in_package(class_name,method_name, path_list,d):
for p in path_list:
src_class_name, src_method_name, src_descriptor = p.get_src(d.get_class_manager())
package = ntpath.dirname(src_class_name)
if (src_method_name == method_name and src_class_name == class_name) or package in class_name:
return p
return None
def get_instruction_offset(instruction,method):
for index,i in enumerate(method.get_instructions()):
if i.get_raw() == instruction.get_raw():
return index
return -1
def track_string_value(method,index,variable):
"""
Tracks back the value of a string variable that has been declared in code
If the value comes from a literal string, it returns it.
If the valua cannot be traced back to a literal string, it returns the chain
of method calls that resulted in that string until initialization of the object
:param method: is the method where we are searching
:param index: is the next instruction after the declaration of the IntentFilter has been found
:param variable: is the register name where the IntentFilter is placed
:return:
"""
action = "NotTracedBackPossibleParameter"
while index >= 0:
ins = method.get_instruction(index)
if variable == ins.get_output().split(",")[0].strip() and ins.get_op_value() in [0x1A,0x1B]:#0x1A is const-string or const-string/jumbo
action = ins.get_output().split(",")[1].strip()
return action[1:-1]
elif variable == ins.get_output().strip() and ins.get_op_value() in [12]:#12 is move-result-object
ins2 = method.get_instruction(index-1)
if len(ins2.get_output().split(","))==2:
action = ins2.get_output().split(",")[1] + action
elif len(ins2.get_output().split(","))==3 and variable == ins2.get_output().split(",")[0]:
action = ins2.get_output().split(",")[2] + action
elif variable in ins.get_output() and ins.get_name()=="new-instance":
# The register might being reused in another variable after this instruction
# Stop here
index = -1
action = ins.get_output().split(",")[1] + action
elif variable == ins.get_output().split(",")[0].strip() and ins.get_op_value() in [0x07, 0x08]:
# Move operation, we just need to track the new variable now.
variable = ins.get_output().split(",")[1].strip()
elif variable == ins.get_output().split(",")[0].strip() and ins.get_op_value() in [0x54]:#taking value from a field call.
action = ins.get_output().split(",")[2].strip()
index = -1
elif variable == ins.get_output().split(",")[0].strip() and ins.get_op_value() in [0x62]:#sget-object
action = ins.get_output().split(",")[1].strip()#Get the variable name
index = -1
index -= 1
return action
def track_int_value(method,index,variable):
"""
Tracks back the value of an int variable that has been declared in code
If the value cannot be traced back to an integer, it returns the chain
of method calls that resulted in that string until initialization of the object
:param method: is the method where we are searching
:param index: is the next instruction index where to start looking backwards
:param variable: is the register name where the int value is placed
:return:
"""
int_value = -1
while index >= 0:
ins = method.get_instruction(index)
if variable == ins.get_output().split(",")[0].strip() and ins.get_op_value() in [0x12,0x13,0x14,0x15,0x16,0x17,0x18,0x19]:#const instructions
if isinstance(ins,dvm.Instruction11n):
return int(ins.B)
elif isinstance(ins,dvm.Instruction21s):
return int(ins.BBBB)
elif isinstance(ins,dvm.Instruction31i):
return int(ins.BBBBBBBB)
else:
print "Not controlled"
return 0
elif variable == ins.get_output().split(",")[0].strip() and ins.get_op_value() in [0x52, 0x53] and ins.get_output().split(" ") == "I":#taking value from a field
int_value = ins.get_output().split(",")[2].strip()
instance_name = ins.get_output().split(",")[2].strip()
int_value = look_for_sput_of_int_instance(method,instance_name)
return int(int_value)
index = -1
index -= 1
return int_value
def look_for_sput_of_int_instance(method, instance_name):
for m in method.CM.vm.get_methods():
for index,i in enumerate(m.get_instructions()):
if i.get_op_value() in [0x67,68] and instance_name in i.get_output():
string_var = i.get_output().split(",")[0].strip()
return track_int_value(m,index,string_var)
return instance_name
def look_for_put_of_string_instance(method, instance_name):
for m in method.CM.vm.get_methods():
for index,i in enumerate(m.get_instructions()):
if i.get_op_value() in [0x5B] and instance_name in i.get_output():
string_var = i.get_output().split(",")[0].strip()
return track_string_value(m,index,string_var)
return instance_name
def get_all_files_in_dir(directory, extension):
matches = []
for root, dirnames, filenames in os.walk(directory):
for filename in fnmatch.filter(filenames, '*' + extension):
matches.append(os.path.join(root, filename))
return matches
# Get a list of all directories within a specified directory with a given prefix.
def get_all_directrories_in_dir(directory, prefix):
directories = []
for entry in os.listdir(directory) :
fullEntry = os.path.join(directory, entry)
if os.path.isdir(fullEntry) and entry.startswith(prefix):
directories.append(fullEntry)
return directories
def escape_quotes(string=""):
return string.replace("\'",'\\\'')
def is_contained_in_strings_of_list(string,list):
for element in list:
if element in string:
return True
return None
def remove_duplicate_lines(infilename,outfilename,remove_infile=True):
lines_seen = set() # holds lines already seen
outfile = open(outfilename, "a")
for line in open(infilename, "r"):
if line not in lines_seen: # not a duplicate
outfile.write(line)
lines_seen.add(line)
outfile.close()
if remove_infile:
os.remove(infilename)
return True
def stats_file(infilename,statsfilename):
channels = {}
for line in open(infilename, "r"):
channel = line.split(",")[1][1:-4]
if channels.has_key(channel):
channels[channel]+=1
else:
channels[channel]=1
with open(statsfilename,'w') as out:
for key in channels.keys():
out.write("{0},{1}\n".format(key,channels[key]))
return statsfilename
def swipl_path():
# if os.name == 'posix':
# return 'swipl'
# else:
return 'swipl'
| {"/generate_facts.py": ["/acid_detectors/implicit_intents.py", "/acid_detectors/shared_preferences.py", "/acid_detectors/utils.py"], "/generate_prolog.py": ["/acid_detectors/utils.py"], "/detect_collusion.py": ["/acid_detectors/collusion.py"]} |
43,174 | dianavintila/ACID | refs/heads/master | /acid_detectors/shared_preferences.py | from logging import Logger
import logging
from acid_detectors.utils import track_string_value, get_instruction_offset, get_path_of_method, should_analyze, track_int_value
class SharedPreferencesAnalysis(object):
def __init__(self,package,preference_file, operation):
self.package = package
self.preference_file = preference_file
self.operation = operation
def get_shared_preferences_writes(apk,d,dx,include_support=None):
shared_preferences = []
sharedprefs_instruction_paths = dx.tainted_packages.search_methods("", "getSharedPreferences", "\(Ljava/lang/String; I\)Landroid/content/SharedPreferences;")
context_instruction_paths = dx.tainted_packages.search_methods(".", "createPackageContext", ".")
for path in sharedprefs_instruction_paths:
src_class_name, src_method_name, src_descriptor = path.get_src(d.get_class_manager())
if should_analyze(src_class_name,include_support):
method = d.get_method_by_idx(path.src_idx)
i = method.get_instruction(0,path.idx)
index = get_instruction_offset(i,method)
if is_edit_present_later(method,index):
new_var = ""
if i.get_op_value() == 0x6E:#invoke-virtual { parameters }, methodtocall
new_var = i.get_output().split(",")[1].strip()
file_mode_var = i.get_output().split(",")[2].strip()
elif i.get_op_value() == 0x74:#invoke-virtual/range {vx..vy},methodtocall
new_var = i.get_output().split(",")[0].split(".")[-1].strip()[1:]
num = int(new_var)-1
new_var = "v"+`num`
file_mode_var = "v"+new_var
file_mode = track_int_value(method,index-1,file_mode_var)
if file_mode != 0:#if word readable or writable
pref_file = track_string_value(method,index-1,new_var)
context_path = get_path_of_method(src_class_name,src_method_name, context_instruction_paths,d)
if context_path:
context_method = d.get_method_by_idx(context_path.src_idx)
c_i = context_method.get_instruction(0,context_path.idx)
c_index = get_instruction_offset(c_i,context_method)
c_name_var = c_i.get_output().split(",")[1].strip()
package = track_string_value(context_method, c_index-1, c_name_var)
else:
package = apk.get_package()
sharedprefs = SharedPreferencesAnalysis(package, pref_file,"write")
shared_preferences.append(sharedprefs)
return shared_preferences
def get_shared_preferences_reads(apk,d,dx,include_support=None):
shared_preferences = []
sharedprefs_instruction_paths = dx.tainted_packages.search_methods(".", "getSharedPreferences", "\(Ljava/lang/String; I\)Landroid/content/SharedPreferences;")
context_instruction_paths = dx.tainted_packages.search_methods(".", "createPackageContext", ".")
for path in sharedprefs_instruction_paths:
src_class_name, src_method_name, src_descriptor = path.get_src(d.get_class_manager())
if should_analyze(src_class_name,include_support):
method = d.get_method_by_idx(path.src_idx)
i = method.get_instruction(0,path.idx)
index = get_instruction_offset(i,method)
new_var = ""
if i.get_op_value() in [0x6E,0x6F,0x72]:#invoke-virtual { parameters }, methodtocall
new_var = i.get_output().split(",")[1].strip()
file_mode_var = i.get_output().split(",")[2].strip()
elif i.get_op_value() == 0x74:#invoke-virtual/range {vx..vy},methodtocall
new_var = i.get_output().split(",")[0].split(".")[-1].strip()[1:]
num = int(new_var)-1
new_var = "v"+`num`
file_mode_var = "v"+new_var
else:
print "Not Controlled"
# we look the position of the method in
file_mode = track_int_value(method,index-1,file_mode_var)
if file_mode != 0:
pref_file = track_string_value(method, index-1, new_var)
context_path = get_path_of_method(src_class_name,src_method_name, context_instruction_paths,d)
if context_path:
context_method = d.get_method_by_idx(context_path.src_idx)
c_i = context_method.get_instruction(0,context_path.idx)
c_index = get_instruction_offset(c_i,context_method)
c_name_var = c_i.get_output().split(",")[1].strip()
package = track_string_value(context_method, c_index-1, c_name_var)
else:
package = apk.get_package()
sharedprefs = SharedPreferencesAnalysis(package, pref_file,"read")
shared_preferences.append(sharedprefs)
return shared_preferences
def is_edit_present_later(method,index):
present = None
try:
while index < method.get_length():
ins = method.get_instruction(index)
if("android/content/SharedPreferences;->edit()" in ins.get_output()):
return True
index = index + 1
except IndexError:
#Fail gently. beginning of the array reached
return None
return None
def tainted_is_create_package_context_present(d, dx, method,class_name="."):
z = dx.tainted_packages.search_methods(class_name, "createPackageContext", ".")
if len(z)==0:
return None
else:
for path in z:
m = d.get_method_by_idx(path.src_idx)
if m == method:
return True
def track_get_shared_preferences_direct(method,index,variable):
action = ""
ins = method.get_instruction(index)
if ins.get_op_value() in [0x0C]:
variable = ins.get_output().split(",")[0].strip()
index += 1
try:
while index < method.get_length():
ins = method.get_instruction(index)
if variable in ins.get_output() and "getSharedPreferences" in ins.get_output():
new_var = ins.get_output().split(",")[1].strip()
action = track_string_value(method, index-1, new_var)
return action
elif variable in ins.get_output().split(",")[1].strip() and ins.get_op_value() in [0x07, 0x08]:
# Move operation, we just need to track the new variable now.
variable = ins.get_output().split(",")[0].strip()
index += 1
except IndexError:
return action
return action | {"/generate_facts.py": ["/acid_detectors/implicit_intents.py", "/acid_detectors/shared_preferences.py", "/acid_detectors/utils.py"], "/generate_prolog.py": ["/acid_detectors/utils.py"], "/detect_collusion.py": ["/acid_detectors/collusion.py"]} |
43,175 | dianavintila/ACID | refs/heads/master | /generate_facts.py | #!/usr/bin/env python
from acid_detectors.implicit_intents import get_implicit_intents, get_dynamic_receivers, get_static_receivers
from acid_detectors.shared_preferences import get_shared_preferences_writes, get_shared_preferences_reads
from acid_detectors.utils import escape_quotes, get_all_files_in_dir
import argparse
import logging
import ntpath
import os
import sys
# ensure androguard library is imported from our modified version
sys.path.append("androguard-acid/")
import androguard.misc
__author__ = "jorgeblasco and Liam O'Reilly"
VERSION_NUMBER = "1.1"
def analyse_apk_file(apk_filename):
logging.info("Analyzing file %s", apk_filename)
try:
a, d, dx = androguard.misc.AnalyzeAPK(apk_filename)
except:
logging.warning(apk_filename + " is not a valid APK. Skipping")
return None
try:
# Perform analysis
app_facts_dict = {}
# Package
package_name = a.get_package()
app_facts_dict['package_name'] = package_name
app_base_file_name = ntpath.basename(apk_filename)
app_facts_dict['app_base_file_name'] = app_base_file_name
# Permissions
logging.info("Looking for permissions")
permission_facts = set()
for permission in a.get_permissions():
permission_facts.add(permission)
app_facts_dict['permissions'] = permission_facts
# Intent sends
logging.info("Looking for intent sends")
send_intent_facts = set()
for intent in get_implicit_intents(a, d, dx):
send_intent_facts.add(escape_quotes("i_" + intent.action))
app_facts_dict['send_intents'] = send_intent_facts
# Shared Prefs sends
logging.info("Looking for shared preferences sends")
send_shared_prefs_facts = set()
for shared_pref in get_shared_preferences_writes(a, d, dx):
send_shared_prefs_facts.add("sp_" + shared_pref.package + "_" + shared_pref.preference_file)
app_facts_dict['send_shared_prefs'] = send_shared_prefs_facts
# Receivers
logging.info("Looking for dynamic receivers")
recv_intents_facts = set()
for receiver in get_dynamic_receivers(a, d, dx):
recv_intents_facts.add("i_" + receiver.get_action())
for receiver in get_static_receivers(a):
recv_intents_facts.add("i_" + receiver.get_action())
app_facts_dict['recv_intents'] = recv_intents_facts
# Shared Prefs Recv
logging.info("Looking for shared preferences receives")
recv_shared_prefs_facts = set()
for shared_pref in get_shared_preferences_reads(a, d, dx):
recv_shared_prefs_facts.add("sp_" + shared_pref.package + "_" + shared_pref.preference_file)
app_facts_dict['recv_shared_prefs'] = recv_shared_prefs_facts
return app_facts_dict
except Exception as err:
logging.critical(err)
logging.critical("Error during analysis of " + apk_filename + ". Skpping")
return None
def write_facts_to_files(app_facts_dict, app_output_dir):
logging.info("Writing facts to " + app_output_dir)
escaped_package_name = escape_quotes(app_facts_dict['package_name'])
# write packages
with open(os.path.join(app_output_dir, "packages.pl.partial"), 'w') as f:
f.write("package('%s','%s').\n" % (escaped_package_name, escape_quotes(app_facts_dict['app_base_file_name'])))
# write permissions
with open(os.path.join(app_output_dir, "uses.pl.partial"), 'w') as f:
for permission in app_facts_dict['permissions']:
f.write("uses('%s','%s').\n" % (escaped_package_name, escape_quotes(permission)))
# write sends
with open(os.path.join(app_output_dir, "sends.pl.partial"), 'w') as f:
for intent in app_facts_dict['send_intents']:
f.write("trans('%s','%s').\n" % (escaped_package_name, escape_quotes(intent)))
for shared_pref in app_facts_dict['send_shared_prefs']:
f.write("trans('%s','%s').\n" % (escaped_package_name, escape_quotes(shared_pref)))
# write receivers
with open(os.path.join(app_output_dir, "receives.pl.partial"), 'w') as f:
for intent in app_facts_dict['recv_intents']:
f.write("recv('%s','%s').\n" % (escaped_package_name, escape_quotes(intent)))
for shared_pref in app_facts_dict['recv_shared_prefs']:
f.write("recv('%s','%s').\n" % (escaped_package_name, escape_quotes(shared_pref)))
def generate_facts(apk_file_list, output_dir, output_dir_prefix):
if not os.path.isdir(output_dir):
logging.info("Output directory " + output_dir + " does not exist. Creating it")
os.mkdir(output_dir)
for apk_filename in apk_file_list:
app_output_dir = os.path.join(output_dir, output_dir_prefix + ntpath.basename(apk_filename))
if os.path.exists(app_output_dir):
logging.warning("Output directory " + app_output_dir + " already exists. Skipping analysis of " + apk_filename)
continue
app_facts_dict = analyse_apk_file(apk_filename)
if app_facts_dict is None:
continue
os.mkdir(app_output_dir)
write_facts_to_files(app_facts_dict, app_output_dir)
def main():
parser = argparse.ArgumentParser(description="Collusion facts generator, version %s. Produce the collusion facts for the given android apks. For each specidied android apk file, a directory will be created which stores the extracted collusion facts. These facts will be used by the generate_prolog program to create a prolog program (which the detect_collusion program will use). If any apks have previously generated collusion fact directories, then these apks will be skipped. This allows for incremental adding of collusion fact directories." % VERSION_NUMBER)
parser.add_argument("-v", "--verbose",
action="store_true", dest="verbose", default=False,
help="increase output verbosity")
parser.add_argument("-o", "--output_dir",
action="store", dest="output_dir", default=".",
help="set the output directory in which the collusion facts directories will be created. Directory will be created if it does not exist. Default is '.'")
parser.add_argument("-p", "--prefix",
action="store", dest="output_dir_prefix", default="collusion_facts_",
help="set output directory prefix used in the naming of the collusion facts directories. Default is 'collusion_facts_'. Note, this can be set to the empty string ''")
group = parser.add_mutually_exclusive_group()
group.add_argument('-d', '--directory', dest="apk_dir", metavar='DIR', help = 'a directory containing apks which are to be processed (this recursivly looks in this directory for apk files). All files that are not apk files will be ignored')
group.add_argument('-a', '--apks', dest="apk_files", metavar='APK', nargs='+', help='apk file(s) to be processing')
args = parser.parse_args()
logging_level = logging.WARNING
if args.verbose:
logging_level = logging.INFO
logging.basicConfig(format='%(levelname)s: %(message)s', level=logging_level)
# Calculate the apk files
apk_file_list = []
if (args.apk_files != None):
apk_file_list = args.apk_files
elif (args.apk_dir != None):
apk_file_list = get_all_files_in_dir(args.apk_dir, ".apk")
logging.info("Version " + VERSION_NUMBER)
logging.info("Apk files to process: \n\t%s" % str.join("\n\t", apk_file_list))
if len(apk_file_list) <= 0:
logging.warning("No apk files specified")
exit(-1);
generate_facts(apk_file_list, args.output_dir, args.output_dir_prefix)
if __name__ == "__main__":
main() | {"/generate_facts.py": ["/acid_detectors/implicit_intents.py", "/acid_detectors/shared_preferences.py", "/acid_detectors/utils.py"], "/generate_prolog.py": ["/acid_detectors/utils.py"], "/detect_collusion.py": ["/acid_detectors/collusion.py"]} |
43,176 | dianavintila/ACID | refs/heads/master | /generate_prolog.py | #!/usr/bin/env python
from acid_detectors.utils import get_all_directrories_in_dir
import argparse
import logging
import os
__author__ = "jorgeblasco and Liam O'Reilly"
VERSION_NUMBER = "1.1"
def append_file_to_file(opened_output_file, input_filename):
with open(input_filename, 'r') as input_file:
for line in input_file:
opened_output_file.write(line)
def produce_prolog_program(collusion_fact_directories, output_file_name, prolog_rules_filename, external_storage_enabled):
with open(output_file_name, 'w') as output_file:
output_file.write("% DO NOT EDIT THIS FILE\n");
output_file.write("% =====================\n");
output_file.write("% This file was automatically generated by the generate_facts program.\n");
output_file.write("\n");
# write facts: packages
logging.info("Writing packages")
for directory in collusion_fact_directories:
input_filename = os.path.join(directory, "packages.pl.partial")
append_file_to_file(output_file, input_filename)
# write fact: permissions
logging.info("Writing uses")
for directory in collusion_fact_directories:
input_filename = os.path.join(directory, "uses.pl.partial")
append_file_to_file(output_file, input_filename)
# write facts: sends
logging.info("Writing sends")
for directory in collusion_fact_directories:
input_filename = os.path.join(directory, "sends.pl.partial")
append_file_to_file(output_file, input_filename)
# write facts: sends - external storage
if external_storage_enabled:
logging.info("Writing sends - external storage")
output_file.write("trans(A,'external_storage'):- uses(A,'android.permission.WRITE_EXTERNAL_STORAGE').\n")
# write facts: receivers
logging.info("Writing receivers")
for directory in collusion_fact_directories:
input_filename = os.path.join(directory, "receives.pl.partial")
append_file_to_file(output_file, input_filename)
# write facts: receivers - external storage
if external_storage_enabled:
logging.info("Writing receivers - external storage")
output_file.write("recv(A,'external_storage'):- uses(A,'android.permission.WRITE_EXTERNAL_STORAGE').\n")
output_file.write("recv(A,'external_storage'):- uses(A,'android.permission.READ_EXTERNAL_STORAGE').\n")
# write prolog rules
logging.info("Writing prolog rules")
append_file_to_file(output_file, prolog_rules_filename)
logging.info("Done")
def main():
default_prolog_rules = os.path.join(os.path.dirname(os.path.realpath(__file__)), "default_prolog_collusion_rules.pl")
parser = argparse.ArgumentParser(description="Collusion prolog generator, version %s. Produce the prolog filter program from the previously generated collusion fact directories. Combines the generated collusion fact directories (produced by the generate_facts program) into a prolog program (which the detect_collusion program will use)." % VERSION_NUMBER)
parser.add_argument("-v", "--verbose",
action="store_true", dest="verbose", default=False,
help="increase output verbosity")
parser.add_argument("-o", "--output_file",
action="store", dest="output_file", default="prolog_program.pl",
help="set the output file to which the prolog program will be written to. Any existing file will be overwritten. Default is 'prolog_program.pl'")
parser.add_argument("-d", "--input_dir",
action="store", dest="input_dir", default=".",
help="set the input directory in which the previously generated collusion facts directories are located. All directories within this input directory (which start with the specified prefix) will be considered as being collusion fact directories (generated by the generate_facts program). Default is '.'")
parser.add_argument("-p", "--prefix",
action="store", dest="dir_prefix", default="collusion_facts_",
help="set directory prefix used to discover the previously generated generated collusion fact directtories. All directories with this prefix (located in the input directory) will be considered as being collusion fact directories (generated by the generate_facts program). This should match the prefix that was used when running the generate_facts program. Default is 'collusion_facts_'. Note, this can be set to the empty string ''")
parser.add_argument("-r", "--rules",
action="store", dest="prolog_rules_filename", default=default_prolog_rules,
help="set the prolog rule file that contains the collusion rules that will be used. The default will be the rules that come packaged as default. Only change this if you know what you are doing.")
parser.add_argument("-s", "--storage",
action="store_true", dest="external_storage_enabled", default=False,
help="Adds rules to consider external storage as a potential communication channel")
args = parser.parse_args()
logging_level = logging.WARNING
if args.verbose:
logging_level = logging.INFO
logging.basicConfig(format='%(levelname)s: %(message)s', level=logging_level)
# Discover the collusion fact directories
collusion_fact_directories = get_all_directrories_in_dir(args.input_dir, args.dir_prefix)
logging.info("Version " + VERSION_NUMBER)
logging.info("Collusion fact directories to process: \n\t%s" % str.join("\n\t", collusion_fact_directories))
logging.info("Prolog collusion rules file: " + args.prolog_rules_filename)
logging.info("Add rules external storage rules: " + str(args.external_storage_enabled))
if len(collusion_fact_directories) <= 0:
logging.warning("No collusion fact directories found")
exit(-1);
produce_prolog_program(collusion_fact_directories, args.output_file, args.prolog_rules_filename, args.external_storage_enabled)
if __name__ == "__main__":
main() | {"/generate_facts.py": ["/acid_detectors/implicit_intents.py", "/acid_detectors/shared_preferences.py", "/acid_detectors/utils.py"], "/generate_prolog.py": ["/acid_detectors/utils.py"], "/detect_collusion.py": ["/acid_detectors/collusion.py"]} |
43,177 | dianavintila/ACID | refs/heads/master | /tests/test_sharedpreferences.py | from logging import Logger, DEBUG
import logging
import sys
sys.path.append("../")
from acid_detectors.shared_preferences import get_shared_preferences_reads, get_shared_preferences_writes
sys.path.append("../androguard-acid/")
from androguard.core.analysis.analysis import VMAnalysis
from androguard.core.analysis.ganalysis import GVMAnalysis
from androguard.core.bytecodes import apk
from androguard.core.bytecodes import dvm
from androguard.misc import AnalyzeAPK
__author__ = 'jorgeblasco'
sender_file="apks/Rec_RSS_Reader_SharedPreferences.apk"
logging.basicConfig(level=logging.INFO)
def test_tainted_shared_preferences_reads():
a,d, dx = AnalyzeAPK("../tests/apks/Rec_RSS_Reader_SharedPreferences.apk")
x = get_shared_preferences_reads(apk=a,d=d,dx=dx)
assert len(x) == 1
assert x[0].package == 'com.acid.colluding.filemanager'
assert x[0].preference_file == 'PrefsFile'
assert x[0].operation == 'read'
def test_tainted_shared_preferences_writes():
a,d, dx = AnalyzeAPK("../tests/apks/Send_FileManager_SharedPreferences.apk")
x = get_shared_preferences_writes(apk=a,d=d,dx=dx)
for i in x:
print i.package
print i.preference_file
print i.operation
assert len(x) == 1
assert x[0].package == 'com.acid.colluding.filemanager'
assert x[0].preference_file == 'PrefsFile'
assert x[0].operation == 'write' | {"/generate_facts.py": ["/acid_detectors/implicit_intents.py", "/acid_detectors/shared_preferences.py", "/acid_detectors/utils.py"], "/generate_prolog.py": ["/acid_detectors/utils.py"], "/detect_collusion.py": ["/acid_detectors/collusion.py"]} |
43,178 | dianavintila/ACID | refs/heads/master | /acid_detectors/__init__.py | __author__ = 'jorgeblasco'
| {"/generate_facts.py": ["/acid_detectors/implicit_intents.py", "/acid_detectors/shared_preferences.py", "/acid_detectors/utils.py"], "/generate_prolog.py": ["/acid_detectors/utils.py"], "/detect_collusion.py": ["/acid_detectors/collusion.py"]} |
43,179 | dianavintila/ACID | refs/heads/master | /tests/test_intents.py | from logging import Logger, DEBUG
import logging
import sys
sys.path.append("../")
from acid_detectors.implicit_intents import get_implicit_intents, get_dynamic_receivers, get_static_receivers
sys.path.append("../androguard-acid/")
from androguard.misc import AnalyzeAPK
__author__ = 'jorgeblasco'
sender_file="apks/Send_WeatherApp_StaticIntent.apk"
logging.basicConfig(level=logging.INFO)
def test_intent_writes():
a,d, dx = AnalyzeAPK("../tests/apks/Send_WeatherApp_StaticIntent.apk")
x = get_implicit_intents(apk=a,d=d,dx=dx)
actions = ["readcontacts","stop","gettasks","sms","start"]
for i in actions:
assert i in [bi.action for bi in x]
assert len(x) == len(actions)
def test_intent_writes_init():
a,d, dx = AnalyzeAPK("../tests/apks/DocViewer_Benign.apk")
x = get_implicit_intents(apk=a,d=d,dx=dx)
actions = ["android.intent.action.SEND"]
for i in actions:
assert i in [bi.action for bi in x]
assert len(x) == len(actions)
def test_static_intent_receives():
a,d, dx = AnalyzeAPK("../tests/apks/Rec_TaskManager_StaticIntent.apk")
x = get_static_receivers(apk=a)
actions = ["stop","gettasks","start","android.intent.action.MAIN"]
for i in actions:
assert i in [bi.get_action() for bi in x]
for i in x:
print i.get_action()
assert len(x) == len(actions)
def test_weatherapp_intent_receives():
a,d, dx = AnalyzeAPK("../tests/apks/Send_WeatherApp_StaticIntent.apk")
x = get_static_receivers(apk=a)
x.extend(get_dynamic_receivers(a,d,dx))
actions = ['android.intent.action.MAIN',"gettasks_response","readcontacts_response"]
for i in actions:
assert i in [bi.get_action() for bi in x]
for i in x:
print i.get_action()
assert len(x) == len(actions)
def test_fwd_intent_receives():
a,d, dx = AnalyzeAPK("../tests/apks/FWD_Gaming_Intent.apk")
x = get_static_receivers(apk=a)
x.extend(get_dynamic_receivers(a,d,dx))
actions = ['android.intent.action.MAIN',"action.SEND.WHATEVER"]
for i in actions:
assert i in [bi.get_action() for bi in x]
for i in x:
print i.get_action()
assert len(x) == len(actions)
| {"/generate_facts.py": ["/acid_detectors/implicit_intents.py", "/acid_detectors/shared_preferences.py", "/acid_detectors/utils.py"], "/generate_prolog.py": ["/acid_detectors/utils.py"], "/detect_collusion.py": ["/acid_detectors/collusion.py"]} |
43,180 | dianavintila/ACID | refs/heads/master | /acid_detectors/implicit_intents.py | from acid_detectors.utils import get_instruction_offset, track_method_call_action, should_analyze, track_string_value, \
get_path_of_method, is_path_of_method_in_package
__author__ = 'jorgeblasco'
class IntentAnalysis(object):
def __init__(self, action="NotTraceable"):
if action == "":
action = "NotTraceable"
self.action = action
class ReceiverAnalysis(object):
def __init__(self, filters):
self.filters = filters
def get_action(self):
for f in self.filters:
return f.action
class IntentFilterAnalysis(object):
def __init__(self, action):
self.action = action
#TODO improve variable tainting with XRefFrom and XRefTo
def get_implicit_intents(apk,d,dx,include_support=None):
"""
Returns a list of Broadcast Intents that which action is set inside this method. They might not be declared in this method.
The best moment to detect an intent is when its action is set.
:rtype: Intent
"""
intents = []
instruction_paths = dx.tainted_packages.search_methods("Landroid/content/Intent;", "setAction", ".")
instruction_paths.extend(dx.tainted_packages.search_methods("Landroid/content/Intent;", "<init>", "\(Ljava\/lang\/String"))
for path in instruction_paths:
src_class_name, src_method_name, src_descriptor = path.get_src(d.get_class_manager())
if should_analyze(src_class_name,include_support):
method = d.get_method_by_idx(path.src_idx)
i = method.get_instruction(0,path.idx)
index = method.code.get_bc().off_to_pos(path.idx)
intent = i.get_output().split(",")[1].strip()
back_index = index
while back_index > 0:
back_index -= 1
i2 = method.get_instruction(back_index)
if intent in i2.get_output() and i2.get_op_value() in [0xC] :#12 is move-result-object
action = track_method_call_action(method,back_index,intent)
intent = IntentAnalysis(action.strip())
intents.append(intent)
back_index = -1
if i2.get_op_value() == 0x1A and intent in i2.get_output(): #const-string
action = i2.get_output().split(",")[1].strip()
intent = IntentAnalysis(action[1:-1].strip())
intents.append(intent)
back_index = -1
return intents
def get_not_exported_static_receivers(apk):
receivers = []
manifest = apk.get_AndroidManifest()
receiver_list = manifest.getElementsByTagName('receiver')
for receiver in receiver_list:
if receiver.attributes.has_key("android:exported") and receiver.attributes.getNamedItem("android:exported").value == "false":
action_list = receiver.getElementsByTagName('action')
for action in action_list:
values = action.attributes.values()
for val in values:
if 'name' in val.name:
intentfilter = IntentFilterAnalysis(str(val.value))
filters = [intentfilter]
receiver = ReceiverAnalysis(filters)
receivers.append(receiver)
activity_list = manifest.getElementsByTagName('activity')
for activity in activity_list:
if activity.attributes.has_key("android:exported") and activity.attributes.getNamedItem("android:exported").value == "false":
action_list = activity.getElementsByTagName('action')
for action in action_list:
values = action.attributes.values()
for val in values:
if 'name' in val.name:
intentfilter = IntentFilterAnalysis(str(val.value))
filters = [intentfilter]
receiver = ReceiverAnalysis(filters)
receivers.append(receiver)
return receivers
def get_static_receivers(apk):
receivers = []
manifest = apk.get_AndroidManifest()
receiver_list = manifest.getElementsByTagName('receiver')
for receiver in receiver_list:
if (receiver.attributes.has_key("android:exported") and receiver.attributes.getNamedItem("android:exported").value != "true") or not receiver.attributes.has_key("android:exported"):
action_list = receiver.getElementsByTagName('action')
for action in action_list:
values = action.attributes.values()
for val in values:
if 'name' in val.name:
intentfilter = IntentFilterAnalysis(str(val.value))
filters = [intentfilter]
receiver = ReceiverAnalysis(filters)
receivers.append(receiver)
activity_list = manifest.getElementsByTagName('activity')
for activity in activity_list:
if (activity.attributes.has_key("android:exported") and activity.attributes.getNamedItem("android:exported").value != "true") or not activity.attributes.has_key("android:exported"):
action_list = activity.getElementsByTagName('action')
for action in action_list:
values = action.attributes.values()
for val in values:
if 'name' in val.name:
intentfilter = IntentFilterAnalysis(str(val.value))
filters = [intentfilter]
receiver = ReceiverAnalysis(filters)
receivers.append(receiver)
return receivers
def get_dynamic_receivers(apk,d,dx,include_support=None):
"""
Returns a list of all the Receivers registered inside a method
:rtype: Receiver
"""
receivers = []
instruction_paths = dx.tainted_packages.search_methods(".", "registerReceiver", "\(Landroid\/content\/BroadcastReceiver")
for path in instruction_paths:
src_class_name, src_method_name, src_descriptor = path.get_src(d.get_class_manager())
if should_analyze(src_class_name,include_support):
method = d.get_method_by_idx(path.src_idx)
i = method.get_instruction(0,path.idx)
index = method.code.get_bc().off_to_pos(path.idx)
if i.get_op_value() in [0x6E,0x6F,0x72]:#invoke-virtual { parameters }, methodtocall or invoke-super
var = i.get_output().split(",")[2].strip() #The second argument holds the IntentFilter with the action
elif i.get_op_value() == 0x74:#invoke-virtual/range {vx..vy},methodtocall
var = i.get_output().split(",")[0].split(".")[-1]
else:
print "Error"
action = track_intent_filter_direct(method,index-1,var)
intentfilter = IntentFilterAnalysis(action)
filters = []
filters.append(intentfilter)
receiver = ReceiverAnalysis(filters)
receivers.append(receiver)
return receivers
def track_intent_filter_direct(method,index,variable):
"""
Tracks the value of the IntentFilter action
:param method: is the method where we are searching
:param index: is the next instruction after the declaration of the IntentFilter has been found
:param variable: is the register name where the IntentFilter is placed
:return:
"""
action = "notDefinedInMethod"
while index > 0:
ins = method.get_instruction(index)
if variable == ins.get_output().split(",")[0].strip() and "Landroid/content/IntentFilter;-><init>(Ljava/lang/String;" in ins.get_output():
new_var = ins.get_output().split(",")[1].strip()
action = track_string_value(method,index-1,new_var)
return action
elif (len(ins.get_output().split(",")) > 1 and variable == ins.get_output().split(",")[1].strip() and ins.get_op_value() in [0x07, 0x08]):#move-objects
# Move operation, we just need to track the new variable now.
new_var = ins.get_output().split(",")[0].strip()
#print "++++"+new_var
action2 = track_intent_filter_direct(method,index+1,new_var)
if(action2 not in ["notDefinedInMethod", "registerReceiver"]):# it may happen that the same variable is referenced in two register. One leads to nowehere and the other is the correct one.
action = action2
return action
elif (variable == ins.get_output().split(",")[0].strip() and "Landroid/content/IntentFilter;-><init>(Landroid/content/IntentFilter;" in ins.get_output()):
# The intent filter is initialized with other intent filter.
# We update the register name to look for.
#TODO THIS GENERATES FALSE POSITIVES
new_var = ins.get_output().split(",")[1].strip()
action2 = track_intent_filter_direct(method,index+1,new_var)
if(action2 not in ["notDefinedInMethod", "registerReceiver"]):# it may happen that the same variable is referenced in two register. One leads to nowehere and the other is the correct one.
action = action2
return action
elif (variable == ins.get_output().split(",")[0].strip() and "addAction" in ins.get_output()):
# There is an addAction that declares the action
# We need to look for its value
new_var = ins.get_output().split(",")[1].strip()
if "p" in new_var:# the varaible comes from a method parameter
action = "MethodParameter"
return action
else:
action = track_string_value(method,index-1,new_var)
return action
elif (variable == ins.get_output().split(",")[0].strip() and ins.get_op_value() in [0x54]):#taking value from a method call.
action = ins.get_output().split(",")[2].strip()
return action
elif "registerReceiver" in ins.get_output():
action = "registerReceiverFoundWithouBeingAbleToTrackParameters"
return action
index -= 1
return action | {"/generate_facts.py": ["/acid_detectors/implicit_intents.py", "/acid_detectors/shared_preferences.py", "/acid_detectors/utils.py"], "/generate_prolog.py": ["/acid_detectors/utils.py"], "/detect_collusion.py": ["/acid_detectors/collusion.py"]} |
43,181 | dianavintila/ACID | refs/heads/master | /detect_collusion.py | #!/usr/bin/env python
import acid_detectors.collusion as collusion
import argparse
import logging
import os
from sets import Set
__author__ = "jorgeblasco and Liam O'Reilly"
VERSION_NUMBER = "1.1"
COLLUSION_KINDS = ['colluding_info', 'colluding_money1', 'colluding_money2', 'colluding_service', 'colluding_camera', 'colluding_accounts', 'colluding_sms']
def collusion_sets(prolog_program_filename, collusion_kind, filter_dir, communication_length, app_package):
sets = Set()
base_file = prolog_program_filename
if filter_dir is not None and os.path.isdir(filter_dir):
logging.info("Filtering intents")
filtered_file_name = collusion.filter_intents_by_folder(prolog_program_filename, filter_dir)
base_file = filtered_file_name
numbered_channels_file = collusion.replace_channels_strings_file(base_file)
mapping_channels = collusion.read_mapping_file(base_file + collusion.channel_numbering_mapping_suffix)
numbered_packages_file = collusion.replace_packages_strings_file(numbered_channels_file)
mapping_packages = collusion.read_mapping_file(numbered_channels_file + collusion.package_numbering_mapping_suffix)
logging.info("Finding colluding apps")
if communication_length is None:
if app_package is None:
logging.info("Searching for all")
app_sets_list = collusion.find_all_colluding(numbered_packages_file, collusion_kind)
else:
app_value = mapping_packages.index("'" + app_package + "'")
logging.info("Specific app")
app_sets_list = collusion.find_package_colluding(numbered_packages_file, app_value, collusion_kind)
else:
if app_package is None:
logging.info("Specific length ")
app_sets_list = collusion.find_all_colluding_length(numbered_packages_file, collusion_kind, communication_length)
else:
app_value = mapping_packages.index("'" + app_package + "'")
logging.info("Specific length and app")
app_sets_list = collusion.find_package_colluding_length(numbered_packages_file, collusion_kind, app_value, communication_length)
logging.info("Finding communication channels")
for app_set in app_sets_list:
channels = collusion.communication_channels(numbered_packages_file, app_set)
c_set = collusion.CollusionSet(collusion_kind, app_set, channels, mapping_packages, mapping_channels)
sets.add(c_set)
return sets
def main():
default_intent_data_to_filter = os.path.join(os.path.dirname(os.path.realpath(__file__)), "default_intent_data_to_filter")
parser = argparse.ArgumentParser(description="Collusion detection program, version %s. Runs the prolog program to detect collusion. This tool outputs a list of all collusion app sets found in the speficied prolog program (which was previously produced by the generate_prolog program). It includes the apps in the set, and the channels used to communicate." % VERSION_NUMBER)
parser.add_argument("prolog_program_filename",
metavar='prolog_program_filename',
help="the prolog program previously generated by the generate_prolog program")
parser.add_argument("collusion_kind",
metavar='collusion_kind',
help="the kind of collusion that should be detected. Possible values are: %s" % str.join(", ", COLLUSION_KINDS),
choices=COLLUSION_KINDS)
parser.add_argument("-v", "--verbose",
action="store_true", dest="verbose", default=False,
help="increase output verbosity")
parser.add_argument("-l", "--length", type=int,
action="store", dest="communication_length", default=None,
help="only detect collusion based on communication paths of a specified length (i.e., app sets of a given size). This is useful to reduce the search space")
parser.add_argument("-a", "--app_package",
action="store", dest="app_package", default=None,
help="detect collusion only for app sets that start with the app with specified pacakge name")
parser.add_argument("-f", "--filter",
action="store", dest="filter_dir", default=None,
help="use specified folder with intent data that is considered safe. Apps that communciate with these intents will not be flagged as colluding. A default directory of common intent data to use for this is located at " + default_intent_data_to_filter + ". Intent actions should be organized inside different files inside the folder (one intent action per line)")
args = parser.parse_args()
logging_level = logging.WARNING
if args.verbose:
logging_level = logging.INFO
logging.basicConfig(format='%(levelname)s: %(message)s', level=logging_level)
logging.info("Version " + VERSION_NUMBER)
colluding_app_sets = collusion_sets(args.prolog_program_filename, args.collusion_kind, args.filter_dir, args.communication_length, args.app_package)
if len(colluding_app_sets) == 0:
print("No collusion detected")
else:
for colluding_app_set in colluding_app_sets:
colluding_app_set.description()
if __name__ == "__main__":
main() | {"/generate_facts.py": ["/acid_detectors/implicit_intents.py", "/acid_detectors/shared_preferences.py", "/acid_detectors/utils.py"], "/generate_prolog.py": ["/acid_detectors/utils.py"], "/detect_collusion.py": ["/acid_detectors/collusion.py"]} |
43,182 | dianavintila/ACID | refs/heads/master | /acid_detectors/collusion.py | import logging
from sets import Set
from acid_detectors.utils import get_all_files_in_dir, swipl_path
__author__ = 'jorgeblasco'
import re
import os.path
import ast
from subprocess import check_output
#swipl -q -t 'findall(P,colluding_info(A,B,P),Ps),writeln(Ps),true' -s imps_detector.pl
channel_numbering_suffix = ".numbered_channels"
channel_numbering_mapping_suffix = ".mapping_channels"
package_numbering_suffix = ".numbered_packages"
package_numbering_mapping_suffix = ".mapping_packages"
class CollusionSet:
def __init__(self,kind,app_list,channels_lists,mapping_packages=None,mapping_channels=None):
self.kind = kind
self.app_list = app_list
if mapping_packages:
self.app_list = [mapping_packages[int(app)] for app in app_list]
if mapping_channels:
self.channels_lists = []
for channels in channels_lists:
self.channels_lists.append([mapping_channels[int(channel)] for channel in channels])
else:
self.channels_lists = channels_lists
def __str__(self):
if len(self.app_list)==0:
return ""
else:
result = self.kind+"\n"+self.app_list[0]
for channels in self.channels_lists:
for i in range(0,len(self.channels),1):
result = result +"-->" + self.channels[i]+ "-->"+ self.app_list[i+1]
return result
def short_description(self):
print str(self)
def description(self):
print "+++++++++++++++"
print " Colluding Set"
print "+++++++++++++++"
print self.kind
print "--------------"
print self.app_list
print "-- Channels --"
for channels in self.channels_lists:
print channels
colluding_predicates = ['colluding_info', 'colluding_money1','colluding_money2','colluding_service','colluding_camera','colluding_accounts','colluding_sms']
def find_all_comm_setof(rule_file):
#Extract package names
packages = find_packages()
#Execute setof over each package name
comm_list = []
for package in packages:
comm_list.extend(find_all_comm_package(rule_file,package))
return comm_list
def find_packages(rule_file):
packages = Set()
count = 0
with open(rule_file) as infile:
for line in infile:
if line.startswith("recv") or line.startswith("trans") or line.startswith("uses") or line.startswith("package"):
item = line.split(",")[0].split("(")[1]
packages.add(item)
return packages
def find_comm_length_all(rule_file,length=2):
return find_comm_length_package(rule_file,"AppA",length)
def find_comm_length_package(rule_file,package_name="AppA",length=2):
if not os.path.isfile(rule_file) :
return None
logging.info("Finding communications with "+str(package_name))
call = [swipl_path(),'-G4g', '-q', '-g', "( \+ comm_length({0},AppB,{1},Visited,Path) -> Ps = [] ; setof(({0},AppB,Path),Visited^comm_length({0},AppB,{1},Visited,Path),Ps)),writeln(Ps),halt".format(package_name,length), "-t", "'halt(1)'", '-s', rule_file]
result = check_output(call)
return parse_returned_app_list(result)
def find_all_comm_package(rule_file,package_name):
if not os.path.isfile(rule_file) :
return None
logging.info("Finding communications with "+package_name)
call = [swipl_path(),'-G4g', '-q', '-g', "( \+ comm({0},AppB,Visited,Path,Length) -> Ps = [] ; setof(({0},AppB,Path),Visited^Length^comm({0},AppB,Visited,Path,Length),Ps)),writeln(Ps),halt".format(package_name), "-t", "'halt(1)'", '-s', rule_file]
result = check_output(call)
return parse_returned_app_list(result)
def find_all_comm(rule_file):
if not os.path.isfile(rule_file) :
return None
logging.info("Executing SWIPL command")
call = [swipl_path(),'-G4g', '-q', '-g', "( \+ comm({0},AppB,Visited,Path,Length) -> Ps = [] ; setof((AppA,AppB,Path),Visited^Length^comm(AppA,AppB,Visited,Path,Length),Ps)),writeln(Ps),halt","-t","'halt(1)'", '-s', rule_file]
result = check_output(call)
return parse_returned_app_list(result)
def find_all_colluding(rule_file,colluding_predicate):
return find_package_colluding(rule_file,"AppA",colluding_predicate)
def find_package_colluding(rule_file,package,colluding_predicate):
if colluding_predicate not in colluding_predicates:
return None
if not os.path.isfile(rule_file) :
return None
logging.info("Executing SWIPL command")
call = [swipl_path(),'-G4g', '-q', '-g', "( \+ {0}({1},AppB,Path) -> Ps = [] ; setof(({1},AppB,Path),{0}({1},AppB,Path),Ps)),writeln(Ps),halt".format(colluding_predicate,package),"-t","'halt(1)'", '-s', rule_file]
result = check_output(call)
return parse_returned_app_list(result)
def find_all_colluding_length(rule_file,colluding_predicate,length=2):
return find_package_colluding_length(rule_file,colluding_predicate,"AppA",length)
def find_package_colluding_length(rule_file,colluding_predicate,package="AppA",length=2):
if colluding_predicate not in colluding_predicates:
return None
if not os.path.isfile(rule_file) :
return None
colluding_predicate = colluding_predicate+"_length"
logging.info("Executing SWIPL command")
call = [swipl_path(),'-G4g', '-q', '-g', "( \+ {0}({2},AppB,Path,{1}) -> Ps = [] ; setof(({2},AppB,Path),{0}({2},AppB,Path,{1}),Ps)),writeln(Ps),halt".format(colluding_predicate,length,package),"-t","'halt(1)'", '-s', rule_file]
logging.debug("Call is :"+str(call))
result = check_output(call)
logging.info("Ids of apps obtained :"+result)
return parse_returned_app_list(result)
#channel(AppA,AppB,Path,Channel)
# 423,420,[55,426]
def communication_channels(rule_file,app_set):
if len(app_set) < 2:
return []
app_a = app_set[0]
app_b = app_set[-1]
path_string = "[]"
if len(app_set) > 2:
path_string = ",".join([str(i) for i in app_set[1:-1]])
path_string = "[" + path_string+ "]"
prolog_command = 'setof(C,channel({0},{1},{2},C),Cs),writeln(Cs),halt'.format(app_a,app_b,path_string)
logging.debug("Executing :"+prolog_command)
call = [swipl_path(),'-G4g','-q', "-g", prolog_command, "-t","'halt(1)'", "-s", rule_file]
result = check_output(call)
return parse_returned_channel_list(result)
def parse_returned_channel_list(list_string):
result = list_string.replace("|",",")
p = re.compile("\[([\d, \|]*)\]")
channel_list = []
for (channels) in re.findall(p,result):
channel_list.append(ast.literal_eval("["+channels+"]"))
return channel_list
def parse_returned_app_list(list_string):
result = list_string.replace("|",",")
p = re.compile(ur'\(([0-9]*),([0-9]*),\[([a-zA-Z\d\.\[,_]*)\]')
colluding_appset_list = []
for (a,b,path) in re.findall(p, result):
comm_apps_list = []
comm_apps_list.append(int(a))
path_list = ast.literal_eval("["+path+"]")
comm_apps_list.extend(path_list)
comm_apps_list.append(int(b))
colluding_appset_list.append(comm_apps_list)
return colluding_appset_list
def read_mapping_file(mapping_file):
mapping = []
with open(mapping_file,'r') as r:
for line in r:
values = line.split(":")
if len(values) == 2:
mapping.append(values[0])
return mapping
def filter_intents_by_folder(rule_file,intent_filters_folder):
files = get_all_files_in_dir(intent_filters_folder, "*")
lines_to_remove = []
filtered_file = rule_file+".filtered"
for file in files:
with open(file,'r') as r:
lines_to_remove.extend([line[:-1] for line in r.readlines()])
with open(filtered_file,'w') as f, open(rule_file,'r') as rulef:
rule_lines = rulef.readlines()
final_lines = [rule for rule in rule_lines if len([line for line in lines_to_remove if line in rule])==0]
f.writelines(final_lines)
return filtered_file
def filter_intents_by_file(file,intent_filters_file):
lines_to_remove = []
filtered_file = file+".filtered"
with open(intent_filters_file,'r') as r:
lines_to_remove.extend([line[:-1] for line in r.readlines()])
with open(filtered_file,'w') as f, open(file,'r') as rulef:
rule_lines = rulef.readlines()
final_lines = [rule for rule in rule_lines if len([line for line in lines_to_remove if line in rule])==0]
f.writelines(final_lines)
return filtered_file
def replace_channels_strings_file(in_filename):
mapping = {}
count = 0
out_filename = in_filename +channel_numbering_suffix
with open(in_filename) as infile, open(in_filename+channel_numbering_mapping_suffix, 'w') as mapping_file, open(out_filename,"w") as outfile:
for line in infile:
if line.startswith("recv") or line.startswith("trans"):
item = line[line.index(",")+1:-3]
if not mapping.has_key(item):
mapping_file.write(item+":"+str(count)+"\n")
mapping[item] = count
count += 1
line = line.replace(item,str(mapping[item]))
outfile.write(line)
return out_filename
def replace_packages_strings_file(in_filename):
mapping = {}
count = 0
out_filename = in_filename +package_numbering_suffix
with open(in_filename) as infile, open(in_filename+package_numbering_mapping_suffix, 'w') as mapping_file, open(out_filename,"w") as outfile:
for line in infile:
if line.startswith("recv") or line.startswith("trans") or line.startswith("uses") or line.startswith("package"):
item = line.split(",")[0].split("(")[1]
if not mapping.has_key(item):
mapping_file.write(item+":"+str(count)+"\n")
mapping[item] = count
count += 1
line = line.replace(item,str(mapping[item]))
outfile.write(line)
return out_filename | {"/generate_facts.py": ["/acid_detectors/implicit_intents.py", "/acid_detectors/shared_preferences.py", "/acid_detectors/utils.py"], "/generate_prolog.py": ["/acid_detectors/utils.py"], "/detect_collusion.py": ["/acid_detectors/collusion.py"]} |
43,189 | fsociety6/SmartAurangabadHack | refs/heads/master | /CCWebsite/health/migrations/0006_crowdsource_location.py | # Generated by Django 2.2.5 on 2020-01-22 04:24
from django.db import migrations, models
import django.utils.timezone
class Migration(migrations.Migration):
dependencies = [
('health', '0005_auto_20200121_1942'),
]
operations = [
migrations.AddField(
model_name='crowdsource',
name='location',
field=models.CharField(default=django.utils.timezone.now, max_length=6),
preserve_default=False,
),
]
| {"/CCWebsite/account/views.py": ["/CCWebsite/account/forms.py"], "/CCWebsite/account/forms.py": ["/CCWebsite/account/models.py"], "/CCWebsite/account/admin.py": ["/CCWebsite/account/models.py"], "/CCWebsite/health/admin.py": ["/CCWebsite/health/models.py"]} |
43,190 | fsociety6/SmartAurangabadHack | refs/heads/master | /CCWebsite/health/urls.py | from django.contrib import admin
from django.urls import path, include
from . import views
urlpatterns = [
path('dashboard/',views.dashboard),
path('symptoms/',views.disease),
path('notification/', views.notifications),
path('dashboard/edit',views.edit_profile,name="edit"),
path('map/',views.maps)
]
| {"/CCWebsite/account/views.py": ["/CCWebsite/account/forms.py"], "/CCWebsite/account/forms.py": ["/CCWebsite/account/models.py"], "/CCWebsite/account/admin.py": ["/CCWebsite/account/models.py"], "/CCWebsite/health/admin.py": ["/CCWebsite/health/models.py"]} |
43,191 | fsociety6/SmartAurangabadHack | refs/heads/master | /CCWebsite/health/migrations/0004_auto_20200121_1925.py | # Generated by Django 2.2.5 on 2020-01-21 13:55
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('health', '0003_auto_20200121_1920'),
]
operations = [
migrations.AlterField(
model_name='crowdsource',
name='Gender',
field=models.CharField(choices=[('MALE', 'Male'), ('FEMALE', 'Female')], max_length=10),
),
]
| {"/CCWebsite/account/views.py": ["/CCWebsite/account/forms.py"], "/CCWebsite/account/forms.py": ["/CCWebsite/account/models.py"], "/CCWebsite/account/admin.py": ["/CCWebsite/account/models.py"], "/CCWebsite/health/admin.py": ["/CCWebsite/health/models.py"]} |
43,192 | fsociety6/SmartAurangabadHack | refs/heads/master | /CCWebsite/chat/consumers.py | import asyncio
import json
from django.contrib.auth import get_user_model
from channels.consumer import AsyncConsumer
from channels.db import database_sync_to_async
class ChatConsumer(AsyncConsumer):
def websocket_connect(self, event):
print("connected: ", event)
def websocket_receive(self, event):
print("Received : ", event)
def websocket_disconnect(self, event):
print("Disconnected: ", event)
| {"/CCWebsite/account/views.py": ["/CCWebsite/account/forms.py"], "/CCWebsite/account/forms.py": ["/CCWebsite/account/models.py"], "/CCWebsite/account/admin.py": ["/CCWebsite/account/models.py"], "/CCWebsite/health/admin.py": ["/CCWebsite/health/models.py"]} |
43,193 | fsociety6/SmartAurangabadHack | refs/heads/master | /CCWebsite/account/views.py | from django.contrib.auth import authenticate, login
from django.contrib.auth.forms import AuthenticationForm
from django.shortcuts import render, redirect
from .forms import LoginForm, UserExtendedForm, UserForm
from django.http import HttpResponse
# Create your views here.
def register(request):
if request.method == "POST":
userform = UserForm(data=request.POST)
userextendedform = UserExtendedForm(data=request.POST)
if userform.is_valid() and userextendedform.is_valid():
user = userform.save()
userextended = userextendedform.save(commit=False)
userextended.user_object = user
userextended.save()
return HttpResponse('signed Up')
else:
userform = UserForm()
userextendedform = UserExtendedForm()
return render(request, 'account/register.html',
{"userform": userform, 'userextendedform': userextendedform})
def user_login_view(request):
if request.method == "POST":
loginform = AuthenticationForm(request,data=request.POST)
if loginform.is_valid():
cd = loginform.cleaned_data
user = authenticate(username=cd['username'], password=cd['password'])
if user is not None:
login(request, user)
return redirect('/dashboard')
else:
return HttpResponse("UnSuccessFully Login !!!")
else:
loginform = AuthenticationForm
return render(request, "account/login.html", {"loginform": loginform})
| {"/CCWebsite/account/views.py": ["/CCWebsite/account/forms.py"], "/CCWebsite/account/forms.py": ["/CCWebsite/account/models.py"], "/CCWebsite/account/admin.py": ["/CCWebsite/account/models.py"], "/CCWebsite/health/admin.py": ["/CCWebsite/health/models.py"]} |
43,194 | fsociety6/SmartAurangabadHack | refs/heads/master | /CCWebsite/health/views.py | from django.shortcuts import render, redirect
from django.http import HttpResponse
import requests
from django.contrib.auth.models import User
from account.models import ExtendedUserModel
from account.forms import EditForm
# Create your views here.
from account.models import ExtendedUserModel
def home(request):
return HttpResponse('chat home')
from health.models import Disease, Crowdsource
# Create your views here.
def home(request):
l = [{"ID": 188, "Name": "Abdominal guarding"}, {"ID": 10, "Name": "Abdominal pain"},
{"ID": 223, "Name": "Abdominal pain associated with menstruation"}, {"ID": 984, "Name": "Absence of a pulse"},
{"ID": 974, "Name": "Aggressiveness"}, {"ID": 981, "Name": "Agitation"},
{"ID": 996, "Name": "Ankle deformity"}, {"ID": 147, "Name": "Ankle swelling"}, {"ID": 238, "Name": "Anxiety"},
{"ID": 1009, "Name": "Arm pain"}, {"ID": 971, "Name": "Arm swelling"}, {"ID": 998, "Name": "Back deformity"},
{"ID": 104, "Name": "Back pain"}, {"ID": 180, "Name": "Black stools"},
{"ID": 57, "Name": "Blackening of vision"}, {"ID": 24, "Name": "Blackhead"},
{"ID": 284, "Name": "Bleeding from vagina"}, {"ID": 176, "Name": "Bleeding in the conjunctiva of the eye"},
{"ID": 48, "Name": "Bloated feeling in the stomach"}, {"ID": 190, "Name": "Blood in stool"},
{"ID": 233, "Name": "Bloody cough"}, {"ID": 991, "Name": "Blue colored skin"},
{"ID": 240, "Name": "Blue spot on skin"}, {"ID": 77, "Name": "Blurred vision"},
{"ID": 239, "Name": "Bold area among hair on the head"}, {"ID": 156, "Name": "Bone fracture"},
{"ID": 250, "Name": "Breathing-related pains"}, {"ID": 979, "Name": "Brittleness of nails"},
{"ID": 192, "Name": "Bulging abdominal wall"}, {"ID": 75, "Name": "Burning eyes"},
{"ID": 46, "Name": "Burning in the throat"}, {"ID": 288, "Name": "Burning nose"},
{"ID": 107, "Name": "Burning sensation when urinating"}, {"ID": 91, "Name": "Changes in the nails"},
{"ID": 170, "Name": "Cheek swelling"}, {"ID": 17, "Name": "Chest pain"}, {"ID": 31, "Name": "Chest tightness"},
{"ID": 175, "Name": "Chills"}, {"ID": 218, "Name": "Coarsening of the skin structure"},
{"ID": 89, "Name": "Cold feet"}, {"ID": 978, "Name": "Cold hands"}, {"ID": 139, "Name": "Cold sweats"},
{"ID": 15, "Name": "Cough"}, {"ID": 228, "Name": "Cough with sputum"}, {"ID": 94, "Name": "Cramps"},
{"ID": 49, "Name": "Cravings"}, {"ID": 134, "Name": "Crusting"}, {"ID": 260, "Name": "Curvature of the spine"},
{"ID": 108, "Name": "Dark urine"}, {"ID": 163, "Name": "Decreased urine stream"},
{"ID": 165, "Name": "Delayed start to urination"}, {"ID": 50, "Name": "Diarrhea"},
{"ID": 79, "Name": "Difficult defecation"}, {"ID": 126, "Name": "Difficulty in finding words"},
{"ID": 98, "Name": "Difficulty in speaking"}, {"ID": 93, "Name": "Difficulty in swallowing"},
{"ID": 53, "Name": "Difficulty to concentrate"}, {"ID": 1007, "Name": "Difficulty to learn"},
{"ID": 1005, "Name": "Difficulty with gait"}, {"ID": 216, "Name": "Discoloration of nails"},
{"ID": 128, "Name": "Disorientation regarding time or place"}, {"ID": 989, "Name": "Distended abdomen"},
{"ID": 207, "Name": "Dizziness"}, {"ID": 71, "Name": "Double vision"},
{"ID": 270, "Name": "Double vision, acute-onset"}, {"ID": 162, "Name": "Dribbling after urination"},
{"ID": 244, "Name": "Drooping eyelid"}, {"ID": 43, "Name": "Drowsiness"}, {"ID": 273, "Name": "Dry eyes"},
{"ID": 272, "Name": "Dry mouth"}, {"ID": 151, "Name": "Dry skin"}, {"ID": 87, "Name": "Earache"},
{"ID": 92, "Name": "Early satiety"}, {"ID": 1011, "Name": "Elbow pain"}, {"ID": 1006, "Name": "Enlarged calf"},
{"ID": 242, "Name": "Eye blinking"}, {"ID": 287, "Name": "Eye pain"}, {"ID": 33, "Name": "Eye redness"},
{"ID": 208, "Name": "Eyelid swelling"}, {"ID": 209, "Name": "Eyelids sticking together"},
{"ID": 219, "Name": "Face pain"}, {"ID": 246, "Name": "Facial paralysis"},
{"ID": 970, "Name": "Facial swelling"}, {"ID": 153, "Name": "Fast, deepened breathing"},
{"ID": 83, "Name": "Fatty defecation"}, {"ID": 982, "Name": "Feeling faint"},
{"ID": 1014, "Name": "Feeling ill"}, {"ID": 76, "Name": "Feeling of foreign body in the eye"},
{"ID": 86, "Name": "Feeling of pressure in the ear"}, {"ID": 164, "Name": "Feeling of residual urine"},
{"ID": 145, "Name": "Feeling of tension in the legs"}, {"ID": 11, "Name": "Fever"},
{"ID": 995, "Name": "Finger deformity"}, {"ID": 1013, "Name": "Finger pain"},
{"ID": 1012, "Name": "Finger swelling"}, {"ID": 214, "Name": "Flaking skin"},
{"ID": 245, "Name": "Flaking skin on the head"}, {"ID": 154, "Name": "Flatulence"},
{"ID": 255, "Name": "Foot pain"}, {"ID": 1002, "Name": "Foot swelling"}, {"ID": 125, "Name": "Forgetfulness"},
{"ID": 62, "Name": "Formation of blisters on a skin area"}, {"ID": 84, "Name": "Foul smelling defecation"},
{"ID": 59, "Name": "Frequent urination"}, {"ID": 110, "Name": "Genital warts"},
{"ID": 152, "Name": "Hair loss"}, {"ID": 976, "Name": "Hallucination"}, {"ID": 72, "Name": "Halo"},
{"ID": 186, "Name": "Hand pain"}, {"ID": 148, "Name": "Hand swelling"}, {"ID": 80, "Name": "Hard defecation"},
{"ID": 184, "Name": "Hardening of the skin"}, {"ID": 9, "Name": "Headache"},
{"ID": 206, "Name": "Hearing loss"}, {"ID": 985, "Name": "Heart murmur"}, {"ID": 45, "Name": "Heartburn"},
{"ID": 122, "Name": "Hiccups"}, {"ID": 993, "Name": "Hip deformity"}, {"ID": 196, "Name": "Hip pain"},
{"ID": 121, "Name": "Hoarseness"}, {"ID": 149, "Name": "Hot flushes"}, {"ID": 197, "Name": "Immobilization"},
{"ID": 120, "Name": "Impaired balance"}, {"ID": 90, "Name": "Impaired hearing"},
{"ID": 70, "Name": "Impaired light-dark adaptation"}, {"ID": 113, "Name": "Impairment of male potency"},
{"ID": 81, "Name": "Incomplete defecation"}, {"ID": 131, "Name": "Increased appetite"},
{"ID": 262, "Name": "Increased drive"}, {"ID": 204, "Name": "Increased salivation"},
{"ID": 40, "Name": "Increased thirst"}, {"ID": 220, "Name": "Increased touch sensitivity"},
{"ID": 39, "Name": "Increased urine quantity"}, {"ID": 257, "Name": "Involuntary movements"},
{"ID": 986, "Name": "Irregular heartbeat"}, {"ID": 65, "Name": "Irregular mole"},
{"ID": 73, "Name": "Itching eyes"}, {"ID": 88, "Name": "Itching in the ear"},
{"ID": 973, "Name": "Itching in the mouth or throat"}, {"ID": 96, "Name": "Itching in the nose"},
{"ID": 21, "Name": "Itching of skin"}, {"ID": 999, "Name": "Itching of the anus"},
{"ID": 247, "Name": "Itching on head"}, {"ID": 268, "Name": "Itching or burning in the genital area"},
{"ID": 194, "Name": "Joint effusion"}, {"ID": 198, "Name": "Joint instability"},
{"ID": 27, "Name": "Joint pain"}, {"ID": 230, "Name": "Joint redness"}, {"ID": 193, "Name": "Joint swelling"},
{"ID": 47, "Name": "Joylessness"}, {"ID": 994, "Name": "Knee deformity"}, {"ID": 256, "Name": "Knee pain"},
{"ID": 146, "Name": "Leg cramps"}, {"ID": 1010, "Name": "Leg pain"}, {"ID": 231, "Name": "Leg swelling"},
{"ID": 143, "Name": "Leg ulcer"}, {"ID": 82, "Name": "Less than 3 defecations per week"},
{"ID": 992, "Name": "Limited mobility of the ankle"}, {"ID": 167, "Name": "Limited mobility of the back"},
{"ID": 178, "Name": "Limited mobility of the fingers"}, {"ID": 1000, "Name": "Limited mobility of the hip"},
{"ID": 195, "Name": "Limited mobility of the leg"}, {"ID": 35, "Name": "Lip swelling"},
{"ID": 205, "Name": "Lockjaw"}, {"ID": 210, "Name": "Loss of eye lashes"},
{"ID": 174, "Name": "Lower abdominal pain"}, {"ID": 263, "Name": "Lower-back pain"},
{"ID": 261, "Name": "Lump in the breast"}, {"ID": 266, "Name": "Malposition of the testicles"},
{"ID": 232, "Name": "Marked veins"}, {"ID": 235, "Name": "Memory gap"},
{"ID": 112, "Name": "Menstruation disorder"}, {"ID": 123, "Name": "Missed period"},
{"ID": 215, "Name": "Moist and softened skin"}, {"ID": 85, "Name": "Mood swings"},
{"ID": 983, "Name": "Morning stiffness"}, {"ID": 135, "Name": "Mouth pain"},
{"ID": 97, "Name": "Mouth ulcers"}, {"ID": 177, "Name": "Muscle pain"},
{"ID": 119, "Name": "Muscle stiffness"}, {"ID": 987, "Name": "Muscle weakness"},
{"ID": 252, "Name": "Muscular atrophy in the leg"}, {"ID": 202, "Name": "Muscular atrophy of the arm"},
{"ID": 168, "Name": "Muscular weakness in the arm"}, {"ID": 253, "Name": "Muscular weakness in the leg"},
{"ID": 44, "Name": "Nausea"}, {"ID": 136, "Name": "Neck pain"}, {"ID": 234, "Name": "Neck stiffness"},
{"ID": 114, "Name": "Nervousness"}, {"ID": 133, "Name": "Night cough"}, {"ID": 1004, "Name": "Night sweats"},
{"ID": 63, "Name": "Non-healing skin wound"}, {"ID": 38, "Name": "Nosebleed"},
{"ID": 221, "Name": "Numbness in the arm"}, {"ID": 254, "Name": "Numbness in the leg"},
{"ID": 200, "Name": "Numbness of the hands"}, {"ID": 137, "Name": "Oversensitivity to light"},
{"ID": 157, "Name": "Overweight"}, {"ID": 155, "Name": "Pain in the bones"},
{"ID": 142, "Name": "Pain in the calves"}, {"ID": 12, "Name": "Pain in the limbs"},
{"ID": 990, "Name": "Pain of the anus"}, {"ID": 203, "Name": "Pain on swallowing"},
{"ID": 251, "Name": "Pain radiating to the arm"}, {"ID": 103, "Name": "Pain radiating to the leg"},
{"ID": 286, "Name": "Pain when chewing"}, {"ID": 189, "Name": "Painful defecation"},
{"ID": 109, "Name": "Painful urination"}, {"ID": 150, "Name": "Pallor"}, {"ID": 37, "Name": "Palpitations"},
{"ID": 140, "Name": "Paralysis"}, {"ID": 118, "Name": "Physical inactivity"},
{"ID": 129, "Name": "Problems with the sense of touch in the face"},
{"ID": 130, "Name": "Problems with the sense of touch in the feet"},
{"ID": 258, "Name": "Protrusion of the eyes"}, {"ID": 172, "Name": "Purulent discharge from the urethra"},
{"ID": 173, "Name": "Purulent discharge from the vagina"}, {"ID": 191, "Name": "Rebound tenderness"},
{"ID": 54, "Name": "Reduced appetite"}, {"ID": 78, "Name": "Ringing in the ear"},
{"ID": 14, "Name": "Runny nose"}, {"ID": 975, "Name": "Sadness"}, {"ID": 269, "Name": "Scalp redness"},
{"ID": 1001, "Name": "Scar"}, {"ID": 60, "Name": "Sensitivity to cold"},
{"ID": 69, "Name": "Sensitivity to glare"}, {"ID": 102, "Name": "Sensitivity to noise"},
{"ID": 264, "Name": "Shiny red tongue"}, {"ID": 29, "Name": "Shortness of breath"},
{"ID": 183, "Name": "Side pain"}, {"ID": 26, "Name": "Skin lesion"}, {"ID": 25, "Name": "Skin nodules"},
{"ID": 124, "Name": "Skin rash"}, {"ID": 61, "Name": "Skin redness"}, {"ID": 217, "Name": "Skin thickening"},
{"ID": 34, "Name": "Skin wheal"}, {"ID": 241, "Name": "Sleepiness with spontaneous falling asleep"},
{"ID": 52, "Name": "Sleeplessness"}, {"ID": 95, "Name": "Sneezing"}, {"ID": 13, "Name": "Sore throat"},
{"ID": 64, "Name": "Sputum"}, {"ID": 179, "Name": "Stomach burning"},
{"ID": 185, "Name": "Stress-related leg pain"}, {"ID": 28, "Name": "Stuffy nose"},
{"ID": 138, "Name": "Sweating"}, {"ID": 236, "Name": "Swelling in the genital area"},
{"ID": 267, "Name": "Swelling of the testicles"}, {"ID": 248, "Name": "Swollen glands in the armpit"},
{"ID": 249, "Name": "Swollen glands in the groin"}, {"ID": 169, "Name": "Swollen glands in the neck"},
{"ID": 211, "Name": "Tears"}, {"ID": 222, "Name": "Testicular pain"}, {"ID": 243, "Name": "Tic"},
{"ID": 201, "Name": "Tingling"}, {"ID": 16, "Name": "Tiredness"}, {"ID": 997, "Name": "Toe deformity"},
{"ID": 1003, "Name": "Toe swelling"}, {"ID": 980, "Name": "Tongue burning"},
{"ID": 977, "Name": "Tongue swelling"}, {"ID": 1008, "Name": "Toothache"},
{"ID": 115, "Name": "Tremor at rest"}, {"ID": 132, "Name": "Tremor on movement"},
{"ID": 988, "Name": "Trouble understanding speech"}, {"ID": 144, "Name": "Unconsciousness, short"},
{"ID": 265, "Name": "Uncontrolled defecation"}, {"ID": 116, "Name": "Underweight"},
{"ID": 160, "Name": "Urge to urinate"}, {"ID": 161, "Name": "Urination during the night"},
{"ID": 68, "Name": "Vision impairment"}, {"ID": 213, "Name": "Vision impairment for far objects"},
{"ID": 166, "Name": "Vision impairment for near objects"}, {"ID": 66, "Name": "Visual field loss"},
{"ID": 101, "Name": "Vomiting"}, {"ID": 181, "Name": "Vomiting blood"},
{"ID": 972, "Name": "Weakness or numbness on right or left side of body"}, {"ID": 23, "Name": "Weight gain"},
{"ID": 22, "Name": "Weight loss"}, {"ID": 30, "Name": "Wheezing"}, {"ID": 187, "Name": "Wound"},
{"ID": 105, "Name": "Yellow colored skin"},
{"ID": 106, "Name": "Yellowish discoloration of the white part of the eye"}]
# l=['sss','sdd']
for i in l:
id = int(i["ID"])
name = str(i['Name'])
Disease.objects.create(ID1=id, name=name)
return HttpResponse(l)
def dashboard(request):
# users=ExtendedUserModel.objects.filter(user_object_id=request.user.id)
# users=user.mo
dat=ExtendedUserModel.objects.get(user_object=request.user)
data=Crowdsource.objects.filter(location=12)
return render(request,'health/index.html',{'data':data,'dat':dat})
def disease(request):
if request.method == 'GET':
symptoms = Disease.objects.all()
dat=ExtendedUserModel.objects.get(user_object=request.user)
return render(request, 'health/symptoms.html', {'sym': symptoms,'dat':dat})
if request.method == 'POST':
# symptoms=Disease.objects.all()
sym = request.POST.getlist('sym')
return redirect('/symptoms/')
def notifications(request):
if request.method == "POST":
pincode = request.POST.get('pincode')
user_list_object = ExtendedUserModel.objects.filter(location=pincode).values('phone_number')
return HttpResponse(user_list_object)
return render(request, 'health/get_pincode_for_notification.html')
def edit_profile(request):
instance = ExtendedUserModel.objects.get(user_object=request.user.id)
form = EditForm(request.POST or None, instance=instance)
if form.is_valid():
form.save()
return redirect(dashboard)
return render(request, 'health/edit.html', {'form': form})
def maps(request):
dat=ExtendedUserModel.objects.get(user_object=request.user)
return render(request,'health/maps.html',{'dat':dat}) | {"/CCWebsite/account/views.py": ["/CCWebsite/account/forms.py"], "/CCWebsite/account/forms.py": ["/CCWebsite/account/models.py"], "/CCWebsite/account/admin.py": ["/CCWebsite/account/models.py"], "/CCWebsite/health/admin.py": ["/CCWebsite/health/models.py"]} |
43,195 | fsociety6/SmartAurangabadHack | refs/heads/master | /CCWebsite/health/migrations/0003_auto_20200121_1920.py | # Generated by Django 2.2.5 on 2020-01-21 13:50
from django.db import migrations, models
import django.utils.timezone
class Migration(migrations.Migration):
dependencies = [
('health', '0002_crowdsource'),
]
operations = [
migrations.AddField(
model_name='crowdsource',
name='created_date',
field=models.DateTimeField(auto_now_add=True, default=django.utils.timezone.now),
preserve_default=False,
),
migrations.AddField(
model_name='crowdsource',
name='modified_date',
field=models.DateTimeField(auto_now=True),
),
migrations.AlterField(
model_name='crowdsource',
name='Gender',
field=models.CharField(choices=[('MALE', 'Male'), ('FEMALE', 'Female')], max_length=1),
),
]
| {"/CCWebsite/account/views.py": ["/CCWebsite/account/forms.py"], "/CCWebsite/account/forms.py": ["/CCWebsite/account/models.py"], "/CCWebsite/account/admin.py": ["/CCWebsite/account/models.py"], "/CCWebsite/health/admin.py": ["/CCWebsite/health/models.py"]} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.