Skip to content

Commit

Permalink
Merge pull request #1 from haladamateusz/backend
Browse files Browse the repository at this point in the history
Backend
  • Loading branch information
PaulCalot committed Oct 28, 2023
2 parents e95f134 + bf414ad commit f8e279d
Show file tree
Hide file tree
Showing 31 changed files with 302 additions and 12 deletions.
9 changes: 9 additions & 0 deletions Makefile
@@ -0,0 +1,9 @@
SHELL := /bin/bash
CONDA := /home/paul/anaconda3/bin/conda

run_server:
source $$(/home/paul/miniconda/bin/conda info --base)/etc/profile.d/conda.sh ; \
conda activate appenv ; \
python backend/manage.py makemigrations ; \
python backend/manage.py migrate ; \
python backend/manage.py runserver
Empty file added backend/backend/__init__.py
Empty file.
Binary file added backend/backend/__pycache__/__init__.cpython-311.pyc
Binary file not shown.
Binary file not shown.
Binary file added backend/backend/__pycache__/urls.cpython-311.pyc
Binary file not shown.
Binary file added backend/backend/__pycache__/wsgi.cpython-311.pyc
Binary file not shown.
16 changes: 16 additions & 0 deletions backend/backend/asgi.py
@@ -0,0 +1,16 @@
"""
ASGI config for backend 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/4.2/howto/deployment/asgi/
"""

import os

from django.core.asgi import get_asgi_application

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

