Skip to content
This repository has been archived by the owner on Aug 28, 2024. It is now read-only.

Commit

Permalink
:alert: black linting
Browse files Browse the repository at this point in the history
  • Loading branch information
Gary-H9 committed Jul 2, 2024
1 parent 249b538 commit b1b7e93
Show file tree
Hide file tree
Showing 7 changed files with 81 additions and 75 deletions.
2 changes: 1 addition & 1 deletion ollamate/asgi.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,6 @@

from django.core.asgi import get_asgi_application

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'ollamate.settings')
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "ollamate.settings")

application = get_asgi_application()
103 changes: 53 additions & 50 deletions ollamate/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

# Read the .env file
env_file = os.path.join(BASE_DIR, '.env')
env_file = os.path.join(BASE_DIR, ".env")
if os.path.isfile(env_file):
print(f"Loading environment variables from {env_file}")
environ.Env.read_env(env_file)
Expand All @@ -40,7 +40,7 @@
# See https://docs.djangoproject.com/en/5.0/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'django-insecure-(y%c-1p0lnlrxg!$3w)ptcyp=wzer(biav_-%_fehgn1oatx8p'
SECRET_KEY = "django-insecure-(y%c-1p0lnlrxg!$3w)ptcyp=wzer(biav_-%_fehgn1oatx8p"

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
Expand All @@ -52,53 +52,55 @@
# Application definition

INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'streamingapp',
'azure_auth'
"django.contrib.admin",
"django.contrib.auth",
"django.contrib.contenttypes",
"django.contrib.sessions",
"django.contrib.messages",
"django.contrib.staticfiles",
"streamingapp",
"azure_auth",
]

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',
"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 = 'ollamate.urls'
ROOT_URLCONF = "ollamate.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',
"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 = 'ollamate.wsgi.application'
WSGI_APPLICATION = "ollamate.wsgi.application"


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

DB_HOST = os.environ.get("DB_HOST", "127.0.0.1")
ENABLE_DB_SSL = (
str(os.environ.get("ENABLE_DB_SSL", DB_HOST not in ["127.0.0.1", "localhost"])).lower()
str(
os.environ.get("ENABLE_DB_SSL", DB_HOST not in ["127.0.0.1", "localhost"])
).lower()
== "true"
)
DATABASES: dict = {
Expand All @@ -121,26 +123,26 @@

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


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

LANGUAGE_CODE = 'en-us'
LANGUAGE_CODE = "en-us"

TIME_ZONE = 'UTC'
TIME_ZONE = "UTC"

USE_I18N = True

Expand All @@ -150,12 +152,12 @@
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/5.0/howto/static-files/

STATIC_URL = 'static/'
STATIC_URL = "static/"

# Default primary key field type
# https://docs.djangoproject.com/en/5.0/ref/settings/#default-auto-field

DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
DEFAULT_AUTO_FIELD = "django.db.models.BigAutoField"

# Azure authentication settings

Expand All @@ -164,21 +166,22 @@
"CLIENT_SECRET": env("CLIENT_SECRET"),
"REDIRECT_URI": env("REDIRECT_URI"),
"SCOPES": ["User.Read"],
"AUTHORITY": "https://login.microsoftonline.com/{}".format(env("AZURE_TENANT_ID")), # Or https://login.microsoftonline.com/common if multi-tenant
# # "LOGOUT_URI": "https://<domain>/logout", # Optional
# # "PUBLIC_URLS": ["<public:view_name>",], # Optional, public views accessible by non-authenticated users
# # "PUBLIC_PATHS": ['/go/',], # Optional, public paths accessible by non-authenticated users
# # "ROLES": {
# # "95170e67-2bbf-4e3e-a4d7-e7e5829fe7a7": "GroupName1",
# # "3dc6539e-0589-4663-b782-fef100d839aa": "GroupName2"
# # }, # Optional, will add user to django group if user is in EntraID group
"USERNAME_ATTRIBUTE": "mail", # The AAD attribute or ID token claim you want to use as the value for the user model `USERNAME_FIELD`
# # "EXTRA_FIELDS": [], # Optional, extra AAD user profile attributes you want to make available in the user mapping function
# "USER_MAPPING_FN": "azure_auth.tests.misc.user_mapping_fn", # Optional, path to the function used to map the AAD to Django attributes
"AUTHORITY": "https://login.microsoftonline.com/{}".format(
env("AZURE_TENANT_ID")
), # Or https://login.microsoftonline.com/common if multi-tenant
# # "LOGOUT_URI": "https://<domain>/logout", # Optional
# # "PUBLIC_URLS": ["<public:view_name>",], # Optional, public views accessible by non-authenticated users
# # "PUBLIC_PATHS": ['/go/',], # Optional, public paths accessible by non-authenticated users
# # "ROLES": {
# # "95170e67-2bbf-4e3e-a4d7-e7e5829fe7a7": "GroupName1",
# # "3dc6539e-0589-4663-b782-fef100d839aa": "GroupName2"
# # }, # Optional, will add user to django group if user is in EntraID group
"USERNAME_ATTRIBUTE": "mail", # The AAD attribute or ID token claim you want to use as the value for the user model `USERNAME_FIELD`
# # "EXTRA_FIELDS": [], # Optional, extra AAD user profile attributes you want to make available in the user mapping function
# "USER_MAPPING_FN": "azure_auth.tests.misc.user_mapping_fn", # Optional, path to the function used to map the AAD to Django attributes
}
LOGIN_URL = "/azure_auth/login"
LOGIN_REDIRECT_URL = "/"
LOGOUT_REDIRECT_URL = '/'
LOGOUT_REDIRECT_URL = "/"

