Skip to content
Open
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
3 changes: 3 additions & 0 deletions backend/backend/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
from .celery import app as celery_app

_all_ = ('celery_app',)
12 changes: 12 additions & 0 deletions backend/backend/celery.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
# backend/celery.py

import os
from celery import Celery

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

app = Celery('backend')

app.config_from_object('django.conf:settings', namespace='CELERY')

app.autodiscover_tasks()
51 changes: 46 additions & 5 deletions backend/backend/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,8 +24,15 @@
# See https://docs.djangoproject.com/en/4.2/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = os.environ["DJANGO_SECRET_KEY"]
FRONTEND_URL = os.environ["FRONTEND_URL"]
# SECRET_KEY = os.environ["DJANGO_SECRET_KEY"]
# FRONTEND_URL = os.environ["FRONTEND_URL"]


from decouple import config
SECRET_KEY=config("DJANGO_SECRET_KEY")

# FRONTEND_URL
FRONTEND_URL=config("FRONTEND_URL",default="http://localhost:3000")

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
Expand All @@ -47,6 +54,7 @@
"authentication",
"chat",
"gpt",
'django_filters',
]

MIDDLEWARE = [
Expand Down Expand Up @@ -84,10 +92,15 @@
# Database
# https://docs.djangoproject.com/en/4.2/ref/settings/#databases


DATABASES = {
"default": {
"ENGINE": "django.db.backends.sqlite3",
"NAME": BASE_DIR / "db.sqlite3",
'default': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': 'fs_ai_db',
'USER': 'postgres',
'PASSWORD': '12345',
'HOST': 'localhost',
'PORT': '5432'
}
}

Expand Down Expand Up @@ -149,3 +162,31 @@
SESSION_COOKIE_SECURE = True
CSRF_COOKIE_SECURE = True
CSRF_COOKIE_SAMESITE = "None"


# CELERY SETTINGS
CELERY_BROKER_URL = 'redis://localhost:6379/0'
CELERY_ACCEPT_CONTENT = ['json']
CELERY_TASK_SERIALIZER = 'json'

# CELERY BEAT SETTINGS
INSTALLED_APPS += ['django_celery_beat']

REST_FRAMEWORK = {
'DEFAULT_FILTER_BACKENDS': ['django_filters.rest_framework.DjangoFilterBackend'],
'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',
'PAGE_SIZE': 5,
}


LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'handlers': {
'console': { 'class': 'logging.StreamHandler' },
},
'root': {
'handlers': ['console'],
'level': 'INFO',
},
}
74 changes: 53 additions & 21 deletions backend/chat/admin.py
Original file line number Diff line number Diff line change
@@ -1,34 +1,69 @@
from django.contrib import admin
from django.utils import timezone
from django.core.exceptions import ValidationError
from django.forms import ModelForm
from nested_admin.nested import NestedModelAdmin, NestedStackedInline, NestedTabularInline

from chat.models import Conversation, Message, Role, Version
from chat.models import Conversation, Message, Role, Version, FileUpload


# Custom Form for FileUpload

class FileUploadForm(ModelForm):
class Meta:
model = FileUpload
fields = '__all__'

def clean(self):
cleaned_data = super().clean()
file = cleaned_data.get('file')

if file:
import hashlib
hash_obj = hashlib.sha256()
for chunk in file.chunks():
hash_obj.update(chunk)
file_hash = hash_obj.hexdigest()

# Check if the same file already exists
if FileUpload.objects.filter(file_hash=file_hash).exclude(pk=self.instance.pk).exists():
raise ValidationError("⚠️ File already exists in the system (duplicate content).")

# Store the hash
cleaned_data['file_hash'] = file_hash

return cleaned_data


class FileUploadAdmin(admin.ModelAdmin):
form = FileUploadForm
readonly_fields = ('file_hash', 'uploaded_at') # Hide from editable fields
fields = ('file', 'original_name') # Only show editable fields
list_display = ('original_name', 'file_hash', 'uploaded_at') # Optional display


# Rest of your admin setup


class RoleAdmin(NestedModelAdmin):
list_display = ["id", "name"]


class MessageAdmin(NestedModelAdmin):
list_display = ["display_desc", "role", "id", "created_at", "version"]

def display_desc(self, obj):
return obj.content[:20] + "..."

display_desc.short_description = "content"


class MessageInline(NestedTabularInline):
model = Message
extra = 2 # number of extra forms to display

extra = 2

class VersionInline(NestedStackedInline):
model = Version
extra = 1
inlines = [MessageInline]


class DeletedListFilter(admin.SimpleListFilter):
title = "Deleted"
parameter_name = "deleted"
Expand All @@ -40,53 +75,50 @@ def lookups(self, request, model_admin):
)

def queryset(self, request, queryset):
value = self.value()
if value == "True":
if self.value() == "True":
return queryset.filter(deleted_at__isnull=False)
elif value == "False":
elif self.value() == "False":
return queryset.filter(deleted_at__isnull=True)
return queryset


class ConversationAdmin(NestedModelAdmin):
actions = ["undelete_selected", "soft_delete_selected"]
inlines = [VersionInline]
list_display = ("title", "id", "created_at", "modified_at", "deleted_at", "version_count", "is_deleted", "user")
list_filter = (DeletedListFilter,)
list_display = ("title", "id", "created_at", "modified_at", "deleted_at", "version_count", "is_deleted", "user", "summary")
list_filter = (DeletedListFilter, 'created_at', 'user')
search_fields = ('title', 'summary', 'user__username')
list_per_page = 10
ordering = ("-modified_at",)

def undelete_selected(self, request, queryset):
queryset.update(deleted_at=None)

undelete_selected.short_description = "Undelete selected conversations"

def soft_delete_selected(self, request, queryset):
queryset.update(deleted_at=timezone.now())

soft_delete_selected.short_description = "Soft delete selected conversations"

def get_action_choices(self, request, **kwargs):
choices = super().get_action_choices(request)
for idx, choice in enumerate(choices):
fn_name = choice[0]
if fn_name == "delete_selected":
new_choice = (fn_name, "Hard delete selected conversations")
choices[idx] = new_choice
if choice[0] == "delete_selected":
choices[idx] = ("delete_selected", "Hard delete selected conversations")
return choices

def is_deleted(self, obj):
return obj.deleted_at is not None

is_deleted.boolean = True
is_deleted.short_description = "Deleted?"


class VersionAdmin(NestedModelAdmin):
inlines = [MessageInline]
list_display = ("id", "conversation", "parent_version", "root_message")


# Register all models

admin.site.register(Role, RoleAdmin)
admin.site.register(Message, MessageAdmin)
admin.site.register(Conversation, ConversationAdmin)
admin.site.register(Version, VersionAdmin)
admin.site.register(FileUpload, FileUploadAdmin)
7 changes: 5 additions & 2 deletions backend/chat/apps.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,5 +2,8 @@


class ChatConfig(AppConfig):
default_auto_field = "django.db.models.BigAutoField"
name = "chat"
default_auto_field = 'django.db.models.BigAutoField'
name = 'chat'

def ready(self):
import chat.signals
20 changes: 20 additions & 0 deletions backend/chat/management/commands/cleanup_old_conversations.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
from django.core.management.base import BaseCommand
from django.utils import timezone
from chat.models import Conversation
from datetime import timedelta

class Command(BaseCommand):
help = 'Soft-deletes conversations older than 30 days'

def handle(self, *args, **kwargs):
days = 30
cutoff_date = timezone.now() - timedelta(days=days)

deleted_count = Conversation.objects.filter(
created_at__lt=cutoff_date,
deleted_at__isnull=True
).update(deleted_at=timezone.now())

self.stdout.write(
self.style.SUCCESS(f"{deleted_count} conversations soft-deleted.")
)
17 changes: 17 additions & 0 deletions backend/chat/migrations/0002_conversation_summary.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
# Generated by Django 5.0.2 on 2025-07-05 09:04

from django.db import migrations, models


class Migration(migrations.Migration):
dependencies = [
("chat", "0001_initial"),
]

operations = [
migrations.AddField(
model_name="conversation",
name="summary",
field=models.TextField(blank=True, null=True),
),
]
22 changes: 22 additions & 0 deletions backend/chat/migrations/0003_fileupload.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
# Generated by Django 5.0.2 on 2025-07-07 10:47

from django.db import migrations, models


class Migration(migrations.Migration):
dependencies = [
("chat", "0002_conversation_summary"),
]

operations = [
migrations.CreateModel(
name="FileUpload",
fields=[
("id", models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name="ID")),
("file", models.FileField(upload_to="uploads/")),
("file_hash", models.CharField(max_length=64, unique=True)),
("original_name", models.CharField(max_length=255)),
("uploaded_at", models.DateTimeField(auto_now_add=True)),
],
),
]
35 changes: 35 additions & 0 deletions backend/chat/migrations/0004_filelog.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
# Generated by Django 5.0.2 on 2025-07-08 12:45

import django.db.models.deletion
from django.conf import settings
from django.db import migrations, models


class Migration(migrations.Migration):
dependencies = [
("chat", "0003_fileupload"),
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]

operations = [
migrations.CreateModel(
name="FileLog",
fields=[
("id", models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name="ID")),
("file_name", models.CharField(max_length=255)),
(
"action",
models.CharField(
choices=[("UPLOAD", "Upload"), ("DELETE", "Delete"), ("ACCESS", "Access")], max_length=10
),
),
("timestamp", models.DateTimeField(auto_now_add=True)),
(
"user",
models.ForeignKey(
null=True, on_delete=django.db.models.deletion.SET_NULL, to=settings.AUTH_USER_MODEL
),
),
],
),
]
17 changes: 17 additions & 0 deletions backend/chat/migrations/0005_alter_fileupload_file_hash.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
# Generated by Django 5.0.2 on 2025-07-08 13:07

from django.db import migrations, models


class Migration(migrations.Migration):
dependencies = [
("chat", "0004_filelog"),
]

operations = [
migrations.AlterField(
model_name="fileupload",
name="file_hash",
field=models.CharField(max_length=64),
),
]
17 changes: 17 additions & 0 deletions backend/chat/migrations/0006_alter_fileupload_file_hash.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
# Generated by Django 5.0.2 on 2025-07-08 13:10

from django.db import migrations, models


class Migration(migrations.Migration):
dependencies = [
("chat", "0005_alter_fileupload_file_hash"),
]

operations = [
migrations.AlterField(
model_name="fileupload",
name="file_hash",
field=models.CharField(max_length=64, unique=True),
),
]
Loading