Skip to content
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

26 implement ai #31

Merged
merged 3 commits into from
Sep 1, 2023
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
2 changes: 1 addition & 1 deletion backend/accounts/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,4 +45,4 @@
# path('allauth/', include('allauth.urls')),

path("~redirect/", view=UserRedirectView.as_view(), name="redirect")
]
]
2 changes: 1 addition & 1 deletion backend/accounts/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -177,7 +177,7 @@ class AdminActivateUserView(generics.GenericAPIView):
serializer_class = EmailVerificationSerializer

def send_activated_account_email(self, user):
email_subject = 'Raspberry-Account activated'
email_subject = 'Learnverse-Account activated'
email_body = render_to_string(
'activated_account.html',
{
Expand Down
3 changes: 1 addition & 2 deletions backend/backend/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -220,5 +220,4 @@


GOOGLE_DRIVE_STORAGE_JSON_KEY_FILE = BASE_DIR / 'google_storage.json'
# GOOGLE_DRIVE_STORAGE_JSON_KEY_FILE_CONTENTS = config("GOOGLE_DRIVE_STORAGE_JSON_KEY_FILE_CONTENTS")

# GOOGLE_DRIVE_STORAGE_JSON_KEY_FILE_CONTENTS = config("GOOGLE_DRIVE_STORAGE_JSON_KEY_FILE_CONTENTS")
1 change: 1 addition & 0 deletions backend/backend/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
path('',include('accounts.urls')),
path('',include('main.urls')),
path('',include('quizapp.urls')),
path('',include('chatbot.urls')),
path('',api_root),
path('api/schema/', SpectacularAPIView.as_view(), name='schema'),
path('api/schema/swagger-ui/', SpectacularSwaggerView.as_view(), name='swagger-ui'),
Expand Down
Empty file added backend/chatbot/__init__.py
Empty file.
3 changes: 3 additions & 0 deletions backend/chatbot/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 backend/chatbot/apps.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
from django.apps import AppConfig


class ChatbotConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
name = 'chatbot'
Empty file.
3 changes: 3 additions & 0 deletions backend/chatbot/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.
21 changes: 21 additions & 0 deletions backend/chatbot/serializers.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
from rest_framework import serializers

class ChatbotSerializer(serializers.Serializer):
COMMAND_CHOICES = (
('define', 'Define'),
('synonyms', 'Synonyms'),
('antonyms', 'Antonyms'),
('wikipedia','Wikipedia'),
('summarize','Summarize'),
# Add other choices here
)
command = serializers.ChoiceField(choices=COMMAND_CHOICES)
input_data = serializers.CharField()

# serializers.py

from rest_framework import serializers

class TranslationSerializer(serializers.Serializer):
target_language = serializers.CharField()
text = serializers.CharField()
3 changes: 3 additions & 0 deletions backend/chatbot/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.
8 changes: 8 additions & 0 deletions backend/chatbot/urls.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
from django.urls import path
from. import views

urlpatterns = [
# path('chatbot/',views.chatbot_view,name='chatbot'),
path('chatbot/',views.ChatbotView.as_view()),
path('translate/', views.TranslationView.as_view(), name='translate-view'),
]
122 changes: 122 additions & 0 deletions backend/chatbot/views.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,122 @@
# views.py
from rest_framework.decorators import api_view
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework import generics
from rest_framework import status
from .serializers import *
from nltk.corpus import wordnet
import wikipedia
import requests
import math
import datetime
import random
import nltk

nltk.download('wordnet')

class ChatbotView(generics.GenericAPIView):
serializer_class = ChatbotSerializer
def post(self, request):
serializer = self.get_serializer(data=request.data)
serializer.is_valid(raise_exception=True)
command = serializer.validated_data['command']
input_data = serializer.validated_data['input_data']
try:
response = process_user_input(command, input_data)
except:
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

return Response({'input_data': input_data, 'response': response}, status=status.HTTP_200_OK)


def process_user_input(command,input_data):
if command == 'define':
response = get_word_meaning(input_data)
elif command == 'synonyms':
response = find_synonyms(input_data)
elif command == 'antonyms':
response = find_antonyms(input_data)
elif command == 'wikipedia':
response = search_wikipedia(input_data)
elif command == 'summarize':
response = text_summary(input_data)
return response



def find_synonyms(word):
synsets = wordnet.synsets(word)
synonyms = set()
for synset in synsets:
for lemma in synset.lemmas():
synonyms.add(lemma.name())
return ', '.join(synonyms)

def find_antonyms(word):
synsets = wordnet.synsets(word)
antonyms = set()
for synset in synsets:
for lemma in synset.lemmas():
for antonym in lemma.antonyms():
antonyms.add(antonym.name())
return ', '.join(antonyms)

def translate_word(word):
api_key = 'YOUR_API_KEY'
target_language = 'fr' # French as an example
response = requests.get(f'https://translation.googleapis.com/language/translate/v2?key={api_key}&q={word}&target={target_language}')
translation = response.json().get('data', {}).get('translations', [{}])[0].get('translatedText', '')
return translation


def search_wikipedia(topic):
try:
summary = wikipedia.summary(topic, sentences=1)
return summary
except wikipedia.exceptions.DisambiguationError:
return f"Multiple meanings found for '{topic}'. Please be more specific."
except wikipedia.exceptions.PageError:
return f"No Wikipedia page found for '{topic}'."

def get_word_meaning(word):
synsets = wordnet.synsets(word)
if synsets:
return synsets[0].definition()
else:
return "Meaning not found."

def text_summary(word):
url = "https://summarize-texts.p.rapidapi.com/pipeline"
payload = {'input':word}
headers = {
"content-type": "application/json",
"X-RapidAPI-Key": "810e4d97dcmsh934985e8b5d5f55p1ec1edjsnaf06bb921da8",
"X-RapidAPI-Host": "summarize-texts.p.rapidapi.com"
}
response = requests.post(url, json=payload, headers=headers)
summary = response.json().get('output')[0].get('text')
return summary





# views.py

from rest_framework import generics, status
from rest_framework.response import Response
from translate import Translator

class TranslationView(generics.CreateAPIView):
serializer_class = TranslationSerializer
def post(self, request, *args, **kwargs):
target_language_name = request.data.get('target_language')
text_to_translate = request.data.get('text')

translator = Translator(to_lang=target_language_name)
translated_text = translator.translate(str(text_to_translate))

return Response({'translated_text': translated_text}, status=status.HTTP_200_OK)


1 change: 1 addition & 0 deletions backend/requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ google-api-python-client==2.97.0
google-auth==1.35.0
google-auth-httplib2==0.1.0
googleapis-common-protos==1.60.0
google-auth-oauthlib==1.0.0
httplib2==0.22.0
idna==3.4
inflection==0.5.1
Expand Down