AUTHENTICATION_BACKENDS = ("azure_auth.backends.AzureBackend",)

11 changes: 7 additions & 4 deletions ollamate/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,11 @@
from streamingapp.views import redirect_to_ollama

urlpatterns = [
path('admin/', admin.site.urls),
path("azure_auth/", include("azure_auth.urls"),),
path('stream/', include('streamingapp.urls')),
path('', redirect_to_ollama)
path("admin/", admin.site.urls),
path(
"azure_auth/",
include("azure_auth.urls"),
),
path("stream/", include("streamingapp.urls")),
path("", redirect_to_ollama),
]
2 changes: 1 addition & 1 deletion ollamate/wsgi.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,6 @@

from django.core.wsgi import get_wsgi_application

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'ollamate.settings')
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "ollamate.settings")

application = get_wsgi_application()
4 changes: 2 additions & 2 deletions streamingapp/apps.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,5 +2,5 @@


class StreamingappConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
name = 'streamingapp'
default_auto_field = "django.db.models.BigAutoField"
name = "streamingapp"
2 changes: 1 addition & 1 deletion streamingapp/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,5 +2,5 @@
from . import views

urlpatterns = [
path('call-ollama/', views.call_ollama, name='call_ollama'),
path("call-ollama/", views.call_ollama, name="call_ollama"),
]
32 changes: 16 additions & 16 deletions streamingapp/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,26 +8,23 @@
# Configure logging
logging.basicConfig(level=logging.DEBUG)


@azure_auth_required
def call_ollama(request):
if request.method == 'POST':
user_input = request.POST.get('userInput', '')
if request.method == "POST":
user_input = request.POST.get("userInput", "")
try:
conversation_history = json.loads(user_input)
except json.JSONDecodeError as e:
logging.error("JSONDecodeError: %s", e)
return JsonResponse({"error": "Invalid input format"}, status=400)

url = 'http://localhost:11434/api/chat'
headers = {'Content-Type': 'application/json'}
data = {
"model": "llama3",
"messages": conversation_history,
"stream": False
}

url = "http://localhost:11434/api/chat"
headers = {"Content-Type": "application/json"}
data = {"model": "llama3", "messages": conversation_history, "stream": False}

logging.debug("Sending data to Ollama API: %s", json.dumps(data, indent=2))

try:
response = requests.post(url, json=data, headers=headers)
response.raise_for_status()
Expand All @@ -37,14 +34,17 @@ def call_ollama(request):
ollama_response = response_data.get("message", {}).get("content", "")
if not ollama_response:
logging.error("Empty response from Ollama API")
return JsonResponse({"error": "Empty response from Ollama API"}, status=500)

return JsonResponse(
{"error": "Empty response from Ollama API"}, status=500
)

return JsonResponse({"response": ollama_response})
except requests.RequestException as e:
logging.error("RequestException: %s", e)
return JsonResponse({"error": str(e)}, status=500)
else:
return render(request, 'streamingapp/input_form.html')

return render(request, "streamingapp/input_form.html")


def redirect_to_ollama(request):
return redirect('/stream/call-ollama')
return redirect("/stream/call-ollama")

0 comments on commit b1b7e93

Please sign in to comment.