Sovereign AI Ecosystem

'Complete Full-Stack AI Persona Generator: Django REST API + React Frontend [post] deterministic

Comprehensive tutorial for building a sophisticated full-stack application

DjangoReactAIOllamaLLMPersonaTutorialPythonTypeScriptREST APIFull-StackWeb Development

![Image](/images/ComfyUI_00190_.png)

Building a Full-Stack Application with Django and React: A Step-by-Step Guide

In this comprehensive guide, we'll walk through the process of building a full-stack application using Django for the backend and React for the frontend. The application allows users to upload a writing sample, analyzes it using an AI language model, and generates blog posts in the style of the uploaded sample.

GitHub Repository: [kliewerdaniel/Django-React-Ollama-Integration](https://github.com/kliewerdaniel/Django-React-Ollama-Integration)

Introduction

This guide aims to help you build a full-stack application that:

  • **Backend (Django):**
  • - Allows users to upload a writing sample.
  • - Analyzes the writing sample using an AI language model.
  • - Stores the analysis and allows generating new content based on the analysis.
  • **Frontend (React):**
  • - Provides a user interface to upload writing samples.
  • - Displays a list of saved personas (analysis results).
  • - Allows generating and viewing blog posts in the style of the uploaded samples.

---

Setting Up the Backend with Django

Creating a Django Project

First, ensure you have Python and Django installed. Create a new Django project and application:

bash django-admin startproject backend cd backend python manage.py startapp core

Configuring Settings

Update the backend/settings.py file to include the necessary configurations:

  • Add rest_framework, core, and corsheaders to INSTALLED_APPS.
  • Configure middleware to include CorsMiddleware.
  • Set up CORS_ALLOWED_ORIGINS to allow your frontend to communicate with the backend.

```python # backend/settings.py

INSTALLED_APPS = [ # ... 'rest_framework', 'core', 'corsheaders', ]

MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', # ... ]

CORS_ALLOWED_ORIGINS = [ 'http://localhost:3000', # Frontend URL ] ```

Defining Models

Create models for Persona and BlogPost in core/models.py:

```python # core/models.py

from django.db import models

class Persona(models.Model): name = models.CharField(max_length=100) data = models.JSONField()

def __str__(self): return self.name

class BlogPost(models.Model): persona = models.ForeignKey(Persona, on_delete=models.CASCADE, related_name='blog_posts') title = models.CharField(max_length=200, blank=True, null=True) content = models.TextField() created_at = models.DateTimeField(auto_now_add=True)

def __str__(self): return self.title or f"BlogPost {self.id}" ```

Apply the migrations:

bash python manage.py makemigrations python manage.py migrate

Creating Serializers

Define serializers to convert model instances to JSON and vice versa in core/serializers.py:

```python # core/serializers.py

from rest_framework import serializers from .models import Persona, BlogPost from .utils import analyze_writing_sample import logging

logger = logging.getLogger(__name__)

class PersonaSerializer(serializers.ModelSerializer): writing_sample = serializers.CharField(write_only=True)

class Meta: model = Persona fields = ['id', 'name', 'writing_sample', 'data'] read_only_fields = ['id', 'data']

def create(self, validated_data): writing_sample = validated_data.pop('writing_sample') logger.debug(f"Writing sample received: {writing_sample[:100]}...") analyzed_data = analyze_writing_sample(writing_sample) logger.debug(f"Analyzed data: {analyzed_data}") if not analyzed_data: logger.error("Failed to analyze the writing sample.") raise serializers.ValidationError({"writing_sample": "Analysis failed."}) validated_data['data'] = analyzed_data return Persona.objects.create(**validated_data)

class BlogPostSerializer(serializers.ModelSerializer): persona = serializers.StringRelatedField()

class Meta: model = BlogPost fields = ['id', 'persona', 'title', 'content', 'created_at'] ```

Writing Utility Functions

Create utility functions in core/utils.py to interact with the AI language model and process responses:

```python # core/utils.py

import logging import requests import json import re from decouple import config

logger = logging.getLogger(__name__) OLLAMA_API_URL = config('OLLAMA_API_URL', default='http://localhost:11434/api/generate')

def extract_json(response_text): decoder = json.JSONDecoder() pos = 0 while pos < len(response_text): try: obj, pos = decoder.raw_decode(response_text, pos) return obj except json.JSONDecodeError: pos += 1 return None

def analyze_writing_sample(writing_sample): encoding_prompt = f''' Please analyze the writing style and personality of the given writing sample. Provide a detailed assessment of their characteristics using the following template. Rate each applicable characteristic on a scale of 1-10 where relevant, or provide a descriptive value. Return the results in a JSON format.

"name": "[Author/Character Name]", "vocabulary_complexity": [1-10], "sentence_structure": "[simple/complex/varied]", "paragraph_organization": "[structured/loose/stream-of-consciousness]", "idiom_usage": [1-10], "metaphor_frequency": [1-10], "simile_frequency": [1-10], "tone": "[formal/informal/academic/conversational/etc.]", "punctuation_style": "[minimal/heavy/unconventional]", "contraction_usage": [1-10], "pronoun_preference": "[first-person/third-person/etc.]", "passive_voice_frequency": [1-10], "rhetorical_question_usage": [1-10], "list_usage_tendency": [1-10], "personal_anecdote_inclusion": [1-10], "pop_culture_reference_frequency": [1-10], "technical_jargon_usage": [1-10], "parenthetical_aside_frequency": [1-10], "humor_sarcasm_usage": [1-10], "emotional_expressiveness": [1-10], "emphatic_device_usage": [1-10], "quotation_frequency": [1-10], "analogy_usage": [1-10], "sensory_detail_inclusion": [1-10], "onomatopoeia_usage": [1-10], "alliteration_frequency": [1-10], "word_length_preference": "[short/long/varied]", "foreign_phrase_usage": [1-10], "rhetorical_device_usage": [1-10], "statistical_data_usage": [1-10], "personal_opinion_inclusion": [1-10], "transition_usage": [1-10], "reader_question_frequency": [1-10], "imperative_sentence_usage": [1-10], "dialogue_inclusion": [1-10], "regional_dialect_usage": [1-10], "hedging_language_frequency": [1-10], "language_abstraction": "[concrete/abstract/mixed]", "personal_belief_inclusion": [1-10], "repetition_usage": [1-10], "subordinate_clause_frequency": [1-10], "verb_type_preference": "[active/stative/mixed]", "sensory_imagery_usage": [1-10], "symbolism_usage": [1-10], "digression_frequency": [1-10], "formality_level": [1-10], "reflection_inclusion": [1-10], "irony_usage": [1-10], "neologism_frequency": [1-10], "ellipsis_usage": [1-10], "cultural_reference_inclusion": [1-10], "stream_of_consciousness_usage": [1-10], "openness_to_experience": [1-10], "conscientiousness": [1-10], "extraversion": [1-10], "agreeableness": [1-10], "emotional_stability": [1-10], "dominant_motivations": "[achievement/affiliation/power/etc.]", "core_values": "[integrity/freedom/knowledge/etc.]", "decision_making_style": "[analytical/intuitive/spontaneous/etc.]", "empathy_level": [1-10], "self_confidence": [1-10], "risk_taking_tendency": [1-10], "idealism_vs_realism": "[idealistic/realistic/mixed]", "conflict_resolution_style": "[assertive/collaborative/avoidant/etc.]", "relationship_orientation": "[independent/communal/mixed]", "emotional_response_tendency": "[calm/reactive/intense]", "creativity_level": [1-10], "age": "[age or age range]", "gender": "[gender]", "education_level": "[highest level of education]", "professional_background": "[brief description]", "cultural_background": "[brief description]", "primary_language": "[language]", "langua

Sources

DanielKliewer.com blog · source

Related (0)

No recorded relationships.

← all Blog