application = get_asgi_application()
127 changes: 127 additions & 0 deletions backend/backend/settings.py
@@ -0,0 +1,127 @@
"""
Django settings for backend project.
Generated by 'django-admin startproject' using Django 4.2.4.
For more information on this file, see
https://docs.djangoproject.com/en/4.2/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/4.2/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/4.2/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'django-insecure-c6k@o#a!)p0=l1q%_zc!=tw624-*4a6u*c651oon7r_k+0&mrs'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = ["*"]
CORS_ORIGIN_ALLOW_ALL = True
CORS_ALLOWED_ORIGINS = []

# Application definition

INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework',
'drag',
'corsheaders',
]

MIDDLEWARE = [
'corsheaders.middleware.CorsMiddleware',
'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 = 'backend.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 = 'backend.wsgi.application'


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

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


# Password validation
# https://docs.djangoproject.com/en/4.2/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/4.2/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/4.2/howto/static-files/

STATIC_URL = 'static/'

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

DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
7 changes: 7 additions & 0 deletions backend/backend/urls.py
@@ -0,0 +1,7 @@
from django.contrib import admin
from django.urls import path, include

urlpatterns = [
path('admin/', admin.site.urls),
path('', include('drag.urls')),
]
16 changes: 16 additions & 0 deletions backend/backend/wsgi.py
@@ -0,0 +1,16 @@
"""
WSGI config for backend 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/4.2/howto/deployment/wsgi/
"""

import os

from django.core.wsgi import get_wsgi_application

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

application = get_wsgi_application()
Binary file added backend/db.sqlite3
Binary file not shown.
Empty file added backend/drag/__init__.py
Empty file.
Binary file added backend/drag/__pycache__/__init__.cpython-311.pyc
Binary file not shown.
Binary file added backend/drag/__pycache__/admin.cpython-311.pyc
Binary file not shown.
Binary file added backend/drag/__pycache__/apps.cpython-311.pyc
Binary file not shown.
Binary file added backend/drag/__pycache__/models.cpython-311.pyc
Binary file not shown.
Binary file not shown.
Binary file added backend/drag/__pycache__/urls.cpython-311.pyc
Binary file not shown.
Binary file added backend/drag/__pycache__/views.cpython-311.pyc
Binary file not shown.
3 changes: 3 additions & 0 deletions backend/drag/admin.py
@@ -0,0 +1,3 @@
from django.contrib import admin

# Register your models here.
6 changes: 6 additions & 0 deletions backend/drag/apps.py
@@ -0,0 +1,6 @@
from django.apps import AppConfig


class DragConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
name = 'drag'
Empty file.
Binary file not shown.
3 changes: 3 additions & 0 deletions backend/drag/models.py
@@ -0,0 +1,3 @@
from django.db import models

# Create your models here.
11 changes: 11 additions & 0 deletions backend/drag/serializers.py
@@ -0,0 +1,11 @@
from rest_framework import serializers

class QuestionSerializer(serializers.Serializer):
question = serializers.CharField()
userId = serializers.CharField()

class FeedbackSerializer(serializers.Serializer):
previousQuestion = serializers.CharField()
previousResults = serializers.JSONField()
feedback = serializers.ChoiceField(choices=['OKAY', 'BAD_GPT', 'BAD_DOCUMENTS'])
userId = serializers.CharField()
3 changes: 3 additions & 0 deletions backend/drag/tests.py
@@ -0,0 +1,3 @@
from django.test import TestCase

# Create your tests here.
11 changes: 11 additions & 0 deletions backend/drag/urls.py
@@ -0,0 +1,11 @@
from django.urls import path, include
from rest_framework.routers import DefaultRouter
from .views import AskQuestionViewSet, SendFeedbackViewSet

router = DefaultRouter()
router.register(r'askQuestion', AskQuestionViewSet, basename='ask-question')
router.register(r'sendFeedback', SendFeedbackViewSet, basename='send-feedback')

urlpatterns = [
path('', include(router.urls)),
]
41 changes: 41 additions & 0 deletions backend/drag/views.py
@@ -0,0 +1,41 @@
from rest_framework import viewsets, status
from rest_framework.response import Response
from .serializers import QuestionSerializer, FeedbackSerializer

def query_model(question):
# Replace this with the actual implementation
return {
"result": [
{'url': 'http://example.com'
, 'description': 'Example'
, 'sysId': 'ahsoashoa'
, 'type': 'PDF'
, 'language': 'English'
}
]
}


def handle_feedback(feedback, previousQuestion, previousResults):
# Replace this with the actual implementation
return [{'status': 'received'}]

class AskQuestionViewSet(viewsets.ViewSet):
def create(self, request):
serializer = QuestionSerializer(data=request.data)
if serializer.is_valid():
data = serializer.validated_data
response_data = query_model(data['question'])
return Response(response_data, status=status.HTTP_200_OK)
else:
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

class SendFeedbackViewSet(viewsets.ViewSet):
def create(self, request):
serializer = FeedbackSerializer(data=request.data)
if serializer.is_valid():
data = serializer.validated_data
response_data = handle_feedback(data['feedback'], data['previousQuestion'], data['previousResults'])
return Response(response_data, status=status.HTTP_200_OK)
else:
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
22 changes: 22 additions & 0 deletions backend/manage.py
@@ -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', 'backend.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()
5 changes: 4 additions & 1 deletion frontend/angular.json
Expand Up @@ -118,6 +118,9 @@
}
},
"cli": {
"schematicCollections": ["@angular-eslint/schematics"]
"schematicCollections": [
"@angular-eslint/schematics"
],
"analytics": false
}
}
34 changes: 23 additions & 11 deletions frontend/src/app/service/llama/llama.service.ts
Expand Up @@ -3,6 +3,7 @@ import { HttpClient } from '@angular/common/http';
import { LlamaResponseResult } from '../../models/llama-response.interface';
import { BehaviorSubject, Observable, of, tap } from 'rxjs';
import { LlamaResponseMock } from '../../mocks/LlamaResponse.mock';
import { FEEDBACK } from 'src/app/models/feedback.enum';

@Injectable({
providedIn: 'root'
Expand All @@ -15,24 +16,35 @@ export class LlamaService {
askQuestion(question: string, userId: string): Observable<LlamaResponseResult> {
console.log('endpoint: /askQuestion');
console.log('body', { question, userId });
return of(LlamaResponseMock).pipe(
tap(data => {
this.lastResults.next(data);
this.lastQuestionAsked.next(question);
})
);
//this.httpClient.post<LlamaResponse>('<PASTE_URL_HERE>', { question, userId });
}
// return of(LlamaResponseMock).pipe(
// tap(data => {
// this.lastResults.next(data);
// this.lastQuestionAsked.next(question);
// })
// );
return this.httpClient.post<LlamaResponseResult>('http://127.0.0.1:8000/askQuestion/', { question, userId }).pipe(
tap(data => {
this.lastResults.next(data);
this.lastQuestionAsked.next(question);
})
);
}

sendFeedback(feedback: string, userId: string): Observable<boolean> {
sendFeedback(feedback: FEEDBACK, userId: string): Observable<boolean> {
console.log('endpoint: /sendFeedback');
console.log('body', {
feedback,
userId,
question: this.lastQuestionAsked.getValue(),
results: this.lastResults.getValue()
});
return of(true);
// this.httpClient.post<LlamaResponse>('<PASTE_URL_HERE>', { feedback, userId, previousQuestion, previousResults });
// return of(true);
return this.httpClient.post<boolean>('http://127.0.0.1:8000/sendFeedback/'
, {
feedback,
userId,
previousQuestion: this.lastQuestionAsked.getValue(),
previousResults: this.lastResults.getValue()
});
}
}

0 comments on commit f8e279d

Please sign in to comment.