Skip to content

Dublin City Center Pub Finder #110

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
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
Original file line number Diff line number Diff line change
Expand Up @@ -21241,4 +21241,4 @@
]
}
]
}
}
6 changes: 3 additions & 3 deletions apps/django_langchain_voyageai/finder/README.md
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
# Django MongoDB Backend - Project Template

This is a Django project starter template for the Django MongoDB Backend.
In order to use it with your version of Django:
In order to use it with your version of Django:

- Find your Django version. To do so from the command line, make sure you
have Django installed and run:
Expand All @@ -14,7 +14,7 @@ django-admin --version
## Create the Django project

From your shell, run the following command to create a new Django project
replacing the `{{ project_name }}` and `{{ version }}` sections.
replacing the `{{ project_name }}` and `{{ version }}` sections.

```bash
django-admin startproject {{ project_name }} --template https://github.com/mongodb-labs/django-mongodb-project/archive/refs/heads/{{ version }}.x.zip
Expand All @@ -25,4 +25,4 @@ the command would look like this:

```bash
django-admin startproject 5_0_example --template https://github.com/mongodb-labs/django-mongodb-project/archive/refs/heads/5.0.x.zip
```
```
3 changes: 0 additions & 3 deletions apps/django_langchain_voyageai/finder/dublinfinder/admin.py
Original file line number Diff line number Diff line change
@@ -1,3 +0,0 @@
from django.contrib import admin

# Register your models here.
4 changes: 2 additions & 2 deletions apps/django_langchain_voyageai/finder/dublinfinder/apps.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,5 +2,5 @@


class DublinfinderConfig(AppConfig):
default_auto_field = 'django_mongodb_backend.fields.ObjectIdAutoField'
name = 'dublinfinder'
default_auto_field = "django_mongodb_backend.fields.ObjectIdAutoField"
name = "dublinfinder"
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
from django.db import models
from django_mongodb_backend.fields import ArrayField, EmbeddedModelField
from django_mongodb_backend.models import EmbeddedModel
from django_mongodb_backend.managers import MongoManager
from django_mongodb_backend.models import EmbeddedModel


# Embedded, so it doesn't have it's own collection.
class DisplayName(EmbeddedModel):
Expand All @@ -25,4 +26,4 @@ class Meta:
managed = False

def __str__(self):
return self.displayName.text
return self.displayName.text
Original file line number Diff line number Diff line change
Expand Up @@ -106,4 +106,3 @@ <h2>Results for "{{ query }}"</h2>

</body>
</html>

3 changes: 0 additions & 3 deletions apps/django_langchain_voyageai/finder/dublinfinder/tests.py
Original file line number Diff line number Diff line change
@@ -1,3 +0,0 @@
from django.test import TestCase

# Create your tests here.
46 changes: 22 additions & 24 deletions apps/django_langchain_voyageai/finder/dublinfinder/views.py
Original file line number Diff line number Diff line change
@@ -1,44 +1,45 @@
import os

from django.shortcuts import render
import os
from dotenv import load_dotenv
from langchain_voyageai.embeddings import VoyageAIEmbeddings
from langchain_mongodb.vectorstores import MongoDBAtlasVectorSearch
from langchain_voyageai.embeddings import VoyageAIEmbeddings

load_dotenv()


def search_places(request):
# Get query from the user.
query = request.GET.get("query", "")
results = []

# Same from our langchain_integration.py file.
if query:
# Use our API keys.
voyage_api_key = os.getenv("VOYAGE_API_KEY")
connection_string = os.getenv("MONGO_URI")
# This is our embeddings object.

# This is our embeddings object.
embeddings = VoyageAIEmbeddings(
voyage_api_key=voyage_api_key,
model="voyage-3-lite"
voyage_api_key=voyage_api_key, model="voyage-3-lite"
)

# This is your `database.collection`.
namespace = "dublinfinder.placesinfo"
# Vector store with our embeddings model.

# Vector store with our embeddings model.
vector_store = MongoDBAtlasVectorSearch.from_connection_string(
connection_string=connection_string,
namespace=namespace,
embedding_key="embedding",
index_name="vector_index",
text_key="reviews",
embedding=embeddings
embedding=embeddings,
)

# Similarity search, LangChain handles embedding the query.
results_with_scores = vector_store.similarity_search_with_score(query, k=3)

# Post-process and make it look pretty.
processed_results = []
maximum_char = 800
Expand All @@ -47,22 +48,19 @@ def search_places(request):
name = doc.metadata.get("displayName", {}).get("text", "Unknown")
address = doc.metadata.get("formattedAddress", "Unknown")
review_text = doc.page_content if doc.page_content else ""

# Refining it so we don't end in the middle of a sentence.
if len(review_text) > maximum_char:
shortened = review_text[:maximum_char]
last_period = shortened.rfind('.')
last_period = shortened.rfind(".")
if last_period != -1:
review = shortened[:last_period+1]

processed_results.append({
"name": name,
"address": address,
"review": review,
"score": score
})

review = shortened[: last_period + 1]

processed_results.append(
{"name": name, "address": address, "review": review, "score": score}
)

results = processed_results

# Template.
return render(request, "search_results.html", {"results": results, "query": query})
2 changes: 1 addition & 1 deletion apps/django_langchain_voyageai/finder/finder/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', 'finder.settings')
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "finder.settings")

application = get_asgi_application()
80 changes: 40 additions & 40 deletions apps/django_langchain_voyageai/finder/finder/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,16 +10,16 @@
https://docs.djangoproject.com/en/4.2/ref/settings/
"""

import django_mongodb_backend
import os
from pathlib import Path

import django_mongodb_backend
from dotenv import load_dotenv

load_dotenv()
connection_string = os.getenv("MONGO_URI")


from pathlib import Path

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

Expand All @@ -28,7 +28,7 @@
# 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-sx&$+jrfc(d!%wmvdh==+(+=57)1mx)fef7)b_bb48jbxqj9!k'
SECRET_KEY = "django-insecure-sx&$+jrfc(d!%wmvdh==+(+=57)1mx)fef7)b_bb48jbxqj9!k"

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

INSTALLED_APPS = [
'dublinfinder.apps.DublinfinderConfig',
'finder.apps.MongoAdminConfig',
'finder.apps.MongoAuthConfig',
'finder.apps.MongoContentTypesConfig',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
"dublinfinder.apps.DublinfinderConfig",
"finder.apps.MongoAdminConfig",
"finder.apps.MongoAuthConfig",
"finder.apps.MongoContentTypesConfig",
"django.contrib.sessions",
"django.contrib.messages",
"django.contrib.staticfiles",
]

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


# Database
Expand All @@ -91,26 +91,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/4.2/topics/i18n/

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

TIME_ZONE = 'UTC'
TIME_ZONE = "UTC"

USE_I18N = True

Expand All @@ -120,15 +120,15 @@
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/4.2/howto/static-files/

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

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

DEFAULT_AUTO_FIELD = 'django_mongodb_backend.fields.ObjectIdAutoField'
DEFAULT_AUTO_FIELD = "django_mongodb_backend.fields.ObjectIdAutoField"

MIGRATION_MODULES = {
'admin': 'mongo_migrations.admin',
'auth': 'mongo_migrations.auth',
'contenttypes': 'mongo_migrations.contenttypes',
"admin": "mongo_migrations.admin",
"auth": "mongo_migrations.auth",
"contenttypes": "mongo_migrations.contenttypes",
}
7 changes: 4 additions & 3 deletions apps/django_langchain_voyageai/finder/finder/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,12 +14,13 @@
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
from dublinfinder import views

urlpatterns = [
path('admin/', admin.site.urls),
path('search/', views.search_places, name='search_places'),
path('', views.search_places, name='search_places')
path("admin/", admin.site.urls),
path("search/", views.search_places, name="search_places"),
path("", views.search_places, name="search_places"),
]
2 changes: 1 addition & 1 deletion apps/django_langchain_voyageai/finder/finder/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', 'finder.settings')
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "finder.settings")

application = get_wsgi_application()
5 changes: 3 additions & 2 deletions apps/django_langchain_voyageai/finder/manage.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
#!/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', 'finder.settings')
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "finder.settings")
try:
from django.core.management import execute_from_command_line
except ImportError as exc:
Expand All @@ -18,5 +19,5 @@ def main():
execute_from_command_line(sys.argv)


if __name__ == '__main__':
if __name__ == "__main__":
main()
Loading
Loading