Saturday, 6 December 2025

Auto review system using gemini api in php

 Auto review system using gemini api in php

Google AI key लो (free):

https://aistudio.google.com/app/apikey 

apna api key or prompt replace karo.

<?php

// 🔑 Gemini API Key
$apiKey = "YOUR-API-KEY";

// 1) Fetch available models
function listModels($apiKey) {
    $url = "https://generativelanguage.googleapis.com/v1beta/models?key=" . urlencode($apiKey);
    $ch = curl_init($url);
    curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_HTTPHEADER => ["Content-Type: application/json"],
        CURLOPT_TIMEOUT => 10
    ]);
    $resp = curl_exec($ch);
    if ($resp === false) {
        return null;
    }
    $json = json_decode($resp, true);
    if (!isset($json['models']) || !is_array($json['models'])) {
        return null;
    }
    return $json['models'];
}

// 2) Choose first model that supports generateContent
function pickModel($models) {
    foreach ($models as $m) {
        if (isset($m['supportedGenerationMethods'])
            && in_array("generateContent", $m['supportedGenerationMethods'])) {
            return $m['name'];  // model name like "models/gemini-2.5-flash"
        }
    }
    return null;
}

// 3) Use chosen model to review article
function reviewArticle($modelFullName, $title, $content, $apiKey) {
    // modelFullName example: "models/gemini-2.5-flash"
    $url = "https://generativelanguage.googleapis.com/v1beta/" . $modelFullName . ":generateContent?key=" . urlencode($apiKey);

   $systemPrompt = <<<EOT
You are a strict content-review and JSON-only generator for an automated article approval system.

Your rules:
- Analyze the given title + content.
- Return ONLY clean JSON.
- NO markdown, NO code fences, NO backticks, NO explanations.
- JSON MUST be valid, directly parsable, and must follow the exact structure below.

JSON STRUCTURE (strict):
{
  "allowed": true or false,
  "category": "short category string",
  "risk_score": 0-100,
  "violations": ["list of policy violations"]
}

--------------------------------------
ALLOWED CONTENT (DO NOT BLOCK):
--------------------------------------
These categories must ALWAYS be allowed, even if exaggerated or promotional:
- Business, finance, trading, investing
- Financial marketing or promotional claims
- Exaggerated or misleading profit claims (allowed)
- Pricing information
- Automation systems, trading bots, algorithmic trading
- API integration and technical tools
- Tutorials, guides, general education
- Motivational, spiritual, religious content
- Normal product or service descriptions

IMPORTANT:
Misleading or exaggerated financial statements MUST NOT cause rejection.
Instead return:
- allowed: true
- category: "Financial Exaggeration"
- risk_score: 1040
- violations: ["Financial exaggeration warning"] (optional)

--------------------------------------
REJECT ONLY IF TEXT CONTAINS:
--------------------------------------
These 9 critical banned categories MUST be blocked:
1. Illegal activity or instructions
2. Explicit adult/sexual content
3. Hate speech or targeted harassment
4. Violence, violent threats, or harm encouragement
5. Weapons, explosives, or illegal drugs
6. Political propaganda, election influence, political bias
7. Terrorism or extremist content
8. Serious medical misinformation that can cause harm
9. Fraud, scam instructions, or identity theft techniques

If ANY of these appear → allowed = false.

--------------------------------------
RISK SCORE RULE:
--------------------------------------
020  = Very Safe  
2040 = Mild Risk (still allowed)  
4070 = High Risk (allowed unless prohibited category)  
70100 = Reject (only if in banned category list)

--------------------------------------
FINAL RULE:
--------------------------------------
Unless the content violates the banned categories,
you MUST return allowed: true.

Return ONLY the clean JSON object.
EOT;



    $fullText = "TITLE: " . $title . "\n\nCONTENT:\n" . $content;

    $payload = [
        "contents" => [[
            "parts" => [[ "text" => $systemPrompt . "\n\n" . $fullText ]]
        ]]
    ];

    $ch = curl_init($url);
    curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_POST => true,
        CURLOPT_HTTPHEADER => ["Content-Type: application/json"],
        CURLOPT_POSTFIELDS => json_encode($payload),
        CURLOPT_TIMEOUT => 20
    ]);
    $resp = curl_exec($ch);
    if ($resp === false) {
        return ["error" => "cURL request failed"];
    }
    $json = json_decode($resp, true);
    if (!isset($json['candidates'][0]['content']['parts'][0]['text'])) {
        return ["error" => "No candidate text in API response", "raw" => $resp];
    }
    $out = json_decode($json['candidates'][0]['content']['parts'][0]['text'], true);
    if (!is_array($out)) {
        return ["error" => "Invalid JSON from model", "raw" => $json['candidates'][0]['content']['parts'][0]['text']];
    }
    return $out;
}

