Skip to content

chandana2624/realtime-source-code-analyzer

Repository files navigation

🔍 Realtime Source Code Analyzer

ScholarX ML Engineer Internship — Task 2: Package a Model Inference Service

A production-ready FastAPI inference service that analyzes source code quality in real-time, detecting issues and returning actionable improvement suggestions with a quality score.


📁 Project Structure

realtime-source-code-analyzer/
│
├── app.py              # FastAPI application — all endpoints defined here
├── analyzer.py         # Core analysis engine — rule-based ML logic
├── validator.py        # Pydantic input/output validation models
├── requirements.txt    # Python dependencies
├── sample_input.json   # Example request body for testing
├── logs.txt            # Runtime log file (auto-written by the service)
├── Dockerfile          # Docker container configuration
├── render.yaml         # Render.com deployment configuration
├── .gitignore          # Git ignore rules
└── README.md           # This file

⚙️ What Each File Does

File Purpose
app.py FastAPI app — defines routes, middleware, exception handlers
analyzer.py Analysis engine — detects issues, computes quality score
validator.py Pydantic models — validates all API inputs and outputs
requirements.txt Lists all Python packages to install
sample_input.json Ready-to-use test payload for Postman/curl
logs.txt Auto-populated with all request and analysis logs
Dockerfile Builds the service into a Docker container
render.yaml One-click deploy config for Render.com
.gitignore Keeps your repository clean

🚀 Run Locally

Prerequisites

  • Python 3.10 or higher
  • pip

Step 1 — Clone the repository

git clone https://github.com/YOUR_USERNAME/realtime-source-code-analyzer.git
cd realtime-source-code-analyzer

Step 2 — Create a virtual environment

# Windows
python -m venv venv
venv\Scripts\activate

# macOS / Linux
python -m venv venv
source venv/bin/activate

Step 3 — Install dependencies

pip install -r requirements.txt

Step 4 — Start the server

uvicorn app:app --reload --host 0.0.0.0 --port 8000

Step 5 — Open Swagger UI

http://localhost:8000/docs

📡 API Endpoints

GET / — Service Info

Returns basic service metadata.

Response:

{
  "service": "Realtime Source Code Analyzer",
  "version": "1.0.0",
  "status": "running",
  "docs": "/docs",
  "health": "/health",
  "analyze_endpoint": "POST /analyze",
  "supported_languages": ["c", "cpp", "java", "javascript", "python"]
}

GET /health — Health Check

Used by uptime monitors and container orchestration.

Response:

{
  "status": "healthy",
  "service": "Realtime Source Code Analyzer",
  "version": "1.0.0",
  "supported_langs": ["c", "cpp", "java", "javascript", "python"]
}

POST /analyze — Analyze Source Code ⭐

Request Body:

{
  "language": "python",
  "code": "def add(a,b): return a+b",
  "context": "Optional description"
}

Supported Languages: python, javascript, java, cpp, c

Example Response:

{
  "status": "success",
  "language": "python",
  "score": 8.3,
  "total_lines": 1,
  "issues": [
    "Missing docstrings: 1 function(s) appear to lack documentation.",
    "Lines exceeding 79 characters: [1] (showing first 5)."
  ],
  "suggestions": [
    "Add docstrings to all functions using triple-quoted strings.",
    "Break long lines using Python's implicit line continuation or backslash.",
    "Run `flake8` or `pylint` for a full automated style report."
  ],
  "metadata": {
    "function_count": 1,
    "total_deductions": 1.7,
    "max_score": 10.0,
    "supported_lang": true
  }
}

🧪 Testing with curl

Health Check

curl http://localhost:8000/health

Analyze Code

curl -X POST http://localhost:8000/analyze \
  -H "Content-Type: application/json" \
  -d "{\"language\": \"python\", \"code\": \"def add(a,b): return a+b\"}"

Using the sample_input.json file

curl -X POST http://localhost:8000/analyze \
  -H "Content-Type: application/json" \
  -d @sample_input.json

🧪 Testing with Postman

  1. Open Postman → click New Request
  2. Set method to POST
  3. Enter URL: http://localhost:8000/analyze
  4. Go to Body → select raw → set format to JSON
  5. Paste this body:
{
  "language": "python",
  "code": "def add(a,b): return a+b"
}
  1. Click Send
  2. You will see the analysis response in the panel below

For Health Check:

  • Method: GET
  • URL: http://localhost:8000/health
  • No body required

🐳 Run with Docker

Build the image

docker build -t source-code-analyzer .

Run the container

docker run -p 8000:8000 source-code-analyzer

Access

http://localhost:8000/docs

☁️ Deploy to Render

  1. Push this repository to GitHub
  2. Go to render.comNew Web Service
  3. Connect your GitHub repository
  4. Render will auto-detect render.yaml and configure the service
  5. Click Deploy — your live URL will be ready in ~2 minutes
  6. Test your live endpoint:
    https://YOUR-SERVICE.onrender.com/docs
    https://YOUR-SERVICE.onrender.com/health
    

📊 What the Analyzer Checks

Check Description
Missing Docstrings Flags functions without documentation
Formatting Issues Trailing whitespace, long lines, mixed indentation
Duplicate Lines Detects copy-pasted repeated code
Long Functions Functions exceeding 20 lines are flagged
Naming Conventions Single-letter names, CamelCase functions (Python)
Complexity Counts branching keywords to estimate cyclomatic complexity
TODO Comments Flags unresolved TODO/FIXME/HACK markers

🧠 Scoring System

  • Start score: 10.0
  • Each detected issue deducts points (0.2 – 2.0 depending on severity)
  • Final score: clamped between 0.0 and 10.0
  • Score of 8.0+ = Good quality code ✅
  • Score of 5.0–7.9 = Needs improvement ⚠️
  • Score below 5.0 = Major issues detected ❌

📤 Upload to GitHub

# Initialize git (skip if already done)
git init

# Add all files
git add .

# Commit
git commit -m "feat: Realtime Source Code Analyzer - FastAPI inference service"

# Add remote (replace with your repo URL)
git remote add origin https://github.com/YOUR_USERNAME/realtime-source-code-analyzer.git

# Push
git push -u origin main

🏗️ Tech Stack

Technology Role
FastAPI Web framework & API server
Pydantic v2 Input validation & response schemas
Uvicorn ASGI server
Python 3.11 Runtime
Docker Containerization
Render Cloud deployment

📝 License

MIT — ScholarX Technologies © 2026


Built for ScholarX ML Engineer Internship — Task 2: Package a Model Inference Service

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors