Skip to content

sAI-2025/Book-analysis-agent

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

7 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation


Book Analysis Chatbot (Django + AI)

Python 3.11 Django REST LLM via Groq Transformer Emotion Model TailwindCSS Hugging Face Spaces MIT License Beta Status

Analyze any book passage with word count, predominant emotion, candidate source books, and a concise summary. Frontend is a modern chat UI; backend is Django REST-style endpoint wiring your NLP modules.

  • Stack: Django, Transformers (emotion), Groq API (LLM), Vanilla JS/Tailwind UI.
  • No DB required (stateless analysis), WhiteNoise for static serving, Docker-compatible.

Features

  • Word count via Python text processing.
  • Emotion detection with a pre-trained transformer.
  • Book candidates and summaries via Groq LLM API.
  • Responsive chat UI with typing indicator and structured result cards.
  • Ready for local dev and Hugging Face Spaces (Docker).

File Structure

c:/Users/chskc/Desktop/no parking/assignment/
└── book_analysis_project/
    ├── .env
    ├── chat/
    │   ├── admin.py
    │   ├── apps.py
    │   ├── migrations/
    │   │   ├── __init__.py
    │   │   └── __pycache__/
    │   │       └── __init__.cpython-311.pyc
    │   ├── models.py
    │   ├── templates/
    │   │   └── chat/
    │   │       └── chat.html
    │   ├── tests.py
    │   ├── urls.py
    │   ├── views.py
    │   ├── __init__.py
    │   └── __pycache__/
    │       ├── admin.cpython-311.pyc
    │       ├── apps.cpython-311.pyc
    │       ├── models.cpython-311.pyc
    │       ├── urls.cpython-311.pyc
    │       ├── views.cpython-311.pyc
    │       └── __init__.cpython-311.pyc
    ├── chatbot_project/
    │   ├── asgi.py
    │   ├── settings.py
    │   ├── urls.py
    │   ├── wsgi.py
    │   ├── __init__.py
    │   └── __pycache__/
    │       ├── settings.cpython-311.pyc
    │       ├── urls.cpython-311.pyc
    │       ├── wsgi.cpython-311.pyc
    │       └── __init__.cpython-311.pyc
    ├── db.sqlite3
    ├── main.py
    ├── manage.py
    ├── modules/
    │   ├── emotion.py
    │   ├── groq_inference.py
    │   ├── utils.py
    │   ├── wordcount.py
    │   └── __pycache__/
    │       ├── emotion.cpython-311.pyc
    │       ├── groq_inference.cpython-311.pyc
    │       └── wordcount.cpython-311.pyc
    ├── README.md
    ├── requirements.txt
    └── staticfiles/
        └── admin/
            ├── css/...
            ├── img/...
            └── js/...
  • chat/: Django app with chat UI template and API endpoints.
  • chatbot_project/: Project settings, URLs, WSGI/ASGI.
  • modules/: Core NLP logic (word count, emotion, Groq inference, utils).
  • staticfiles/: Collected static (auto-generated by collectstatic).
  • .env: Environment variables (GROQ_API_KEY, DEBUG, DJANGO_SECRET_KEY).

Prerequisites

  • Python 3.11+
  • Pip and virtualenv
  • Groq API key (set GROQ_API_KEY in .env)
  • Hugging Face model auto-download enabled on first run

Setup (Local Development)

  1. Create and activate a virtual environment
python -m venv venv
venv\Scripts\activate
  1. Install dependencies
pip install -r requirements.txt
  1. Create a .env file at project root
DJANGO_SECRET_KEY=replace-with-a-random-string
DEBUG=True
GROQ_API_KEY=replace-with-your-groq-key
  1. Run Django server
python manage.py runserver
  1. Open the app

Usage

  • Paste a passage in the chat box and click Send.
  • Backend calls:
    • modules/wordcount.py for count
    • modules/emotion.py for emotion detection
    • modules/groq_inference.py for candidate books and a 2–3 sentence summary
  • Results render as a structured card in the chat.

