YAML Metadata Warning:empty or missing yaml metadata in repo card
Check out the documentation for more information.
- HawkEyes Universe (v2)
- ๐ณ Docker (run this project on any machine)
- โก Quick Start: ๐ Conda on localhost (Python 3.14)
- ๐ฃ Guest Voiceprint Registry (
/speechflow/) - ๐ Secrets & Credentials (tracked in git)
- ๐ HuggingFace Hub Login
- ๐ฅ CUDA Library Path for GPU (cublas)
- Sync: 2026-11-22 - whitespace adjustment
- --- End of file marker (auto-generated) ---
HawkEyes Universe (v2)
One FastAPI service (Universe_API.py, port 5656) that fronts every HawkEyes
AI module โ retail image analysis, OCR, face detection/recognition, eKYC, NLP
scoring and the speech-analysis pipeline โ behind a single uniform contract:
POST /<module>/ with an appId + image/audio URLs, and the module's result
comes back on ai_feedback. Interactive docs at http://<host>:5656/docs.
- Modules live in
modules/<name>/<name>_main.py, one class each. - Model weights are loaded once at boot by
tools/models_handler.pyfromAI_Models/(~5 GB, git-lfs) and passed into each request. - Sample request bodies for every endpoint are in
DemoBody/*.json. - appId per endpoint is in
tools/appId.jsonโ a request whoseappIddoesn't match is answered withstatusAI: falseand no work done.
| endpoint | module | endpoint | module |
|---|---|---|---|
/bat/ |
BAT shelf/POSM detection | /nlpBat/, /nlpZeroCal/, /nlpMaya/, /nlpRancon/ |
NLP scoring variants |
/hotspot/ |
BAT hotspot | /speechflow/ |
speech analyzer + guest registry |
/fridgeDetection/ |
beverage fridge | /conversationalguidance/ |
conversational guidance |
/materialDetection/ |
material detection | /speakmetric/ |
speak metrics |
/faceDetection/, /faceRecognition/ |
face stack | /pitchMonitoring/, /SuzukipitchMonitoring/ |
pitch monitoring |
/banglaOcr/, /nidOcr/, /ocr/, /mTHouseOCR/ |
OCR stack | /intimgana/, /intimgana_ubl/ |
international image analysis |
/domex/, /fmcg/ |
UBL categories | /status/<module> |
per-module health |
Hardware
Preferred: NVIDIA RTX A4000 or RTX 3090 Ti. Avoid RTX 5060 Ti and Tesla P100 โ neither works with this CUDA/driver combination.
Everything falls back to CPU automatically (torch, ctranslate2, YOLO); it is only slower. Whisper large-v3 + the YOLO set + pyannote + speechbrain loaded at once needs roughly 24 GB RAM.
RAM: the API uses about 11 GB at startup and levels off at about 20 GB once every
route has been used, with or without a GPU. Use a machine with at least 32 GB, and
run only one instance on it. In Docker, keep MEMORY_LIMIT at 22g or higher.
๐ณ Docker (run this project on any machine)
The Docker image is still on Python 3.11, with its own pins in
docker/requirements/, while the conda setup below is on Python 3.14.
docker-compose.yml runs standalone on any machine with plain Docker
Desktop (CPU-only โ torch/ctranslate2/YOLO all fall back automatically,
just slower). GPU acceleration is opt-in via docker-compose.gpu.yml,
which requires the NVIDIA Container Toolkit on the host and a driver
supporting CUDA 13 forward compat (>=580.x). Everything below is a
one-time host setup โ the image itself is fully self-contained and pinned.
# 1. Pull the actual model weights (image does NOT bake these in โ 5GB, LFS)
git lfs pull
# 2. Secrets come with the clone and are mounted at run time, never baked into
# the image: tools/.env, tools/service_account.json,
# modules/ekyc/utils/cloudVisionAPI.json
# 3. Ollama runs on the HOST, not in this image (see "Ollama" below)
ollama pull qwen3:8b
# 4. Build + run โ CPU-only, any machine:
docker compose up --build -d
# ...or with GPU, on a host with the NVIDIA Container Toolkit installed:
docker compose -f docker-compose.yml -f docker-compose.gpu.yml up --build -d
# 5. Check it's alive
curl http://localhost:5656/docs
docker compose logs -f
To stop: docker compose down (add -v to also wipe the model-download
caches in speechbrain_cache/hf_cache, forcing a re-download next start).
Reaching the host's Ollama from the container
The image contains no Ollama. The container reaches the host daemon over
host.docker.internal, which docker-compose.yml already maps via
extra_hosts: host-gateway and passes as
OLLAMA_HOST=http://host.docker.internal:11434. For that to resolve, Ollama
must be listening on all interfaces, not just loopback:
sudo systemctl edit ollama # add: [Service] / Environment="OLLAMA_HOST=0.0.0.0:11434"
sudo systemctl restart ollama
docker compose exec he-universe curl -s http://host.docker.internal:11434/api/tags
If that last command fails, guests simply stay "Guest" โ nothing else breaks.
Verifying the Docker setup
bash scripts/lint-docker.sh # hadolint + compose config, seconds
bash scripts/docker-smoke-test.sh # full build + start + wait-for-healthy
docker-smoke-test.sh needs the same prerequisites as steps 1-2 above (real
AI_Models/ weights + credential files) since the app won't start without
them โ that's also why CI (.github/workflows/docker-ci.yml) only lints and
builds, not runs, the image.
Running with plain docker run (no compose, e.g. on a machine that only pulled the image)
Compose's volumes/env/GPU flags translated 1:1:
docker run -d \
--name he-universe \
--gpus all \
-p 5656:5656 \
-e PUID=$(id -u) -e PGID=$(id -g) \
-e OLLAMA_HOST=http://host.docker.internal:11434 \
--add-host host.docker.internal:host-gateway \
-v "$(pwd)/AI_Models:/app/AI_Models:ro" \
-v speechbrain_cache:/app/AI_Models/SpeechAnalyzer_Models/pretrained_models \
-v hf_cache:/home/appuser/.cache/huggingface \
-v "$(pwd)/logs:/app/logs" \
-v "$(pwd)/data/guest_registry:/app/data/guest_registry" \
-v "$(pwd)/tools/.env:/app/tools/.env:ro" \
-v "$(pwd)/tools/service_account.json:/app/tools/service_account.json:ro" \
-v "$(pwd)/modules/ekyc/utils/cloudVisionAPI.json:/app/modules/ekyc/utils/cloudVisionAPI.json:ro" \
--restart unless-stopped \
hawkeyes-universe:latest
(swap the final image name for yourdockerhubuser/hawkeyes-universe:latest if pulling from Docker Hub instead of building locally)
Publishing to Docker Hub
The image is already built to be push-safe: AI_Models/ (proprietary weights),
all credential files, .git, and the Dockerfile/compose files themselves are
excluded from the build context (.dockerignore) โ only application code and
pinned dependencies get baked in. Application source code IS baked in
though (COPY . .), so unless this is meant to be public, push to a
private Docker Hub repository.
export IMAGE_NAME=yourdockerhubuser/hawkeyes-universe
export IMAGE_TAG=1.0.0 # or "latest" โ pick something you can track releases by
docker login
docker compose build
docker compose push
(docker compose push works because image: in docker-compose.yml is
already registry-qualified via $IMAGE_NAME/$IMAGE_TAG.)
To pull and run it on another machine afterward, that machine needs docker login
too (for a private repo), then the same docker run/docker compose up
commands above with IMAGE_NAME/IMAGE_TAG set to match, plus its own copy of
AI_Models/ (git-lfs) and the secret files โ those never travel with the image.
โก Quick Start: ๐ Conda on localhost (Python 3.14)
(skip this if you're using Docker above)
Needs an NVIDIA driver that supports CUDA 13.2 (the CUDA Version shown by
nvidia-smi). Without a GPU everything falls back to CPU, just slower.
System packages
sudo apt update
sudo apt install -y git git-lfs wget ffmpeg libgl1 libglib2.0-0 nvtop
Conda
Skip this if you already have conda:
wget https://github.com/conda-forge/miniforge/releases/latest/download/Miniforge3-Linux-x86_64.sh
bash Miniforge3-Linux-x86_64.sh -b -p $HOME/miniforge3
source "$HOME/miniforge3/bin/activate"
conda init
Then open a new terminal.
Get the code and model weights
git lfs install
git config --global credential.helper store
git clone -b dev https://huggingface.co/HawkEyesAI/v2_HE_Universe
cd v2_HE_Universe
git lfs pull
The credential files come with the clone: see "Secrets & Credentials" below.
Create the environment
bash scripts/setup_conda_env.sh
Creates the HE env from environment.yml and requirements.txt, and takes
10-15 minutes the first time. It's safe to re-run. It also does the steps pip
can't do on its own:
- Patches
face_recognition_models, which imports the removedpkg_resources. - Adds a conda activation hook so
faster-whispercan findlibcublas.so.12(see "CUDA Library Path for GPU" below). - Downloads the NLTK data and pulls the Ollama model used for guest names.
| File | What it holds |
|---|---|
environment.yml |
Python itself, plus a prebuilt dlib from conda-forge, so nothing needs compiling |
requirements.txt |
Packages the project uses directly, pinned to exact versions |
requirements-freeze.txt |
Full snapshot of a verified environment, for reference |
Run
conda activate HE
python Universe_API.py
The first start downloads Whisper and the speech models (several GB). Check it
at http://127.0.0.1:5656/docs. Set HOST and PORT to change the address.
Check every route
With the API running, from another terminal:
python scripts/smoke_test_routes.py
It posts each sample in DemoBody/ to its route, one at a time, and exits
non-zero if any route fails. A sample whose image or audio URL no longer exists
is reported as SKIP rather than FAIL; replace that URL to test the route. Pass
--base http://host:port to check another machine.
The /status/* routes check the production ngrok tunnel by default. On a VM
without it, set STATUS_BASE_URL=http://127.0.0.1:5656 in tools/.env.
๐ Optional: expose it with ngrok
curl -s https://ngrok-agent.s3.amazonaws.com/ngrok.asc | sudo tee /etc/apt/trusted.gpg.d/ngrok.asc >/dev/null
echo "deb https://ngrok-agent.s3.amazonaws.com buster main" | sudo tee /etc/apt/sources.list.d/ngrok.list
sudo apt update
sudo apt install -y ngrok
ngrok config add-authtoken "${NGROK_AUTHTOKEN:?set NGROK_AUTHTOKEN env var first}"
ngrok http --domain=batnlp.ngrok.app 5656
๐ฃ Guest Voiceprint Registry (/speechflow/)
The speech analyzer identifies the employee from tools/emp_audio/emp_reg.py
and now also learns the guest. On a first meeting it isolates the guest's
diarized audio, asks the local Ollama model (step 8๏ธโฃ above) for the name the
guest states about themselves, and enrolls that voiceprint. Every later
conversation with the same voice comes back named instead of "Guest" โ live,
with no restart, because the registry is one in-process object mutated in place.
Bangla and English
Audio may be Bangla, English, or the two mixed in one sentence. Two Whisper passes run over each conversation, because the two consumers want opposite things:
| pass | settings | used for |
|---|---|---|
| translated | language="en", task="translate" |
the detection regexes in utils/plannedData.py |
| native | language auto-detected, condition_on_previous_text=False |
reading the guest's spoken name |
The translated pass is deliberately left exactly as it was, because the
patterns_employee regexes are tuned to its specific mangling (they absorb
"Benchelon Hazards Bridge"), and changing it would move the KPI numbers.
The native pass exists because a name cannot survive translation. Whisper was
previously told language="en" even when the speaker was talking Bangla, which
forces a Bangla name through an English-only token prior โ that is how a
shopkeeper who said "Rakib" was enrolled as "Rakim". The native pass runs only
for guest speakers, so it costs one extra pass per guest, not per speaker.
Names are stored in Latin script to match the employee roster, so a name
given in Bangla is transliterated by the same local model that extracted it
(เฆฐเฆพเฆเฆฟเฆฌ โ Rakib). Set TRANSLITERATE_NAMES=false to keep it as spoken.
Behaviour
All tunable via env (see .env.example / tools/guest_registry/config.py):
- Works whether or not an employee speaks: every speaker not matched to an employee is resolved on their own (a solo guest recording works too).
- Employees are matched first and never enter the guest registry. A speaker whose spoken name belongs to a registered employee (e.g. "I am Nayem" when the voice scored under the threshold) is also never enrolled as a guest.
- Enrollment needs โฅ
MIN_ENROLL_SECONDS(3s) of that speaker's audio and a name they say about themselves. No name โ stays "Guest", stores nothing. - Matching needs โฅ
MIN_RESOLVE_SECONDS(2s); shorter clips are not compared at all, because ECAPA embeddings from a scrap of audio are unstable both ways. - A returning voice wins over a differing spoken name; the mismatch is reported
as
name_conflicton the guest payload and logged โ and that clip is not added to the voiceprint, since the disagreement is the best available signal that it may belong to someone else. - Near-miss rescue: a score in
[GUEST_NEAR_MISS_THRESHOLD, GUEST_MATCH_THRESHOLD)is too weak to name a guest, but if the speaker states that guest's registered name it is accepted as a fresh sample rather than enrolled as a duplicate. Without this a guest whose one stored voiceprint was poor could never acquire a better one โadd_sampleonly ever ran after a successful match. - Up to
MAX_SAMPLES_PER_GUEST(5) clips per guest. At the cap a current-recipe sample displaces an older-recipe one; same-recipe samples are never evicted. - A name is only enrolled when both Whisper passes agree on it
(
GUEST_NAME_REQUIRE_AGREEMENT), and never when it contains a tobacco brand token โ a cigarette brand in the registry scores against every shopkeeper met afterwards. - Ollama down / slow โ name extraction returns nothing and the endpoint behaves exactly as it did before this feature.
Voiceprints
Voiceprints are built from the original audio, not the noise-reduced copy,
and from the longest single contiguous speech run rather than every diarized
segment concatenated. noisereduce's spectral gating leaves artefacts shaped by
each recording's own noise profile, so the same voice recorded on two visits
embedded differently and scored far below threshold against itself; and
concatenation joins non-adjacent audio with hard cuts the encoder reads as
signal. Both are controlled by GUEST_EMBED_SOURCE / GUEST_EMBED_LONGEST_SEGMENT.
Changing either changes the embedding recipe version, recorded on every
sample. Voiceprints enrolled under an older recipe still participate in matching
but score low, which looks exactly like a stranger's voice โ so they are flagged
at startup and listed by manage stale. Re-enroll them for full accuracy.
Administration
python -m tools.guest_registry.manage list # who is enrolled
python -m tools.guest_registry.manage stale # stale voiceprints
python -m tools.guest_registry.manage rename guest_0001 Rakib # fix a wrong name
python -m tools.guest_registry.manage merge guest_0004 guest_0001 # one person, two records
python -m tools.guest_registry.manage prune [guest_id] # drop old-recipe samples + orphan wavs
python -m tools.guest_registry.manage delete guest_0003 # remove a guest
# in Docker: docker compose exec he-universe python -m tools.guest_registry.manage list
A rename or delete lands in index.json immediately, but the API holds the
registry in memory โ restart it for the change to take effect there.
Data lives in data/guest_registry/ (index.json + audio/<guest_id>/*.wav),
bind-mounted and writable in docker-compose.yml. It is gitignored โ these are
recordings of real people. AI_Models is mounted read-only and cannot hold it.
๐ Secrets & Credentials (tracked in git)
These files are required at runtime and are committed with the repo, so a clone already has them. Anyone with read access to the repo can read them, so replace the key if that access ever widens:
tools/.envโELEVENLABS_API_KEY,FERNET_KEY,ENCRYPTED(HF token)tools/service_account.jsonโ GCP service account for Gemini (Vertex AI) and Translatemodules/ekyc/utils/cloudVisionAPI.jsonโ GCP service account for VisionNGROK_AUTHTOKENenv var, if exposing via ngrok
๐ HuggingFace Hub Login
Only needed to clone or pull this repo from Hugging Face. The app gets its own
token for gated models from tools/.env.
hf auth login
๐ฅ CUDA Library Path for GPU (cublas)
faster-whisper (via ctranslate2) loads libcublas.so.12 by name at run time,
but torch's CUDA 13 packages only ship libcublas.so.13. Without a fix,
transcription fails with RuntimeError: Library libcublas.so.12 is not found.
requirements.txt includes nvidia-cublas-cu12 to provide the library, and
scripts/setup_conda_env.sh adds a conda activation hook that puts it on
LD_LIBRARY_PATH. The hook only runs on conda activate HE or conda run -n HE,
so calling the env's python by its full path skips it.
GCP Project Setup โ Required Services & APIs
If you are creating a new GCP project to run this system from scratch, enable the following services and APIs before deploying.
1. Core APIs to Enable
Go to APIs & Services โ Library in the GCP Console, or run:
gcloud services enable \
aiplatform.googleapis.com \
translate.googleapis.com \
vision.googleapis.com \
storage.googleapis.com \
iam.googleapis.com \
iamcredentials.googleapis.com
| API / Service | Why it is needed |
|---|---|
Vertex AI API (aiplatform.googleapis.com) |
Hosts gemini-2.5-flash via the google-genai SDK. Used by mtHouseOCR, banglaOCR, ekyc, nlpRancon, and speakMetric (guest name extraction). |
Cloud Translation API (translate.googleapis.com) |
Used by ModelSpeechAnalyzer to translate Bangla speech transcripts to English for pattern matching. |
Cloud Vision API (vision.googleapis.com) |
Used by the ekyc module for document OCR and face detection. |
Cloud Storage API (storage.googleapis.com) |
Required by Vertex AI internally for model serving. Also used if you store audio/image assets in GCS. |
IAM API (iam.googleapis.com) |
Required to create and manage the service account used by the application. |
IAM Service Account Credentials API (iamcredentials.googleapis.com) |
Required for service account token generation (used by the google-genai Vertex AI client). |
2. Vertex AI โ Region
Important: Only
us-central1is confirmed to servegemini-2.5-flashvia Vertex AI for this project.
The region is hardcoded in tools/gemini_client.py:
LOCATION = "us-central1"
Do not change this to another region without first verifying that gemini-2.5-flash is available there via the Vertex AI model garden.
3. Service Account
Create one service account with the following roles:
cat > he_setup.sh <<'HE_SETUP_EOF'
#!/usr/bin/env bash
#
# HE Universe - GCP automatic setup
#
# Run it as a file, never paste it line by line:
# bash he_setup.sh
#
# Safe to rerun: existing resources are skipped.
set -euo pipefail
trap 'echo; echo "[ERROR] Failed at line $LINENO: $BASH_COMMAND" >&2' ERR
echo
echo "================================================"
echo " HE UNIVERSE GCP AUTOMATIC SETUP"
echo "================================================"
echo
# --------------------------------------------------
# 0. PREREQUISITES
# --------------------------------------------------
for CMD in gcloud jq; do
if ! command -v "$CMD" >/dev/null 2>&1; then
echo "ERROR: '$CMD' is not installed."
exit 1
fi
done
ask_yes_no() {
# ask_yes_no "Question" default(y|n)
local prompt="$1" default="$2" reply
if [[ "$default" == "y" ]]; then
read -rp "$prompt [Y/n]: " reply < /dev/tty || reply=""
[[ -z "$reply" || "$reply" =~ ^[Yy] ]]
else
read -rp "$prompt [y/N]: " reply < /dev/tty || reply=""
[[ "$reply" =~ ^[Yy] ]]
fi
}
# --------------------------------------------------
# 1. INPUT
# --------------------------------------------------
read -rp "Enter your GCP Project ID: " PROJECT_ID < /dev/tty
PROJECT_ID="$(echo "$PROJECT_ID" | tr -d '[:space:]')"
if [[ -z "$PROJECT_ID" ]]; then
echo "ERROR: Project ID cannot be empty."
exit 1
fi
SA_NAME="he-universe"
SA_EMAIL="${SA_NAME}@${PROJECT_ID}.iam.gserviceaccount.com"
KEY_FILE="tools/service_account.json"
APIS=(
aiplatform.googleapis.com
translate.googleapis.com
vision.googleapis.com
storage.googleapis.com
iam.googleapis.com
iamcredentials.googleapis.com
cloudresourcemanager.googleapis.com
orgpolicy.googleapis.com
)
ROLES=(
roles/aiplatform.user
roles/cloudtranslate.user
roles/storage.objectViewer
)
KEY_CONSTRAINTS=(
iam.disableServiceAccountKeyCreation
iam.managed.disableServiceAccountKeyCreation
)
FAILED=0
OVERRIDDEN=() # constraints this script turned off
PREEXISTING=() # constraints that already had a project-level policy
JQ_HAS_ROLE='
any(
(.bindings // [])[];
.role == $role
and .condition == null
and ((.members // []) | index($member) != null)
)'
# true if the file is a non-empty, valid key for THIS service account
valid_key() {
[[ -s "$1" ]] && jq -e \
--arg email "$SA_EMAIL" \
'.type == "service_account" and .client_email == $email and (.private_key | length > 0)' \
"$1" >/dev/null 2>&1
}
# --------------------------------------------------
# 2. AUTHENTICATION
# --------------------------------------------------
echo
echo "[1/10] Checking authentication..."
ACTIVE_ACCOUNT=$(gcloud auth list \
--filter="status:ACTIVE" \
--format="value(account)" 2>/dev/null || true)
if [[ -z "$ACTIVE_ACCOUNT" ]]; then
echo "ERROR: No authenticated GCP account."
echo "Run: gcloud auth login"
exit 1
fi
echo "[OK] Account: $ACTIVE_ACCOUNT"
# --------------------------------------------------
# 3. PROJECT VALIDATION
# --------------------------------------------------
echo
echo "[2/10] Verifying project..."
if ! gcloud projects describe "$PROJECT_ID" >/dev/null 2>&1; then
echo "ERROR: Project '$PROJECT_ID' not found or permission denied."
exit 1
fi
gcloud config set project "$PROJECT_ID" >/dev/null 2>&1
ORG_ID=$(gcloud projects get-ancestors "$PROJECT_ID" \
--format="value(id,type)" 2>/dev/null | awk '$2=="organization"{print $1}' || true)
echo "[OK] Project: $PROJECT_ID"
if [[ -n "$ORG_ID" ]]; then
echo "[OK] Organization: $ORG_ID"
else
echo "[INFO] Project is not inside an organization."
fi
# --------------------------------------------------
# 4. ENABLE APIs
# --------------------------------------------------
echo
echo "[3/10] Checking APIs..."
if ! ENABLED_APIS=$(gcloud services list \
--enabled \
--project="$PROJECT_ID" \
--format="value(config.name)"); then
echo "ERROR: Could not list APIs."
echo "Usually means billing is not linked or you lack permission."
exit 1
fi
for API in "${APIS[@]}"; do
if grep -Fxq "$API" <<< "$ENABLED_APIS"; then
echo "[EXISTS] $API"
else
echo "[ENABLING] $API"
if gcloud services enable "$API" --project="$PROJECT_ID"; then
echo "[ENABLED] $API"
else
echo "[FAILED] Could not enable $API (billing / permission?)"
FAILED=$((FAILED + 1))
fi
fi
done
# --------------------------------------------------
# 5. SERVICE ACCOUNT
# --------------------------------------------------
echo
echo "[4/10] Checking service account..."
if gcloud iam service-accounts describe "$SA_EMAIL" \
--project="$PROJECT_ID" >/dev/null 2>&1; then
echo "[EXISTS] $SA_EMAIL"
else
gcloud iam service-accounts create "$SA_NAME" \
--project="$PROJECT_ID" \
--display-name="HE Universe API"
echo "[WAITING] For service account to propagate..."
for i in {1..20}; do
if gcloud iam service-accounts describe "$SA_EMAIL" \
--project="$PROJECT_ID" >/dev/null 2>&1; then
break
fi
sleep 3
done
echo "[CREATED] $SA_EMAIL"
fi
# --------------------------------------------------
# 6. IAM ROLES
# --------------------------------------------------
echo
echo "[5/10] Checking IAM roles..."
POLICY=$(gcloud projects get-iam-policy "$PROJECT_ID" --format=json)
for ROLE in "${ROLES[@]}"; do
EXISTS=$(jq -r \
--arg role "$ROLE" \
--arg member "serviceAccount:$SA_EMAIL" \
"$JQ_HAS_ROLE" <<< "$POLICY")
if [[ "$EXISTS" == "true" ]]; then
echo "[EXISTS] $ROLE"
continue
fi
echo "[GRANTING] $ROLE"
GRANTED=false
for i in {1..5}; do
if gcloud projects add-iam-policy-binding "$PROJECT_ID" \
--member="serviceAccount:$SA_EMAIL" \
--role="$ROLE" \
--condition=None \
--quiet >/dev/null 2>&1; then
GRANTED=true
break
fi
echo " retrying in 5s ($i/5)..."
sleep 5
done
if $GRANTED; then
echo "[GRANTED] $ROLE"
else
echo "[FAILED] Could not grant $ROLE (need Owner / IAM Admin?)"
FAILED=$((FAILED + 1))
fi
done
# --------------------------------------------------
# 7. EXISTING KEY FILE CHECK
# --------------------------------------------------
mkdir -p tools
NEED_KEY=true
if [[ -e "$KEY_FILE" ]]; then
if valid_key "$KEY_FILE"; then
NEED_KEY=false
elif [[ ! -s "$KEY_FILE" ]] || ! jq -e '.type == "service_account"' "$KEY_FILE" >/dev/null 2>&1; then
# Empty or broken file left by an earlier failed run
echo
echo "[CLEANUP] $KEY_FILE is empty or invalid - removing it."
rm -f "$KEY_FILE"
else
# Valid key, but for a different service account: keep it aside
OTHER_EMAIL=$(jq -r '.client_email // "unknown"' "$KEY_FILE")
BACKUP="${KEY_FILE%.json}.$(date +%Y%m%d%H%M%S).bak.json"
echo
echo "[WARNING] $KEY_FILE belongs to a different account:"
echo " $OTHER_EMAIL"
echo " Moving it to $BACKUP"
mv "$KEY_FILE" "$BACKUP"
chmod 600 "$BACKUP"
fi
fi
# --------------------------------------------------
# 8. KEY CREATION POLICY (ORG POLICY)
# --------------------------------------------------
echo
echo "[6/10] Checking key creation policy..."
is_enforced() {
# true if the effective policy on this project enforces the constraint
local c="$1" out
out=$(gcloud org-policies describe "$c" \
--project="$PROJECT_ID" --effective --format=json 2>/dev/null) || return 1
[[ "$(jq -r '[.spec.rules[]?.enforce] | any' <<< "$out")" == "true" ]]
}
has_project_policy() {
gcloud org-policies describe "$1" --project="$PROJECT_ID" >/dev/null 2>&1
}
BLOCKING=()
if ! $NEED_KEY; then
echo "[SKIPPED] Valid key already exists, no new key needed."
elif [[ -z "$ORG_ID" ]]; then
echo "[OK] No organization, no key policy restrictions."
else
for C in "${KEY_CONSTRAINTS[@]}"; do
if is_enforced "$C"; then
echo "[BLOCKED] $C is enforced"
BLOCKING+=("$C")
else
echo "[OK] $C not enforced"
fi
done
fi
if (( ${#BLOCKING[@]} > 0 )); then
echo
echo "Service account key creation is blocked by organization policy."
echo "The script can turn this off for project '$PROJECT_ID' ONLY"
echo "(the rest of the organization stays protected)."
echo
if ask_yes_no "Allow key creation for this project?" "n"; then
for C in "${BLOCKING[@]}"; do
if has_project_policy "$C"; then
PREEXISTING+=("$C")
fi
TMP_POLICY=$(mktemp)
cat > "$TMP_POLICY" <<POLICY_EOF
name: projects/${PROJECT_ID}/policies/${C}
spec:
rules:
- enforce: false
POLICY_EOF
if gcloud org-policies set-policy "$TMP_POLICY" >/dev/null 2>&1; then
echo "[ALLOWED] $C turned off for $PROJECT_ID"
OVERRIDDEN+=("$C")
else
echo "[FAILED] Could not change $C - permission denied."
echo
echo " You need 'Organization Policy Administrator'."
echo " Ask an org admin to run:"
echo
echo " gcloud organizations add-iam-policy-binding $ORG_ID \\"
echo " --member=\"user:$ACTIVE_ACCOUNT\" \\"
echo " --role=\"roles/orgpolicy.policyAdmin\""
echo
echo " Then rerun: bash he_setup.sh"
fi
rm -f "$TMP_POLICY"
done
else
echo "[SKIPPED] Policy left unchanged. Key creation will likely fail."
fi
fi
# --------------------------------------------------
# 9. CREATE KEY
# --------------------------------------------------
echo
echo "[7/10] Preparing key file..."
if ! $NEED_KEY; then
echo "[EXISTS] Valid key for $SA_EMAIL"
echo "[SKIPPED] Key will not be overwritten."
else
# Policy changes take a few minutes to propagate, so retry longer
if (( ${#OVERRIDDEN[@]} > 0 )); then
TRIES=24 # 24 x 30s = up to 12 minutes
echo "[INFO] Policy changes can take a few minutes to apply."
else
TRIES=1
fi
CREATED=false
for (( i=1; i<=TRIES; i++ )); do
echo "[GENERATING] Service account key (attempt $i/$TRIES)..."
if gcloud iam service-accounts keys create "$KEY_FILE" \
--iam-account="$SA_EMAIL" \
--project="$PROJECT_ID" 2>/tmp/he_key_err.txt \
&& valid_key "$KEY_FILE"; then
CREATED=true
break
fi
rm -f "$KEY_FILE"
if (( i < TRIES )); then
echo " not allowed yet, waiting 30s..."
sleep 30
fi
done
if $CREATED; then
chmod 600 "$KEY_FILE"
echo "[CREATED] $KEY_FILE"
else
echo
echo "[FAILED] Key creation failed:"
sed 's/^/ /' /tmp/he_key_err.txt 2>/dev/null || true
echo
echo "Check the policy step above, then rerun: bash he_setup.sh"
FAILED=$((FAILED + 1))
fi
rm -f /tmp/he_key_err.txt
fi
# --------------------------------------------------
# 10. RE-ENABLE PROTECTION
# --------------------------------------------------
echo
echo "[8/10] Restoring key creation protection..."
if (( ${#OVERRIDDEN[@]} > 0 )); then
echo "Existing keys keep working after protection is re-enabled."
if ask_yes_no "Re-enable the protection now (recommended)?" "y"; then
for C in "${OVERRIDDEN[@]}"; do
if [[ " ${PREEXISTING[*]-} " == *" $C "* ]]; then
echo "[SKIPPED] $C had a custom project policy before;"
echo " restore it manually in Organization Policies."
elif gcloud org-policies delete "$C" --project="$PROJECT_ID" >/dev/null 2>&1; then
echo "[RESTORED] $C (inherits organization setting again)"
else
echo "[WARNING] Could not restore $C - do it in the console."
fi
done
else
echo "[SKIPPED] Key creation stays allowed for $PROJECT_ID."
fi
else
echo "[SKIPPED] Nothing was changed."
fi
# --------------------------------------------------
# 11. FINAL VERIFICATION
# --------------------------------------------------
echo
echo "[9/10] Final verification..."
echo
echo "================================================"
echo " VERIFICATION REPORT"
echo "================================================"
if [[ "$(gcloud config get-value project 2>/dev/null)" == "$PROJECT_ID" ]]; then
echo "[OK] Project"
else
echo "[FAILED] Project"
FAILED=$((FAILED + 1))
fi
if gcloud iam service-accounts describe "$SA_EMAIL" \
--project="$PROJECT_ID" >/dev/null 2>&1; then
echo "[OK] Service account"
else
echo "[FAILED] Service account"
FAILED=$((FAILED + 1))
fi
ENABLED_APIS=$(gcloud services list \
--enabled \
--project="$PROJECT_ID" \
--format="value(config.name)" 2>/dev/null || true)
for API in "${APIS[@]}"; do
if grep -Fxq "$API" <<< "$ENABLED_APIS"; then
echo "[OK] API: $API"
else
echo "[FAILED] API: $API"
FAILED=$((FAILED + 1))
fi
done
POLICY=$(gcloud projects get-iam-policy "$PROJECT_ID" --format=json 2>/dev/null || echo '{}')
for ROLE in "${ROLES[@]}"; do
EXISTS=$(jq -r \
--arg role "$ROLE" \
--arg member "serviceAccount:$SA_EMAIL" \
"$JQ_HAS_ROLE" <<< "$POLICY")
if [[ "$EXISTS" == "true" ]]; then
echo "[OK] IAM: $ROLE"
else
echo "[FAILED] IAM: $ROLE"
FAILED=$((FAILED + 1))
fi
done
if valid_key "$KEY_FILE"; then
echo "[OK] Service account JSON key"
echo "[OK] Key matches project account"
else
echo "[FAILED] JSON key missing or invalid"
FAILED=$((FAILED + 1))
fi
# --------------------------------------------------
# DOWNLOAD + SUMMARY
# --------------------------------------------------
echo
echo "[10/10] Download & summary"
echo
if valid_key "$KEY_FILE"; then
if type cloudshell >/dev/null 2>&1; then
echo "Triggering Cloud Shell download..."
cloudshell download "$KEY_FILE" || \
echo "[WARNING] Auto download failed. Use Cloud Shell menu (โฎ) -> Download"
elif type dl >/dev/null 2>&1; then
echo "Triggering Cloud Shell download..."
dl "$KEY_FILE" || \
echo "[WARNING] Auto download failed. Use Cloud Shell menu (โฎ) -> Download"
else
echo "Manually download: $(pwd)/$KEY_FILE"
echo "Cloud Shell menu (โฎ) -> Download"
fi
else
echo "[SKIPPED] No valid key file - nothing downloaded."
fi
echo
echo "================================================"
if [[ "$FAILED" -eq 0 ]]; then
echo " ALL VERIFICATIONS PASSED"
echo "================================================"
echo
echo "Project ID: $PROJECT_ID"
echo "Service Account: $SA_EMAIL"
echo "Key File: $KEY_FILE"
echo
echo "GCP setup completed successfully."
else
echo " COMPLETED WITH $FAILED FAILURE(S)"
echo "================================================"
echo
echo "Check the [FAILED] messages above."
echo "This script is safe to rerun."
fi
echo
echo "SECURITY WARNING:"
echo "Never commit service_account.json to GitHub."
echo "================================================"
HE_SETUP_EOF
bash he_setup.sh
Place the downloaded JSON key at tools/service_account.json. Both tools/gemini_client.py and tools/models_handler.py read it from that path.
| IAM Role | Used by |
|---|---|
roles/aiplatform.user |
Gemini inference via Vertex AI (gemini_client.py) |
roles/cloudtranslate.user |
Cloud Translation in ModelSpeechAnalyzer |
roles/cloudvision.serviceAgent |
Cloud Vision in ekyc module |
4. External API Key (ElevenLabs)
The heSpeechAnalyzer and nlpRancon modules optionally use ElevenLabs for high-quality speech-to-text (falls back to local Whisper if the key is absent).
Set in .env:
ELEVENLABS_API_KEY=your_key_here
Get a key at elevenlabs.io. The free tier is sufficient for testing.
5. Checklist Summary
[ ] New GCP project created
[ ] Vertex AI API enabled (aiplatform.googleapis.com)
[ ] Cloud Translation API enabled (translate.googleapis.com)
[ ] Cloud Vision API enabled (vision.googleapis.com)
[ ] Cloud Storage API enabled (storage.googleapis.com)
[ ] IAM APIs enabled (iam + iamcredentials)
[ ] Service account created with aiplatform.user + cloudtranslate.user + cloudvision.serviceAgent
[ ] Service account key downloaded to tools/service_account.json
[ ] Region set to us-central1 in tools/gemini_client.py
[ ] ELEVENLABS_API_KEY set in tools/.env (optional โ Whisper fallback works without it)