35808-vm/core/views.py
Flatlogic Bot fad3944722 Final 100
2025-11-18 03:33:52 +00:00

68 lines
3.3 KiB
Python

from django.shortcuts import render
from ai.local_ai_api import LocalAIApi
import logging
logger = logging.getLogger(__name__)
def home(request):
"""
Render the landing page and handle the content generation form.
"""
context = {}
if request.method == 'POST':
topic = request.POST.get('topic', '').strip()
form_type = request.POST.get('form_type', 'website') # Default to website
context['topic'] = topic
context['form_type'] = form_type
if not topic:
context['error'] = 'Please enter a topic.'
else:
try:
if form_type == 'website':
prompt = {
"input": [
{"role": "system", "content": "You are an expert SEO content strategist. Generate a compelling blog post title and a list of relevant SEO keywords for a given topic. Return the result as a JSON object with two keys: 'title' and 'keywords'. The 'keywords' should be a list of strings."},
{"role": "user", "content": f"The topic is: {topic}"},
],
"text": {"format": {"type": "json_object"}},
}
response = LocalAIApi.create_response(prompt)
if response.get("success"):
payload = LocalAIApi.decode_json_from_response(response)
if payload:
context['results'] = payload
else:
context['error'] = 'Failed to generate content. The AI response was not valid JSON.'
else:
logger.warning("AI error: %s", response.get("error"))
context['error'] = 'Failed to generate content due to an AI error.'
elif form_type == 'youtube':
prompt = {
"input": [
{"role": "system", "content": "You are a YouTube content expert. Generate a catchy title, a list of relevant keywords, and a list of hashtags for a given video topic. Return the result as a JSON object with three keys: 'title', 'keywords', and 'hashtags'. 'keywords' and 'hashtags' should be lists of strings."},
{"role": "user", "content": f"The topic is: {topic}"},
],
"text": {"format": {"type": "json_object"}},
}
response = LocalAIApi.create_response(prompt)
if response.get("success"):
payload = LocalAIApi.decode_json_from_response(response)
if payload:
context['youtube_results'] = payload
else:
context['error'] = 'Failed to generate content. The AI response was not valid JSON.'
else:
logger.warning("AI error: %s", response.get("error"))
context['error'] = 'Failed to generate content due to an AI error.'
except Exception as e:
logger.error("An unexpected error occurred: %s", e)
context['error'] = 'An unexpected error occurred.'
return render(request, "core/index.html", context)