Skip to content
suryanshwork3456Public

About

Resources

Stars

1 star

Watchers

0 watching

Forks

Repository files navigation

# Project Setup Guide

This project requires **Python 3.14.x**. 

Follow the instructions for your OS below.

---

## 1. Install Python 3.14

### Windows
1. Go to https://www.python.org/downloads/windows/
2. Download the **Windows installer (64-bit)** for Python 3.14.x
3. Run the installer:
   - ✅ Check **"Add python.exe to PATH"**
   - Click **"Customize installation"**
   - Keep all default optional features checked (pip, py launcher)
   - Click **Install**
4. Open a **new** terminal and verify:
   ```powershell
   py -0

You should see -V:3.14 in the list.

macOS

  1. Go to https://www.python.org/downloads/macos/
  2. Download the macOS 64-bit universal2 installer for Python 3.14.x
  3. Run the .pkg installer and follow the prompts (defaults are fine)
  4. Open a new terminal and verify:
    python3.14 --version

2. Clone the repo

git clone <https://github.com/suryanshwork3456/fasAl.git>
cd server

If you already have the repo, pull the latest changes instead:

git pull origin main

3. Create and activate the virtual environment

Windows (PowerShell)

py -3.14 -m venv venv
venv\Scripts\activate
python --version   # should show Python 3.14.x

macOS (Terminal)

python3.14 -m venv venv
source venv/bin/activate
python --version   # should show Python 3.14.x

You'll know it worked when your terminal prompt shows (venv) at the start.


4. Install dependencies

With the venv activated:

pip install -r requirements.txt

This installs the exact package versions the team uses, including the SQLAlchemy version that supports Python 3.14, as well as Alembic (used for database migrations — see Section 8 below).


5. Set VS Code's interpreter (do this once per machine and it maybe optional for you)

  1. Open the project folder in VS Code
  2. Press Ctrl+Shift+P (Windows) or Cmd+Shift+P (Mac)
  3. Type "Python: Select Interpreter"
  4. Choose the interpreter inside your venv folder:
    • Windows: .\venv\Scripts\python.exe
    • Mac: ./venv/bin/python

If it's not listed, choose "Enter interpreter path" → "Find..." and browse to the path above manually.


6. Set up environment variables

On Windows: Copy-Item .env.example .env On Mac/Linux/Git Bash: cp .env.example .env

Now open the .env file in any code editor and fill in your own values:

  • DATABASE_URL — your local PostgreSQL connection string (postgresql://postgres:your_password@localhost:5432/sih_gis_db)
  • SECRET_KEY — any random string (generate one with python -c "import secrets; print(secrets.token_hex(32))")
  • GEMINI_API_KEY — your Google Gemini API key (get one at https://aistudio.google.com/apikey), used by google-genai
  • PORT — Port is 8000

⚠️ Important: DATABASE_URL must point to the same database the team is using for this project. Alembic tracks schema history per-database via an alembic_version table — pointing at the wrong database, or sharing this database with an unrelated project that also runs its own migrations, will cause Can't locate revision errors. See Section 8 for details.

7. Run the server

uvicorn app.main:app --reload

Server should start at http://127.0.0.1:8000 with no import errors.

Note: The app no longer auto-creates tables on startup (init_db() is disabled). Tables are created/updated exclusively through Alembic migrations — make sure you've run alembic upgrade head (see below) before starting the server for the first time, or your endpoints will fail with "relation does not exist" errors.


8. Database migrations (Alembic)

This project uses Alembic to manage database schema changes. Table creation and every schema change (adding/removing columns, changing types, etc.) goes through a migration file — never through manually running SQL or relying on create_all().

First-time setup (after cloning, before running the server)

Apply all existing migrations to your local database:

cd server
alembic upgrade head

This creates every table your models define, matching the current state of the alembic/versions/ folder. Verify it worked:

alembic current

This should print the latest revision ID — matching the newest file in alembic/versions/.

Whenever you pull new changes from teammates

If git pull brings in new files under alembic/versions/, run:

alembic upgrade head

again before starting the server, to apply any new schema changes to your local database.

Daily workflow (after initial setup)

Every time you start working:

# Windows
venv\Scripts\activate

# Mac
source venv/bin/activate

git pull origin main
pip install -r requirements.txt   # only needed if requirements.txt changed
alembic upgrade head              # only needed if new migrations were pulled
uvicorn app.main:app --reload

When you're done:

deactivate

Updating requirements.txt (only if you added a new package)

pip install <new-package>
pip freeze > requirements.txt
git add requirements.txt
git commit -m "Update requirements"
git push

Let teammates know to re-run pip install -r requirements.txt after pulling.


Troubleshooting

AssertionError: Class ... directly inherits TypingOnly ... You're on the wrong Python version or an outdated SQLAlchemy. Confirm:

python --version      # must be 3.14.x
pip show sqlalchemy   # must be 2.0.41 or higher

If either is wrong, delete venv and redo Step 3–4.

py -3.14 / python3.14 not found Python 3.14 isn't installed or isn't on PATH. Reinstall following Step 1, and make sure "Add to PATH" was checked (Windows) or reopen your terminal (Mac).

VS Code still shows the wrong Python version Redo Step 5 — VS Code caches the interpreter per-workspace and won't auto-switch after you recreate a venv.

relation "..." does not exist when hitting an endpoint You haven't applied migrations yet. Run alembic upgrade head from inside server/, then restart the server.

Can't locate revision identified by '...' The database's alembic_version bookmark references a migration file that doesn't exist in your local alembic/versions/ folder. This usually means either (a) you're missing migration files that a teammate committed — run git pull and try again — or (b) this database is shared with another project that ran its own migrations against it (see the Shared Database note above). Do not fix this by manually editing alembic_version — ask in the team channel first.

ModuleNotFoundError: No module named 'app' when running an alembic command You're running the command from the wrong directory. All alembic commands must be run from inside server/, where alembic.ini and app/ both live:

cd server
alembic upgrade head

Crop Insight API - basic RAG version

Folder structure

crop_rag_app/
├── main.py                  # FastAPI app entrypoint
├── requirements.txt
├── .env.example
├── routes/
│   └── analyze.py           # POST /analyze - the image upload route
├── rag/
│   ├── config.py            # all settings in one place
│   ├── chunking.py          # splits documents into small pieces
│   ├── embeddings.py        # text -> vector, via Gemini
│   ├── vector_store.py      # wraps ChromaDB (store + search)
│   └── retriever.py         # ties embeddings + vector_store together
├── scripts/
│   └── ingest.py            # run manually to build the knowledge base
├── knowledge_base/
│   └── docs/                # your raw .txt reference documents go here
└── data/
    └── chroma_db/           # created automatically - the vector database files

Setup

  1. Install dependencies:

    pip install -r requirements.txt
    
  2. Copy .env.example to .env and add your Gemini API key:

    cp .env.example .env
    

    Then either export it in your shell, or use a tool like python-dotenv to load it automatically.

  3. Build the knowledge base (only needs to be run once, and again any time you add or edit files in knowledge_base/docs/):

    python scripts/ingest.py
    
  4. Run the API:

    uvicorn main:app --reload
    
  5. Test it - POST an image to http://localhost:8000/analyze as multipart form-data under the field name file.

Adding more knowledge

Drop more .txt files into knowledge_base/docs/, one document per file (disease guide, deficiency guide, regional advisory, whatever you have), then re-run python scripts/ingest.py. The route code never needs to change - it always searches whatever is currently in the vector database.

What's intentionally left simple for now

This is the basic version. When you're ready to move toward production, the things worth revisiting are:

  • Retrieval quality: right now it's a straight top-k vector search. Metadata filtering (e.g. only search chunks tagged with the identified crop type) would cut down on irrelevant matches.
  • Error handling: right now Gemini or Chroma failures raise a generic 500. Production would want more specific error handling and retries.
  • Observability: logging which chunks got retrieved for which query, so you can debug bad answers.
  • Swapping ChromaDB for a hosted vector database if you need multiple servers to share one knowledge base (Chroma's local file mode is single-machine).
  • Re-embedding only changed documents in ingest.py, instead of everything, once your knowledge base grows large.

None of this requires restructuring the code above - it's designed so each of those upgrades happens inside one file at a time.

About

Resources

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages