|
|
|
|
@ -0,0 +1,528 @@
|
|
|
|
|
import json
|
|
|
|
|
import logging
|
|
|
|
|
import os
|
|
|
|
|
import uuid
|
|
|
|
|
|
|
|
|
|
import openai
|
|
|
|
|
from openai.error import OpenAIError
|
|
|
|
|
from django.conf import settings
|
|
|
|
|
from django.core.paginator import Paginator
|
|
|
|
|
# 新增(第7行):导入JsonResponse用于API响应
|
|
|
|
|
from django.http import HttpResponse, HttpResponseForbidden, JsonResponse
|
|
|
|
|
from django.shortcuts import get_object_or_404
|
|
|
|
|
from django.shortcuts import render
|
|
|
|
|
from django.templatetags.static import static
|
|
|
|
|
from django.utils import timezone
|
|
|
|
|
from django.utils.html import strip_tags
|
|
|
|
|
from django.utils.translation import gettext_lazy as _
|
|
|
|
|
from django.views.decorators.csrf import csrf_exempt
|
|
|
|
|
from django.views.decorators.http import require_POST
|
|
|
|
|
from django.views.generic.detail import DetailView
|
|
|
|
|
from django.views.generic.list import ListView
|
|
|
|
|
from haystack.views import SearchView
|
|
|
|
|
|
|
|
|
|
from blog.models import Article, Category, LinkShowType, Links, Tag
|
|
|
|
|
from comments.forms import CommentForm
|
|
|
|
|
from djangoblog.plugin_manage import hooks
|
|
|
|
|
from djangoblog.plugin_manage.hook_constants import ARTICLE_CONTENT_HOOK_NAME
|
|
|
|
|
from djangoblog.utils import cache, get_blog_setting, get_sha256
|
|
|
|
|
# 新增(第23-24行):导入标签推荐模块
|
|
|
|
|
from .tag_recommender import recommend_tags_by_content
|
|
|
|
|
|
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
class ArticleListView(ListView):
|
|
|
|
|
# template_name属性用于指定使用哪个模板进行渲染
|
|
|
|
|
template_name = 'blog/article_index.html'
|
|
|
|
|
|
|
|
|
|
# context_object_name属性用于给上下文变量取名(在模板中使用该名字)
|
|
|
|
|
context_object_name = 'article_list'
|
|
|
|
|
|
|
|
|
|
# 页面类型,分类目录或标签列表等
|
|
|
|
|
page_type = ''
|
|
|
|
|
paginate_by = settings.PAGINATE_BY
|
|
|
|
|
page_kwarg = 'page'
|
|
|
|
|
link_type = LinkShowType.L
|
|
|
|
|
|
|
|
|
|
def get_view_cache_key(self):
|
|
|
|
|
return self.request.get['pages']
|
|
|
|
|
|
|
|
|
|
@property
|
|
|
|
|
def page_number(self):
|
|
|
|
|
page_kwarg = self.page_kwarg
|
|
|
|
|
page = self.kwargs.get(
|
|
|
|
|
page_kwarg) or self.request.GET.get(page_kwarg) or 1
|
|
|
|
|
return page
|
|
|
|
|
|
|
|
|
|
def get_queryset_cache_key(self):
|
|
|
|
|
"""
|
|
|
|
|
子类重写.获得queryset的缓存key
|
|
|
|
|
"""
|
|
|
|
|
raise NotImplementedError()
|
|
|
|
|
|
|
|
|
|
def get_queryset_data(self):
|
|
|
|
|
"""
|
|
|
|
|
子类重写.获取queryset的数据
|
|
|
|
|
"""
|
|
|
|
|
raise NotImplementedError()
|
|
|
|
|
|
|
|
|
|
def get_queryset_from_cache(self, cache_key):
|
|
|
|
|
'''
|
|
|
|
|
缓存页面数据
|
|
|
|
|
:param cache_key: 缓存key
|
|
|
|
|
:return:
|
|
|
|
|
'''
|
|
|
|
|
value = cache.get(cache_key)
|
|
|
|
|
if value:
|
|
|
|
|
logger.info('get view cache.key:{key}'.format(key=cache_key))
|
|
|
|
|
return value
|
|
|
|
|
else:
|
|
|
|
|
article_list = self.get_queryset_data()
|
|
|
|
|
cache.set(cache_key, article_list)
|
|
|
|
|
logger.info('set view cache.key:{key}'.format(key=cache_key))
|
|
|
|
|
return article_list
|
|
|
|
|
|
|
|
|
|
def get_queryset(self):
|
|
|
|
|
'''
|
|
|
|
|
重写默认,从缓存获取数据
|
|
|
|
|
:return:
|
|
|
|
|
'''
|
|
|
|
|
key = self.get_queryset_cache_key()
|
|
|
|
|
value = self.get_queryset_from_cache(key)
|
|
|
|
|
return value
|
|
|
|
|
|
|
|
|
|
def get_context_data(self, **kwargs):
|
|
|
|
|
kwargs['linktype'] = self.link_type
|
|
|
|
|
return super(ArticleListView, self).get_context_data(**kwargs)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
class IndexView(ArticleListView):
|
|
|
|
|
'''
|
|
|
|
|
首页
|
|
|
|
|
'''
|
|
|
|
|
# 友情链接类型
|
|
|
|
|
link_type = LinkShowType.I
|
|
|
|
|
|
|
|
|
|
def get_queryset_data(self):
|
|
|
|
|
article_list = Article.objects.filter(type='a', status='p')
|
|
|
|
|
return article_list
|
|
|
|
|
|
|
|
|
|
def get_queryset_cache_key(self):
|
|
|
|
|
cache_key = 'index_{page}'.format(page=self.page_number)
|
|
|
|
|
return cache_key
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
class ArticleDetailView(DetailView):
|
|
|
|
|
'''
|
|
|
|
|
文章详情页面
|
|
|
|
|
'''
|
|
|
|
|
template_name = 'blog/article_detail.html'
|
|
|
|
|
model = Article
|
|
|
|
|
pk_url_kwarg = 'article_id'
|
|
|
|
|
context_object_name = "article"
|
|
|
|
|
|
|
|
|
|
def get_context_data(self, **kwargs):
|
|
|
|
|
comment_form = CommentForm()
|
|
|
|
|
|
|
|
|
|
article_comments = self.object.comment_list()
|
|
|
|
|
|
|
|
|
|
# 新增(第122-123行):获取排序方式,默认为按时间倒序
|
|
|
|
|
sort_by = self.request.GET.get('comment_sort', 'time_desc')
|
|
|
|
|
parent_comments = article_comments.filter(parent_comment=None)
|
|
|
|
|
|
|
|
|
|
# 新增(第126-134行):根据排序方式排序(支持按时间、点赞数排序)
|
|
|
|
|
if sort_by == 'time_asc':
|
|
|
|
|
parent_comments = parent_comments.order_by('creation_time')
|
|
|
|
|
elif sort_by == 'like_desc':
|
|
|
|
|
parent_comments = parent_comments.order_by('-like_count', '-creation_time')
|
|
|
|
|
elif sort_by == 'like_asc':
|
|
|
|
|
parent_comments = parent_comments.order_by('like_count', 'creation_time')
|
|
|
|
|
else: # time_desc (默认)
|
|
|
|
|
parent_comments = parent_comments.order_by('-creation_time')
|
|
|
|
|
|
|
|
|
|
blog_setting = get_blog_setting()
|
|
|
|
|
paginator = Paginator(parent_comments, blog_setting.article_comment_count)
|
|
|
|
|
page = self.request.GET.get('comment_page', '1')
|
|
|
|
|
if not page.isnumeric():
|
|
|
|
|
page = 1
|
|
|
|
|
else:
|
|
|
|
|
page = int(page)
|
|
|
|
|
if page < 1:
|
|
|
|
|
page = 1
|
|
|
|
|
if page > paginator.num_pages:
|
|
|
|
|
page = paginator.num_pages
|
|
|
|
|
|
|
|
|
|
p_comments = paginator.page(page)
|
|
|
|
|
next_page = p_comments.next_page_number() if p_comments.has_next() else None
|
|
|
|
|
prev_page = p_comments.previous_page_number() if p_comments.has_previous() else None
|
|
|
|
|
|
|
|
|
|
# 新增(第152-161行):构建URL时保留排序参数
|
|
|
|
|
base_url = self.object.get_absolute_url()
|
|
|
|
|
sort_param = f'&comment_sort={sort_by}' if sort_by != 'time_desc' else ''
|
|
|
|
|
|
|
|
|
|
if next_page:
|
|
|
|
|
kwargs[
|
|
|
|
|
'comment_next_page_url'] = base_url + f'?comment_page={next_page}{sort_param}#commentlist-container'
|
|
|
|
|
if prev_page:
|
|
|
|
|
kwargs[
|
|
|
|
|
'comment_prev_page_url'] = base_url + f'?comment_page={prev_page}{sort_param}#commentlist-container'
|
|
|
|
|
kwargs['form'] = comment_form
|
|
|
|
|
kwargs['article_comments'] = article_comments
|
|
|
|
|
kwargs['p_comments'] = p_comments
|
|
|
|
|
kwargs['comment_count'] = len(
|
|
|
|
|
article_comments) if article_comments else 0
|
|
|
|
|
# 新增(第167行):传递排序参数到模板
|
|
|
|
|
kwargs['comment_sort'] = sort_by
|
|
|
|
|
|
|
|
|
|
kwargs['next_article'] = self.object.next_article
|
|
|
|
|
kwargs['prev_article'] = self.object.prev_article
|
|
|
|
|
|
|
|
|
|
context = super(ArticleDetailView, self).get_context_data(**kwargs)
|
|
|
|
|
article = self.object
|
|
|
|
|
# Action Hook, 通知插件"文章详情已获取"
|
|
|
|
|
hooks.run_action('after_article_body_get', article=article, request=self.request)
|
|
|
|
|
# # Filter Hook, 允许插件修改文章正文
|
|
|
|
|
article.body = hooks.apply_filters(ARTICLE_CONTENT_HOOK_NAME, article.body, article=article,
|
|
|
|
|
request=self.request)
|
|
|
|
|
|
|
|
|
|
return context
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
class CategoryDetailView(ArticleListView):
|
|
|
|
|
'''
|
|
|
|
|
分类目录列表
|
|
|
|
|
'''
|
|
|
|
|
page_type = "分类目录归档"
|
|
|
|
|
|
|
|
|
|
def get_queryset_data(self):
|
|
|
|
|
slug = self.kwargs['category_name']
|
|
|
|
|
category = get_object_or_404(Category, slug=slug)
|
|
|
|
|
|
|
|
|
|
categoryname = category.name
|
|
|
|
|
self.categoryname = categoryname
|
|
|
|
|
categorynames = list(
|
|
|
|
|
map(lambda c: c.name, category.get_sub_categorys()))
|
|
|
|
|
article_list = Article.objects.filter(
|
|
|
|
|
category__name__in=categorynames, status='p')
|
|
|
|
|
return article_list
|
|
|
|
|
|
|
|
|
|
def get_queryset_cache_key(self):
|
|
|
|
|
slug = self.kwargs['category_name']
|
|
|
|
|
category = get_object_or_404(Category, slug=slug)
|
|
|
|
|
categoryname = category.name
|
|
|
|
|
self.categoryname = categoryname
|
|
|
|
|
cache_key = 'category_list_{categoryname}_{page}'.format(
|
|
|
|
|
categoryname=categoryname, page=self.page_number)
|
|
|
|
|
return cache_key
|
|
|
|
|
|
|
|
|
|
def get_context_data(self, **kwargs):
|
|
|
|
|
|
|
|
|
|
categoryname = self.categoryname
|
|
|
|
|
try:
|
|
|
|
|
categoryname = categoryname.split('/')[-1]
|
|
|
|
|
except BaseException:
|
|
|
|
|
pass
|
|
|
|
|
kwargs['page_type'] = CategoryDetailView.page_type
|
|
|
|
|
kwargs['tag_name'] = categoryname
|
|
|
|
|
return super(CategoryDetailView, self).get_context_data(**kwargs)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
class AuthorDetailView(ArticleListView):
|
|
|
|
|
'''
|
|
|
|
|
作者详情页
|
|
|
|
|
'''
|
|
|
|
|
page_type = '作者文章归档'
|
|
|
|
|
|
|
|
|
|
def get_queryset_cache_key(self):
|
|
|
|
|
from uuslug import slugify
|
|
|
|
|
author_name = slugify(self.kwargs['author_name'])
|
|
|
|
|
cache_key = 'author_{author_name}_{page}'.format(
|
|
|
|
|
author_name=author_name, page=self.page_number)
|
|
|
|
|
return cache_key
|
|
|
|
|
|
|
|
|
|
def get_queryset_data(self):
|
|
|
|
|
author_name = self.kwargs['author_name']
|
|
|
|
|
article_list = Article.objects.filter(
|
|
|
|
|
author__username=author_name, type='a', status='p')
|
|
|
|
|
return article_list
|
|
|
|
|
|
|
|
|
|
def get_context_data(self, **kwargs):
|
|
|
|
|
author_name = self.kwargs['author_name']
|
|
|
|
|
kwargs['page_type'] = AuthorDetailView.page_type
|
|
|
|
|
kwargs['tag_name'] = author_name
|
|
|
|
|
return super(AuthorDetailView, self).get_context_data(**kwargs)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
class TagDetailView(ArticleListView):
|
|
|
|
|
'''
|
|
|
|
|
标签列表页面
|
|
|
|
|
'''
|
|
|
|
|
page_type = '分类标签归档'
|
|
|
|
|
|
|
|
|
|
def get_queryset_data(self):
|
|
|
|
|
slug = self.kwargs['tag_name']
|
|
|
|
|
tag = get_object_or_404(Tag, slug=slug)
|
|
|
|
|
tag_name = tag.name
|
|
|
|
|
self.name = tag_name
|
|
|
|
|
article_list = Article.objects.filter(
|
|
|
|
|
tags__name=tag_name, type='a', status='p')
|
|
|
|
|
return article_list
|
|
|
|
|
|
|
|
|
|
def get_queryset_cache_key(self):
|
|
|
|
|
slug = self.kwargs['tag_name']
|
|
|
|
|
tag = get_object_or_404(Tag, slug=slug)
|
|
|
|
|
tag_name = tag.name
|
|
|
|
|
self.name = tag_name
|
|
|
|
|
cache_key = 'tag_{tag_name}_{page}'.format(
|
|
|
|
|
tag_name=tag_name, page=self.page_number)
|
|
|
|
|
return cache_key
|
|
|
|
|
|
|
|
|
|
def get_context_data(self, **kwargs):
|
|
|
|
|
# tag_name = self.kwargs['tag_name']
|
|
|
|
|
tag_name = self.name
|
|
|
|
|
kwargs['page_type'] = TagDetailView.page_type
|
|
|
|
|
kwargs['tag_name'] = tag_name
|
|
|
|
|
return super(TagDetailView, self).get_context_data(**kwargs)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
class ArchivesView(ArticleListView):
|
|
|
|
|
'''
|
|
|
|
|
文章归档页面
|
|
|
|
|
'''
|
|
|
|
|
page_type = '文章归档'
|
|
|
|
|
paginate_by = None
|
|
|
|
|
page_kwarg = None
|
|
|
|
|
template_name = 'blog/article_archives.html'
|
|
|
|
|
|
|
|
|
|
def get_queryset_data(self):
|
|
|
|
|
return Article.objects.filter(status='p').all()
|
|
|
|
|
|
|
|
|
|
def get_queryset_cache_key(self):
|
|
|
|
|
cache_key = 'archives'
|
|
|
|
|
return cache_key
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
class LinkListView(ListView):
|
|
|
|
|
model = Links
|
|
|
|
|
template_name = 'blog/links_list.html'
|
|
|
|
|
|
|
|
|
|
def get_queryset(self):
|
|
|
|
|
return Links.objects.filter(is_enable=True)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
class EsSearchView(SearchView):
|
|
|
|
|
def get_context(self):
|
|
|
|
|
paginator, page = self.build_page()
|
|
|
|
|
context = {
|
|
|
|
|
"query": self.query,
|
|
|
|
|
"form": self.form,
|
|
|
|
|
"page": page,
|
|
|
|
|
"paginator": paginator,
|
|
|
|
|
"suggestion": None,
|
|
|
|
|
}
|
|
|
|
|
if hasattr(self.results, "query") and self.results.query.backend.include_spelling:
|
|
|
|
|
context["suggestion"] = self.results.query.get_spelling_suggestion()
|
|
|
|
|
context.update(self.extra_context())
|
|
|
|
|
|
|
|
|
|
return context
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
@csrf_exempt
|
|
|
|
|
def fileupload(request):
|
|
|
|
|
"""
|
|
|
|
|
该方法需自己写调用端来上传图片,该方法仅提供图床功能
|
|
|
|
|
:param request:
|
|
|
|
|
:return:
|
|
|
|
|
"""
|
|
|
|
|
if request.method == 'POST':
|
|
|
|
|
sign = request.GET.get('sign', None)
|
|
|
|
|
if not sign:
|
|
|
|
|
return HttpResponseForbidden()
|
|
|
|
|
if not sign == get_sha256(get_sha256(settings.SECRET_KEY)):
|
|
|
|
|
return HttpResponseForbidden()
|
|
|
|
|
response = []
|
|
|
|
|
for filename in request.FILES:
|
|
|
|
|
timestr = timezone.now().strftime('%Y/%m/%d')
|
|
|
|
|
imgextensions = ['jpg', 'png', 'jpeg', 'bmp']
|
|
|
|
|
fname = u''.join(str(filename))
|
|
|
|
|
isimage = len([i for i in imgextensions if fname.find(i) >= 0]) > 0
|
|
|
|
|
base_dir = os.path.join(settings.STATICFILES, "files" if not isimage else "image", timestr)
|
|
|
|
|
if not os.path.exists(base_dir):
|
|
|
|
|
os.makedirs(base_dir)
|
|
|
|
|
savepath = os.path.normpath(os.path.join(base_dir, f"{uuid.uuid4().hex}{os.path.splitext(filename)[-1]}"))
|
|
|
|
|
if not savepath.startswith(base_dir):
|
|
|
|
|
return HttpResponse("only for post")
|
|
|
|
|
with open(savepath, 'wb+') as wfile:
|
|
|
|
|
for chunk in request.FILES[filename].chunks():
|
|
|
|
|
wfile.write(chunk)
|
|
|
|
|
if isimage:
|
|
|
|
|
from PIL import Image
|
|
|
|
|
image = Image.open(savepath)
|
|
|
|
|
image.save(savepath, quality=20, optimize=True)
|
|
|
|
|
url = static(savepath)
|
|
|
|
|
response.append(url)
|
|
|
|
|
return HttpResponse(response)
|
|
|
|
|
|
|
|
|
|
else:
|
|
|
|
|
return HttpResponse("only for post")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def page_not_found_view(
|
|
|
|
|
request,
|
|
|
|
|
exception,
|
|
|
|
|
template_name='blog/error_page.html'):
|
|
|
|
|
if exception:
|
|
|
|
|
logger.error(exception)
|
|
|
|
|
url = request.get_full_path()
|
|
|
|
|
return render(request,
|
|
|
|
|
template_name,
|
|
|
|
|
{'message': _('Sorry, the page you requested is not found, please click the home page to see other?'),
|
|
|
|
|
'statuscode': '404'},
|
|
|
|
|
status=404)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def server_error_view(request, template_name='blog/error_page.html'):
|
|
|
|
|
return render(request,
|
|
|
|
|
template_name,
|
|
|
|
|
{'message': _('Sorry, the server is busy, please click the home page to see other?'),
|
|
|
|
|
'statuscode': '500'},
|
|
|
|
|
status=500)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def permission_denied_view(
|
|
|
|
|
request,
|
|
|
|
|
exception,
|
|
|
|
|
template_name='blog/error_page.html'):
|
|
|
|
|
if exception:
|
|
|
|
|
logger.error(exception)
|
|
|
|
|
return render(
|
|
|
|
|
request, template_name, {
|
|
|
|
|
'message': _('Sorry, you do not have permission to access this page?'),
|
|
|
|
|
'statuscode': '403'}, status=403)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def clean_cache_view(request):
|
|
|
|
|
cache.clear()
|
|
|
|
|
return HttpResponse('ok')
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
# 新增(第404-467行):标签推荐API视图
|
|
|
|
|
@csrf_exempt
|
|
|
|
|
def recommend_tags_view(request):
|
|
|
|
|
"""
|
|
|
|
|
基于文章标题、正文、分类和作者历史标签推荐标签
|
|
|
|
|
接受POST请求,参数:
|
|
|
|
|
- title: 文章标题
|
|
|
|
|
- body: 文章正文
|
|
|
|
|
- category_id: 分类ID(可选)
|
|
|
|
|
- author_id: 作者ID(可选)
|
|
|
|
|
- max_recommendations: 最大推荐数量(可选,默认10)
|
|
|
|
|
"""
|
|
|
|
|
if request.method != 'POST':
|
|
|
|
|
return JsonResponse({'error': 'Only POST method allowed'}, status=405)
|
|
|
|
|
|
|
|
|
|
try:
|
|
|
|
|
title = request.POST.get('title', '')
|
|
|
|
|
body = request.POST.get('body', '')
|
|
|
|
|
category_id = request.POST.get('category_id')
|
|
|
|
|
author_id = request.POST.get('author_id')
|
|
|
|
|
max_recommendations = int(request.POST.get('max_recommendations', 10))
|
|
|
|
|
|
|
|
|
|
# 验证必需参数
|
|
|
|
|
if not title and not body:
|
|
|
|
|
return JsonResponse({'error': 'Title or body is required'}, status=400)
|
|
|
|
|
|
|
|
|
|
# 获取分类和作者对象
|
|
|
|
|
category = None
|
|
|
|
|
if category_id:
|
|
|
|
|
try:
|
|
|
|
|
category = Category.objects.get(pk=category_id)
|
|
|
|
|
except Category.DoesNotExist:
|
|
|
|
|
pass
|
|
|
|
|
|
|
|
|
|
author = None
|
|
|
|
|
if author_id:
|
|
|
|
|
try:
|
|
|
|
|
from accounts.models import BlogUser
|
|
|
|
|
author = BlogUser.objects.get(pk=author_id)
|
|
|
|
|
except BlogUser.DoesNotExist:
|
|
|
|
|
pass
|
|
|
|
|
|
|
|
|
|
# 获取推荐标签
|
|
|
|
|
recommendations = recommend_tags_by_content(
|
|
|
|
|
title=title,
|
|
|
|
|
body=body,
|
|
|
|
|
category=category,
|
|
|
|
|
author=author,
|
|
|
|
|
max_recommendations=max_recommendations
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
return JsonResponse({
|
|
|
|
|
'success': True,
|
|
|
|
|
'recommendations': recommendations,
|
|
|
|
|
'count': len(recommendations)
|
|
|
|
|
})
|
|
|
|
|
|
|
|
|
|
except Exception as e:
|
|
|
|
|
logger.error(f"Error in recommend_tags_view: {str(e)}", exc_info=True)
|
|
|
|
|
return JsonResponse({
|
|
|
|
|
'error': 'Internal server error',
|
|
|
|
|
'message': str(e)
|
|
|
|
|
}, status=500)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
# 功能:文章AI问答接口(行469-526)
|
|
|
|
|
@require_POST
|
|
|
|
|
def article_ai_answer_view(request, article_id):
|
|
|
|
|
if not settings.OPENAI_API_KEY:
|
|
|
|
|
return JsonResponse({'error': _('AI assistant is not configured yet.')}, status=503)
|
|
|
|
|
|
|
|
|
|
try:
|
|
|
|
|
payload = json.loads(request.body.decode('utf-8'))
|
|
|
|
|
except (ValueError, json.JSONDecodeError):
|
|
|
|
|
payload = {}
|
|
|
|
|
|
|
|
|
|
question = (payload.get('question') or '').strip()
|
|
|
|
|
if not question:
|
|
|
|
|
return JsonResponse({'error': _('Please enter a question.')}, status=400)
|
|
|
|
|
if len(question) > 500:
|
|
|
|
|
return JsonResponse({'error': _('Question is too long, please be concise.')}, status=400)
|
|
|
|
|
|
|
|
|
|
article = get_object_or_404(Article, pk=article_id, status='p')
|
|
|
|
|
content_parts = [
|
|
|
|
|
_('Title: %(title)s') % {'title': article.title},
|
|
|
|
|
strip_tags(getattr(article, 'summary', '') or '')[:800],
|
|
|
|
|
strip_tags(article.body or '')[:4000],
|
|
|
|
|
]
|
|
|
|
|
context_text = '\n\n'.join(filter(None, content_parts))
|
|
|
|
|
|
|
|
|
|
openai.api_key = settings.OPENAI_API_KEY
|
|
|
|
|
messages = [
|
|
|
|
|
{
|
|
|
|
|
'role': 'system',
|
|
|
|
|
'content': _('You are an AI assistant embedded in a blog article page. Answer questions strictly based on '
|
|
|
|
|
'the provided article content. If the answer cannot be found in the article, clearly say that '
|
|
|
|
|
'you do not know. Provide concise answers in the language of the question.')
|
|
|
|
|
},
|
|
|
|
|
{
|
|
|
|
|
'role': 'user',
|
|
|
|
|
'content': _('Article Content:\n%(content)s\n\nQuestion: %(question)s') % {
|
|
|
|
|
'content': context_text,
|
|
|
|
|
'question': question
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
]
|
|
|
|
|
try:
|
|
|
|
|
response = openai.ChatCompletion.create(
|
|
|
|
|
model=getattr(settings, 'OPENAI_CHAT_MODEL', 'gpt-3.5-turbo'),
|
|
|
|
|
messages=messages,
|
|
|
|
|
max_tokens=getattr(settings, 'OPENAI_MAX_TOKENS', 512),
|
|
|
|
|
temperature=0.3,
|
|
|
|
|
timeout=getattr(settings, 'OPENAI_TIMEOUT', 30),
|
|
|
|
|
)
|
|
|
|
|
answer = response['choices'][0]['message']['content'].strip()
|
|
|
|
|
return JsonResponse({'answer': answer})
|
|
|
|
|
except OpenAIError as exc:
|
|
|
|
|
logger.error('article_ai_answer_view error: %s', exc, exc_info=True)
|
|
|
|
|
return JsonResponse({'error': _('AI service is unavailable, please try again later.')}, status=502)
|