"""
Django settings for CourtCase project.

Generated by 'django-admin startproject' using Django 1.11.

For more information on this file, see
https://docs.djangoproject.com/en/1.11/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.11/ref/settings/
"""

import os
from pymongo import MongoClient
from keras.models import load_model
import keras.backend as K
import pickle
import numpy as np


# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
print(BASE_DIR)


# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.11/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '2t5-ou17q=o$h&cg5p-2-_x$*%$xj2+(npgr^3i-dso3+p6y&&'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = ['*']


# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'recommend',
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
#    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'CourtCase.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'CourtCase.wsgi.application'


# Database
# https://docs.djangoproject.com/en/1.11/ref/settings/#databases

DATABASES = {
#    'default': {
#        'ENGINE': 'django.db.backends.sqlite3',
#        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
#    }
}


# Password validation
# https://docs.djangoproject.com/en/1.11/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]


# Internationalization
# https://docs.djangoproject.com/en/1.11/topics/i18n/

LANGUAGE_CODE = 'en_us'

TIME_ZONE = 'Asia/Shanghai'

USE_I18N = True

USE_L10N = True

USE_TZ = True


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.11/howto/static-files/

STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'CourtCase/static/')
STATICFILES_DIRS = (
    'recommend/static/',
)



#载入停用词词典
def load_stop_words(path = 'data/stopWords.txt'):
    stw = []
    with open(path, 'r') as fp:
        for line in fp:
            stw.append(line.strip())
    return stw

# STWS = load_stop_words(os.path.join(BASE_DIR, 'recommend/model/', 'stopwords.txt'))
# STFS = ['b', 'c', 'e', 'g', 'h', 'k', 'l',
#               'o', 's', 'u', 'w', 'x', 'y', 'z',
#               'un', 'nr', 'f', 'i', 'm', 'p',
#               'q', 'r', 'tg', 't']

STWS = None
STFS = None

MAX_LEN = 200

#载入案由预测过程词典
def load_dict(path):
    with open(path, 'rb') as fp:
        dic = pickle.load(fp)
    return dic
# WordDicCls = load_dict(os.path.join(BASE_DIR, 'recommend/model/', 'cls_dictionary.dic'))
WordDicCls = None

#载入打分过程词典
# WordDicRank = load_dict(os.path.join(BASE_DIR, 'recommend/model/', rank_dictionary.dic'))
WordDicRank = None

#载入案由预测模型
def load_case_reason_model(model_path, cls_dict_path):
    def load_cls_weight(path):
        with open(path, 'rb') as fp:
            dic = pickle.load(fp)
        weight_dic = [[item[0], item[1]] for _, item in dic.items()]
        weight_dic.sort(key=lambda x:x[0])
        weight = np.array([item[1] for item in weight_dic])
        return weight
    cls_weight = load_cls_weight(cls_dict_path)
    def my_loss(y_true, y_pred):
        gamma = 2
        alpha = np.max(y_true * cls_weight, axis=-1)
        tmp = np.max(y_true * y_pred, axis=-1)
        return -K.mean(alpha * K.pow(1. - tmp, gamma) * K.log(K.clip(tmp, 1e-8, 1.0)))

    def my_metric(y_true, y_pred):
        predictions = K.argmax(y_pred)
        correct_predictions = K.equal(predictions, K.argmax(y_true))
        return K.mean(K.cast(correct_predictions, "float"))

    model = load_model(model_path, {'my_loss': my_loss, 'my_metric': my_metric})
    return model
# CaseReasonModel = load_case_reason_model(
#     model_path = os.path.join(BASE_DIR, 'recommend/model/', 'cr_model.h5'),
#     cls_dict_path = os.path.join(BASE_DIR, 'recommend/model/', 'cls_5w.dic')
# )
CaseReasonModel = None

#载入案由映射词典
def load_cls_dict(path):
    with open(path, 'rb') as fp:
        dic = pickle.load(fp)
    weight_dic = [[item[0], cls] for cls, item in dic.items()]
    weight_dic.sort(key=lambda x:x[0])
    cls_list = [item[1] for item in weight_dic]
    return cls_list
# ClsDict = load_cls_dict(os.path.join(BASE_DIR, 'recommend/model/', 'cls_5w.dic'))
ClsDict = None

#载入各类别内部重排序模型
def load_rank_model(model_path):
    def my_loss(y_true, y_pred):
        return K.mean(K.pow(K.log(y_pred+1)-K.log(y_true+1), 2))
    model = load_model(model_path, {'my_loss': my_loss})
    return model
# RankModel = load_rank_model(os.path.join(BASE_DIR, 'recommend/model/', 'rank_model.h5'))
RankModel = None

#数据库
# CONN = MongoClient('172.19.241.248', 20000)
# CONN = None