// --- Main flow ---
$error = "";
$result = null;
$modelName = null;

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $title = trim($_POST['title'] ?? "");
    $content = trim($_POST['content'] ?? "");

    if ($title === "" || $content === "") {
        $error = "Title और Content दोनों भरना ज़रूरी है.";
    } else {
        $models = listModels($apiKey);
        if (!$models) {
            $error = "Failed to fetch models list from Gemini API.";
        } else {
            $modelName = pickModel($models);
            if (!$modelName) {
                $error = "कोई suitable model नहीं मिला जो generateContent support करता हो.";
            } else {
                $result = reviewArticle($modelName, $title, $content, $apiKey);
            }
        }
    }
}
?>
<!doctype html>
<html>
<head>
  <meta charset="utf-8">
  <title>Auto-Model Detect Review</title>
  <style>
    body { font-family: Arial; background: #f4f6f8; padding: 30px; }
    .box { max-width:800px; margin:auto; background:#fff; padding:20px; border-radius:8px; box-shadow:0 4px 12px rgba(0,0,0,0.1); }
    textarea, input[type=text] { width:100%; padding:8px; margin-top:8px; border:1px solid #ccc; border-radius:4px; }
    button { padding:10px 16px; margin-top:12px; background:#111; color:#fff; border:none; border-radius:4px; cursor:pointer; }
    .badge { display:inline-block; padding:6px 12px; border-radius:4px; color:#fff; font-weight:bold; }
    .good { background:#28a745; }
    .bad  { background:#dc3545; }
    .debug { background:#eee; padding:10px; margin-top:10px; white-space:pre-wrap; }
  </style>
</head>
<body>
  <div class="box">
    <h2>Auto-Model Detect + Content Review</h2>
    <form method="post">
      <label>Title</label>
      <input type="text" name="title" required value="<?= htmlspecialchars($_POST['title'] ?? '') ?>">
      <label>Content</label>
      <textarea name="content" rows="8" required><?= htmlspecialchars($_POST['content'] ?? '') ?></textarea>
      <button type="submit">Review Article</button>
    </form>

    <?php if ($error): ?>
      <div class="debug"><b>Error:</b> <?= htmlspecialchars($error) ?></div>
    <?php endif; ?>

    <?php if ($result): ?>
      <hr>
      <h3>Result (using model: <code><?= htmlspecialchars($modelName) ?></code>)</h3>
      <?php if (!empty($result['allowed'])): ?>
        <div class="badge good">✅ APPROVED</div>
      <?php else: ?>
        <div class="badge bad">❌ REJECTED</div>
      <?php endif; ?>
      <div style="margin-top:12px;">
        <b>Category:</b> <?= htmlspecialchars($result['category'] ?? '') ?><br>
        <b>Risk Score:</b> <?= htmlspecialchars($result['risk_score'] ?? '') ?>/100
      </div>
      <div style="margin-top:12px;">
        <b>Violations:</b>
        <?php if (!empty($result['violations']) && is_array($result['violations'])): ?>
          <ul>
            <?php foreach ($result['violations'] as $v): ?>
              <li><?= htmlspecialchars($v) ?></li>
            <?php endforeach; ?>
          </ul>
        <?php else: ?>
          <div>None reported.</div>
        <?php endif; ?>
      </div>
      <div class="debug"><b>Full JSON Output:</b><br><?= htmlspecialchars(json_encode($result, JSON_PRETTY_PRINT|JSON_UNESCAPED_UNICODE)) ?></div>
    <?php endif; ?>
  </div>
</body>
</html>