Environment Variables

  • DJANGO_SECRET_KEY: any long random string.
  • DEBUG: True for local, False for production.
  • GROQ_API_KEY: your Groq token for LLM inference.

Store them in .env locally; set them via Space Variables on Hugging Face.


Run Tests

If you add tests later under chat/tests.py:

pytest
# or
python manage.py test

Productivity and Professional Practices

  • Load the transformer model once at startup for consistent latency.
  • Use truncation and no_grad for CPU efficiency in emotion.py.
  • Keep modules independent and side-effect free for easy testing.
  • Add pre-commit hooks (black, isort, flake8) for consistent code style.
  • Use feature branches and pull requests for changes.
  • Cache models in TRANSFORMERS_CACHE to speed restarts.

Deployment (Hugging Face Spaces via Docker)

Spaces supports Docker apps; Django runs behind Gunicorn on port 7860.

  1. Add start.sh (executable)
#!/usr/bin/env bash
set -e
python manage.py collectstatic --noinput
gunicorn chatbot_project.wsgi:application --bind 0.0.0.0:7860 --workers 2 --threads 4 --timeout 120
  1. Dockerfile (root)
FROM python:3.11-slim
RUN apt-get update && apt-get install -y --no-install-recommends build-essential git curl && rm -rf /var/lib/apt/lists/*
WORKDIR /app
COPY requirements.txt /app/requirements.txt
RUN pip install --no-cache-dir -r requirements.txt
COPY . /app
ENV PORT=7860 PYTHONUNBUFFERED=1 PIP_NO_CACHE_DIR=1
EXPOSE 7860
RUN chmod +x /app/start.sh
CMD ["/app/start.sh"]
  1. Configure settings.py for static and hosts
  • Enable WhiteNoise middleware.
  • STATIC_ROOT = BASE_DIR / "staticfiles"
  • ALLOWED_HOSTS = ["*"]
  1. Create a Docker Space on Hugging Face
  • Create Space → SDK: Docker → CPU.
  • Set Space Variables: DJANGO_SECRET_KEY, DEBUG=False, GROQ_API_KEY.
  1. Push code to the Space repo
git add .
git commit -m "Deploy: Dockerized Django app for HF Spaces"
git push
  1. Open your Space URL
  • Check the UI at root.
  • If static files are missing, verify collectstatic ran in logs.

Tip: First request may be slower due to model cold-start. Warm-up by calling a tiny passage in AppConfig.ready() if desired.


Git Workflow

  • Initial push:
git init
git add .
git commit -m "Initial commit: Django chat + modules + UI"
git branch -M main
git remote add origin https://github.com/<user>/<repo>.git
git push -u origin main
  • Update cycle:
git add .
git commit -m "Update: Tailwind UI + API error handling"
git push
  • If remote is ahead:
git pull --rebase origin main
# resolve conflicts
git push

API Contract

POST /api/

  • Request:
{"passage": "Your book excerpt here..."}
  • Response:
{
  "success": true,
  "data": {
    "total_words": 123,
    "emotion": "joy (0.83)",
    "possible_books": {"possible_books": ["The Alchemist", "To Kill a Mockingbird"]},
    "summary": "Two-sentence summary..."
  }
}

Errors:

{"success": false, "error": "message"}

Troubleshooting

  • Module not found:
    • Ensure PYTHONPATH includes project root; run from repo root.
  • 403 CSRF on POST:
    • Use @csrf_exempt on API or send CSRF token if you enable CSRF.
  • Static files not loading in Spaces:
    • Check WhiteNoise, collectstatic logs, and STATIC_URL/STATIC_ROOT.
  • Slow first inference:
    • Model download on first call; subsequent calls are faster.

Roadmap

  • Add LangGraph for agentic orchestration.
  • Add caching for repeated passages.
  • Add streaming UI responses and typing delay.
  • Optional DB to log requests for analytics.

License

MIT (suggested). Include LICENSE file if open-sourcing.

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors