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

🚀 Initialise project #3

Merged
merged 1 commit into from
Jul 1, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -8,3 +8,12 @@ env/
*.code-workspace
*.sha256
terraform.tfstate
super-linter.log
.mypy_cache/
.idea/
__pycache__
*.egg-info/
node_modules/
/static/
/run/
db.sqlite3
22 changes: 22 additions & 0 deletions manage.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
#!/usr/bin/env python
"""Django's command-line utility for administrative tasks."""
import os
import sys


def main():
"""Run administrative tasks."""
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'ollamate.settings')
try:
from django.core.management import execute_from_command_line
except ImportError as exc:
raise ImportError(
"Couldn't import Django. Are you sure it's installed and "
"available on your PYTHONPATH environment variable? Did you "
"forget to activate a virtual environment?"
) from exc
execute_from_command_line(sys.argv)


if __name__ == '__main__':
main()
Empty file added ollamate/__init__.py
Empty file.
16 changes: 16 additions & 0 deletions ollamate/asgi.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
"""
ASGI config for ollamate project.

It exposes the ASGI callable as a module-level variable named ``application``.

For more information on this file, see
https://docs.djangoproject.com/en/5.0/howto/deployment/asgi/
"""

import os

from django.core.asgi import get_asgi_application

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

application = get_asgi_application()
124 changes: 124 additions & 0 deletions ollamate/settings.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,124 @@
"""
Django settings for ollamate project.

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

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

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

from pathlib import Path

# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent


# Quick-start development settings - unsuitable for production
# 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'

# 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',
'streamingapp'
]

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 = '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',
],
},
},
]

WSGI_APPLICATION = 'ollamate.wsgi.application'


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

DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
}
}


# Password validation
# https://docs.djangoproject.com/en/5.0/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/5.0/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_TZ = True


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

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'
23 changes: 23 additions & 0 deletions ollamate/urls.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
"""
URL configuration for ollamate project.

The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/5.0/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path, include

urlpatterns = [
path('admin/', admin.site.urls),
path('stream/', include('streamingapp.urls'))
]
16 changes: 16 additions & 0 deletions ollamate/wsgi.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
"""
WSGI config for ollamate project.

It exposes the WSGI callable as a module-level variable named ``application``.

For more information on this file, see
https://docs.djangoproject.com/en/5.0/howto/deployment/wsgi/
"""

import os

from django.core.wsgi import get_wsgi_application

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

application = get_wsgi_application()
Empty file added streamingapp/__init__.py
Empty file.
3 changes: 3 additions & 0 deletions streamingapp/admin.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
from django.contrib import admin

# Register your models here.
6 changes: 6 additions & 0 deletions streamingapp/apps.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
from django.apps import AppConfig


class StreamingappConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
name = 'streamingapp'
Empty file.
3 changes: 3 additions & 0 deletions streamingapp/models.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
from django.db import models

# Create your models here.
132 changes: 132 additions & 0 deletions streamingapp/templates/streamingapp/input_form.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,132 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Ollamate 🦙🍵</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.5.1/styles/default.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.5.1/highlight.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/tailwindcss/2.2.19/tailwind.min.css" rel="stylesheet">
<style>
html, body {
height: 100%;
margin: 0;
display: flex;
flex-direction: column;
}
.container {
flex: 1;
}
.ollama-response {
white-space: pre-wrap; /* Ensures that whitespace and line breaks are preserved */
word-wrap: break-word; /* Allows breaking long words to wrap properly */
}
pre {
position: relative;
}
.code-label {
position: absolute;
top: 0;
left: 0;
width: 100%;
background: #333;
color: #fff;
padding: 5px 10px;
font-size: 12px;
border-top-left-radius: 5px;
border-top-right-radius: 5px;
box-sizing: border-box; /* Ensure padding does not overflow the box */
}
</style>
</head>
<body class="bg-gray-100 font-sans leading-normal tracking-normal">
<div class="w-full bg-yellow-400 text-center p-2">
<p class="text-black font-bold">A Proof of Concept by the <a href="https://github.com/ministryofjustice/analytical-platform" class="text-blue-700 hover:underline">Analytical Platform</a></p>
</div>
</div>
</div>
<div class="container mx-auto p-4">
<h1 class="text-3xl font-bold mb-4 text-center">Ollamate 🦙🍵</h1>
<h2 class="text-xl font-bold mb-4 text-center">A Simple Conversational AI.</h2>
<p class="mb-4">Enter text below to interact with Ollamate:</p>
<div id="conversation-log" class="bg-white p-4 rounded shadow-lg hidden text-base">
</div>
<form id="ollamaForm" class="mt-4">
<div class="flex items-center">
<textarea id="userInput" name="userInput" required class="border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline resize-none"></textarea>
<button type="submit" class="bg-blue-500 hover:bg-blue-700 text-white py-2 px-4 rounded ml-2">Send</button>
</div>
</form>
</div>

<footer class="bg-gray-800 text-white py-4 mt-8">
<div class="container mx-auto text-center">
<p>📝 <a href="https://github.com/ministryofjustice/analytical-platform" class="text-blue-500 hover:underline">GitHub Repository</a></p>
</div>
</footer>

<script>
$(document).ready(function() {
var conversationHistory = [];

$('#userInput').on('input', function() {
this.style.height = 'auto';
this.style.height = (this.scrollHeight) + 'px';
});

$('#ollamaForm').on('submit', function(event) {
event.preventDefault();
var userInput = $('#userInput').val();
$('#userInput').val('');
$('#userInput').css('height', 'auto');

conversationHistory.push({"role": "user", "content": userInput});

$('#conversation-log').removeClass('hidden');
$('#conversation-log').append('<div class="conversation mb-4"><span class="user-query block text-blue-700 ollama-response"><strong>User:</strong> ' + userInput + '</span></div>');
scrollToBottom();

$.ajax({
url: "{% url 'call_ollama' %}",
type: "POST",
data: {
userInput: JSON.stringify(conversationHistory),
csrfmiddlewaretoken: '{{ csrf_token }}'
},
success: function(response) {
var ollamaResponse = response.response;

var formattedResponse = formatResponse(ollamaResponse);

conversationHistory.push({"role": "assistant", "content": formattedResponse});

$('#conversation-log').append('<div class="conversation mb-4"><span class="ollama-response block text-green-700"><strong>Ollama:</strong> ' + formattedResponse + '</span></div>');
scrollToBottom();

$('pre code').each(function(i, block) {
hljs.highlightElement(block);
});
},
error: function(xhr, status, error) {
$('#conversation-log').append('<div class="conversation mb-4"><span class="ollama-response block text-red-700"><strong>Error:</strong> ' + xhr.responseText + '</span></div>');
scrollToBottom();
}
});
});

function formatResponse(response) {
return response.replace(/```(\w+)?\n([\s\S]*?)```/g, function(match, p1, p2) {
var langClass = p1 ? 'language-' + p1 : '';
var langLabel = p1 ? p1.toUpperCase() : 'CODE';
return '<pre class="rounded overflow-hidden border"><div class="code-label">' + langLabel + '</div><code class="' + langClass + ' p-4">' + p2 + '</code></pre>';
});
}

function scrollToBottom() {
const offset = 100;
window.scrollTo({ top: document.body.scrollHeight + offset, behavior: 'smooth' });
}
});
</script>
</body>
</html>
3 changes: 3 additions & 0 deletions streamingapp/tests.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
from django.test import TestCase

# Create your tests here.
6 changes: 6 additions & 0 deletions streamingapp/urls.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
from django.urls import path
from . import views

urlpatterns = [
path('call-ollama/', views.call_ollama, name='call_ollama'),
]
Loading