Spaces:
Running
Running
Upload 15 files
Browse filesFiles changed (6)
- app.py+78
- example_api.pyAdded+89
- models/aifinder_trained.pt+2-2
- requirements.txt+1
- static/index.html+626-43
- train.pyAdded+305
1234567892 unmodified lines1213141516171 unmodified line19202122232471 unmodified lines96979899100101"""AIFinder API ServerServes classification and training endpoints for the frontend."""import osimport sysimport jsonimport joblib2 unmodified linesimport torch.nn as nnfrom flask import Flask, request, jsonify, send_from_directoryfrom flask_cors import CORSfrom config import MODEL_DIRfrom model import AIFinderNet1 unmodified lineapp = Flask(__name__, static_folder="static", static_url_path="")CORS(app)pipeline = Noneprovider_enc = None71 unmodified lines)@app.route("/api/correct", methods=["POST"])def correct():"""Train on a corrected example."""12345678910111213142 unmodified lines17181920212223241 unmodified line26272829303132333471 unmodified lines106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179"""AIFinder API ServerServes classification and training endpoints for the frontend.Public API:POST /v1/classify β classify text, returns top-N provider predictions.No API key required. Rate-limited to 60 requests/minute per IP."""import osimport reimport sysimport jsonimport joblib2 unmodified linesimport torch.nn as nnfrom flask import Flask, request, jsonify, send_from_directoryfrom flask_cors import CORSfrom flask_limiter import Limiterfrom flask_limiter.util import get_remote_addressfrom config import MODEL_DIRfrom model import AIFinderNet1 unmodified lineapp = Flask(__name__, static_folder="static", static_url_path="")CORS(app)limiter = Limiter(get_remote_address, app=app, default_limits=[])DEFAULT_TOP_N = 5pipeline = Noneprovider_enc = None71 unmodified lines)def _strip_think_tags(text):"""Remove <think>β¦</think> (and <thinking>β¦</thinking>) blocks from input."""text = re.sub(r"<think(?:ing)?>.*?</think(?:ing)?>", "", text, flags=re.DOTALL)return text.strip()@app.route("/v1/classify", methods=["POST"])@limiter.limit("60/minute")def v1_classify():"""Public API β classify text and return top-N provider predictions.Request JSON:text (str): The text to classify. Any <think>/<thinking> tags will bestripped automatically before classification.top_n (int): Number of results to return (default: 5).Response JSON:provider (str): Best-matching provider name.confidence (float): Confidence % for the top provider.top_providers (list): List of {name, confidence} dicts.Rate limit: 60 requests per minute per IP. No API key required.NOTE: If the text you are classifying was produced by a model that emits<think> or <thinking> blocks, you should strip those tags BEFOREsending the text. This endpoint does it for you automatically, butdoing it on your side avoids wasting bytes on the wire."""data = request.get_json(silent=True)if not data or "text" not in data:return jsonify({"error": "Request body must be JSON with a 'text' field."}), 400raw_text = data["text"]text = _strip_think_tags(raw_text)top_n = data.get("top_n", DEFAULT_TOP_N)if not isinstance(top_n, int) or top_n < 1:top_n = DEFAULT_TOP_Nif len(text) < 20:return jsonify({"error": "Text too short (minimum 20 characters after stripping think tags)."}), 400X = pipeline.transform([text])X_t = torch.tensor(X.toarray(), dtype=torch.float32).to(device)with torch.no_grad():prov_logits = net(X_t)prov_proba = torch.softmax(prov_logits.float(), dim=1)[0].cpu().numpy()top_idxs = np.argsort(prov_proba)[::-1][:top_n]top_providers = [{"name": provider_enc.inverse_transform([i])[0],"confidence": round(float(prov_proba[i] * 100), 2),}for i in top_idxs]return jsonify({"provider": top_providers[0]["name"],"confidence": top_providers[0]["confidence"],"top_providers": top_providers,})@app.route("/api/correct", methods=["POST"])def correct():"""Train on a corrected example."""
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889#!/usr/bin/env python3"""Example: Call the AIFinder public API to classify text.
Usage: python example_api.py
Requirements: pip install requests
IMPORTANT β Strip <think>/<thinking> tags! Many reasoning models wrap chain-of-thought in <think>β¦</think> or <thinking>β¦</thinking> blocks. These tags confuse the classifier because they are NOT part of the model's actual output style. The API strips them automatically, but you should also strip them on your side to avoid sending unnecessary data.
API details: POST /v1/classify No API key required. Rate limit: 60 requests/minute per IP."""
import reimport jsonimport requests
# Change this to your server URL (local or HuggingFace Space).API_URL = "https://huggingface.co/spaces/CompactAI/AIFinder/v1/classify"
# Number of top results to return (default on server is 5).TOP_N = 5
EXAMPLE_TEXT = """\I'd be happy to help you understand how neural networks work!
Neural networks are computational models inspired by the human brain. They consist of layers of interconnected nodes (neurons) that process information. Here's a breakdown:
1. **Input Layer**: Receives the raw data2. **Hidden Layers**: Process and transform the data through weighted connections3. **Output Layer**: Produces the final prediction
Each connection has a weight, and each neuron has a bias. During training, the network adjusts these weights using backpropagation to minimize the difference between predicted and actual outputs.
The key insight is that by stacking multiple layers, neural networks can learn increasingly abstract representations of data, enabling them to solve complex tasks like image recognition, natural language processing, and more.
Would you like me to dive deeper into any specific aspect?"""
def strip_think_tags(text: str) -> str: """Remove <think>β¦</think> and <thinking>β¦</thinking> blocks.""" return re.sub( r"<think(?:ing)?>.*?</think(?:ing)?>", "", text, flags=re.DOTALL ).strip()
def classify(text: str, top_n: int = TOP_N) -> dict: """Send text to the AIFinder API and return the JSON response.""" cleaned = strip_think_tags(text) resp = requests.post( API_URL, json={"text": cleaned, "top_n": top_n}, timeout=30, ) resp.raise_for_status() return resp.json()
def main(): print("AIFinder API Example") print("=" * 50) print(f"Endpoint : {API_URL}") print(f"Top-N : {TOP_N}") print()
result = classify(EXAMPLE_TEXT)
print(f"Best match : {result['provider']} ({result['confidence']:.1f}%)") print() print("Top providers:") for entry in result["top_providers"]: bar = "β" * int(entry["confidence"] / 5) + "β" * ( 20 - int(entry["confidence"] / 5) ) print(f" {entry['name']:.<25s} {entry['confidence']:5.1f}% {bar}")
if __name__ == "__main__": main()123version https://git-lfs.github.com/spec/v1oid sha256:87706447863f7cae3a6295d06ecbfb35333b2f05f670d5b47133a76757b6377fsize 165033273123version https://git-lfs.github.com/spec/v1oid sha256:daeb1c62c7ca34fd45b697fb0240608555aa1617e45baa8d81620a69272bbaafsize 165033081
9 unmodified lines1011129 unmodified lineshuggingface_hub>=0.23.0flask>=3.0flask-cors>=4.09 unmodified lines101112139 unmodified lineshuggingface_hub>=0.23.0flask>=3.0flask-cors>=4.0flask-limiter>=3.0
398 unmodified lines39940040140240340440526 unmodified lines432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490245 unmodified lines736737738739740741398 unmodified linesmargin-bottom: 1rem;opacity: 0.5;}@media (max-width: 600px) {.container {padding: 1rem;26 unmodified lines<p class="tagline">Identify which AI provider generated a response</p></header><div class="status-indicator"><span class="status-dot" id="statusDot"></span><span id="statusText">Connecting to API...</span></div><div class="card"><div class="card-label">Paste AI Response</div><textarea id="inputText" placeholder="Paste an AI response here to identify which provider generated it..."></textarea></div><div class="btn-group"><button class="btn btn-primary" id="classifyBtn" disabled><span id="classifyBtnText">Classify</span></button><button class="btn btn-secondary" id="clearBtn">Clear</button></div><div class="results" id="results"><div class="card"><div class="card-label">Result</div><div class="result-main"><span class="result-provider" id="resultProvider">-</span><span class="result-confidence" id="resultConfidence">-</span></div><div class="result-bar"><div class="result-bar-fill" id="resultBar" style="width: 0%"></div></div><ul class="result-list" id="resultList"></ul></div><div class="correction" id="correction"><div class="correction-title">Wrong? Correct the provider to train the model:</div><select id="providerSelect"></select><button class="btn btn-primary" id="trainBtn">Train & Save</button></div></div><div class="stats" id="stats" style="display: none;"><div class="stat"><div class="stat-value" id="correctionsCount">0</div><div class="stat-label">Corrections</div></div><div class="stat"><div class="stat-value" id="sessionCount">0</div><div class="stat-label">Session</div></div></div><div class="actions" id="actions" style="display: none;"><button class="btn btn-secondary" id="exportBtn">Export Trained Model</button><button class="btn btn-secondary" id="resetBtn">Reset Training</button></div><div class="footer"><p>AIFinder — Train on corrections to improve accuracy</p><p style="margin-top: 0.5rem;">245 unmodified lines}});checkStatus();</script></body>398 unmodified lines39940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765826 unmodified lines6856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006245 unmodified lines1252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324398 unmodified linesmargin-bottom: 1rem;opacity: 0.5;}/* ββ Tabs ββ */.tabs {display: flex;gap: 0;margin-bottom: 2rem;border-bottom: 1px solid var(--border);}.tab {padding: 0.75rem 1.5rem;font-family: 'Outfit', sans-serif;font-size: 0.9rem;font-weight: 500;color: var(--text-muted);background: none;border: none;border-bottom: 2px solid transparent;cursor: pointer;transition: all 0.2s ease;}.tab:hover {color: var(--text-secondary);}.tab.active {color: var(--accent);border-bottom-color: var(--accent);}.tab-content {display: none;}.tab-content.active {display: block;animation: fadeIn 0.3s ease;}/* ββ API Docs ββ */.docs-section {margin-bottom: 2rem;}.docs-section h2 {font-size: 1.25rem;font-weight: 600;margin-bottom: 0.75rem;color: var(--text-primary);}.docs-section h3 {font-size: 1rem;font-weight: 500;margin-top: 1.25rem;margin-bottom: 0.5rem;color: var(--text-secondary);}.docs-section p {color: var(--text-secondary);font-size: 0.9rem;margin-bottom: 0.75rem;line-height: 1.7;}.docs-endpoint {display: inline-flex;align-items: center;gap: 0.5rem;background: var(--bg-tertiary);border: 1px solid var(--border);border-radius: 6px;padding: 0.5rem 1rem;margin-bottom: 1rem;font-family: 'JetBrains Mono', monospace;font-size: 0.85rem;}.docs-method {color: var(--success);font-weight: 600;}.docs-path {color: var(--text-primary);}.docs-badge {display: inline-block;font-size: 0.7rem;font-weight: 600;text-transform: uppercase;letter-spacing: 0.05em;padding: 0.2rem 0.6rem;border-radius: 4px;margin-left: 0.5rem;}.docs-badge.free {background: var(--success-muted);color: var(--success);}.docs-badge.limit {background: var(--accent-muted);color: var(--accent-hover);}.docs-code-block {position: relative;background: var(--bg-tertiary);border: 1px solid var(--border);border-radius: 8px;margin-bottom: 1rem;overflow: hidden;}.docs-code-header {display: flex;align-items: center;justify-content: space-between;padding: 0.5rem 1rem;background: var(--bg-elevated);border-bottom: 1px solid var(--border);font-size: 0.75rem;color: var(--text-muted);text-transform: uppercase;letter-spacing: 0.05em;}.docs-copy-btn {background: none;border: 1px solid var(--border);border-radius: 4px;color: var(--text-muted);font-size: 0.7rem;padding: 0.2rem 0.5rem;cursor: pointer;font-family: 'Outfit', sans-serif;transition: all 0.2s ease;}.docs-copy-btn:hover {color: var(--text-primary);border-color: var(--border-light);}.docs-code-block pre {padding: 1rem;overflow-x: auto;font-family: 'JetBrains Mono', monospace;font-size: 0.8rem;line-height: 1.6;color: var(--text-primary);margin: 0;}.docs-table {width: 100%;border-collapse: collapse;font-size: 0.85rem;margin-bottom: 1rem;}.docs-table th {text-align: left;padding: 0.6rem 0.75rem;background: var(--bg-elevated);color: var(--text-secondary);font-weight: 500;border-bottom: 1px solid var(--border);font-size: 0.75rem;text-transform: uppercase;letter-spacing: 0.05em;}.docs-table td {padding: 0.6rem 0.75rem;border-bottom: 1px solid var(--border);color: var(--text-secondary);}.docs-table tr:last-child td {border-bottom: none;}.docs-table code {font-family: 'JetBrains Mono', monospace;font-size: 0.8rem;background: var(--bg-tertiary);padding: 0.15rem 0.4rem;border-radius: 3px;color: var(--accent-hover);}.docs-warning {background: rgba(232, 93, 4, 0.08);border: 1px solid var(--accent-muted);border-radius: 8px;padding: 1rem 1.25rem;margin-bottom: 1rem;font-size: 0.85rem;color: var(--text-secondary);line-height: 1.7;}.docs-warning strong {color: var(--accent-hover);}.docs-inline-code {font-family: 'JetBrains Mono', monospace;font-size: 0.8rem;background: var(--bg-tertiary);padding: 0.15rem 0.4rem;border-radius: 3px;color: var(--accent-hover);}.docs-try-it {background: var(--bg-tertiary);border: 1px solid var(--border);border-radius: 8px;padding: 1.25rem;margin-top: 1rem;}.docs-try-it textarea {min-height: 100px;margin-bottom: 0.75rem;}.docs-try-output {background: var(--bg-primary);border: 1px solid var(--border);border-radius: 6px;padding: 1rem;font-family: 'JetBrains Mono', monospace;font-size: 0.8rem;color: var(--text-secondary);white-space: pre-wrap;word-break: break-word;max-height: 300px;overflow-y: auto;display: none;}.docs-try-output.visible {display: block;animation: fadeIn 0.3s ease;}@media (max-width: 600px) {.container {padding: 1rem;26 unmodified lines<p class="tagline">Identify which AI provider generated a response</p></header><div class="tabs"><button class="tab active" data-tab="classify">Classify</button><button class="tab" data-tab="docs">API Docs</button></div><!-- βββ Classify Tab βββ --><div class="tab-content active" id="tab-classify"><div class="status-indicator"><span class="status-dot" id="statusDot"></span><span id="statusText">Connecting to API...</span></div><div class="card"><div class="card-label">Paste AI Response</div><textarea id="inputText" placeholder="Paste an AI response here to identify which provider generated it..."></textarea></div><div class="btn-group"><button class="btn btn-primary" id="classifyBtn" disabled><span id="classifyBtnText">Classify</span></button><button class="btn btn-secondary" id="clearBtn">Clear</button></div><div class="results" id="results"><div class="card"><div class="card-label">Result</div><div class="result-main"><span class="result-provider" id="resultProvider">-</span><span class="result-confidence" id="resultConfidence">-</span></div><div class="result-bar"><div class="result-bar-fill" id="resultBar" style="width: 0%"></div></div><ul class="result-list" id="resultList"></ul></div><div class="correction" id="correction"><div class="correction-title">Wrong? Correct the provider to train the model:</div><select id="providerSelect"></select><button class="btn btn-primary" id="trainBtn">Train & Save</button></div></div><div class="stats" id="stats" style="display: none;"><div class="stat"><div class="stat-value" id="correctionsCount">0</div><div class="stat-label">Corrections</div></div><div class="stat"><div class="stat-value" id="sessionCount">0</div><div class="stat-label">Session</div></div></div><div class="actions" id="actions" style="display: none;"><button class="btn btn-secondary" id="exportBtn">Export Trained Model</button><button class="btn btn-secondary" id="resetBtn">Reset Training</button></div></div><!-- βββ API Docs Tab βββ --><div class="tab-content" id="tab-docs"><div class="docs-section"><h2>Public Classification API</h2><p>AIFinder exposes a free, public endpoint for programmatic classification.No API key required.</p><div><div class="docs-endpoint"><span class="docs-method">POST</span><span class="docs-path">/v1/classify</span></div><span class="docs-badge free">No API Key</span><span class="docs-badge limit">60 req/min</span></div></div><!-- ββ Request ββ --><div class="docs-section"><h2>Request</h2><p>Send a JSON body with <span class="docs-inline-code">Content-Type: application/json</span>.</p><table class="docs-table"><thead><tr><th>Field</th><th>Type</th><th>Required</th><th>Description</th></tr></thead><tbody><tr><td><code>text</code></td><td>string</td><td>Yes</td><td>The AI-generated text to classify (min 20 chars)</td></tr><tr><td><code>top_n</code></td><td>integer</td><td>No</td><td>Number of results to return (default: <strong>5</strong>)</td></tr></tbody></table><div class="docs-warning"><strong>β οΈ Strip thought tags!</strong><br>Many reasoning models wrap chain-of-thought in<span class="docs-inline-code"><think>β¦</think></span> or<span class="docs-inline-code"><thinking>β¦</thinking></span> blocks.These confuse the classifier. The API strips them automatically, but you shouldremove them on your side too to save bandwidth.</div></div><!-- ββ Response ββ --><div class="docs-section"><h2>Response</h2><div class="docs-code-block"><div class="docs-code-header"><span>JSON</span><button class="docs-copy-btn" onclick="copyCode(this)">Copy</button></div><pre>{"provider": "Anthropic","confidence": 87.42,"top_providers": [{ "name": "Anthropic", "confidence": 87.42 },{ "name": "OpenAI", "confidence": 6.15 },{ "name": "Google", "confidence": 3.28 },{ "name": "xAI", "confidence": 1.74 },{ "name": "DeepSeek", "confidence": 0.89 }]}</pre></div><table class="docs-table"><thead><tr><th>Field</th><th>Type</th><th>Description</th></tr></thead><tbody><tr><td><code>provider</code></td><td>string</td><td>Best-matching provider name</td></tr><tr><td><code>confidence</code></td><td>float</td><td>Confidence % for the top provider</td></tr><tr><td><code>top_providers</code></td><td>array</td><td>Ranked list of <code>{ name, confidence }</code> objects</td></tr></tbody></table></div><!-- ββ Errors ββ --><div class="docs-section"><h2>Errors</h2><table class="docs-table"><thead><tr><th>Status</th><th>Meaning</th></tr></thead><tbody><tr><td><code>400</code></td><td>Missing <code>text</code> field or text shorter than 20 characters</td></tr><tr><td><code>429</code></td><td>Rate limit exceeded (60 requests/minute per IP)</td></tr></tbody></table></div><!-- ββ Code Examples ββ --><div class="docs-section"><h2>Code Examples</h2><h3>cURL</h3><div class="docs-code-block"><div class="docs-code-header"><span>Bash</span><button class="docs-copy-btn" onclick="copyCode(this)">Copy</button></div><pre>curl -X POST https://huggingface.co/spaces/CompactAI/AIFinder/v1/classify \-H "Content-Type: application/json" \-d '{"text": "I would be happy to help you with that! Here is a detailed explanation of how neural networks work...","top_n": 5}'</pre></div><h3>Python</h3><div class="docs-code-block"><div class="docs-code-header"><span>Python</span><button class="docs-copy-btn" onclick="copyCode(this)">Copy</button></div><pre>import reimport requestsAPI_URL = "https://huggingface.co/spaces/CompactAI/AIFinder/v1/classify"def strip_think_tags(text):"""Remove <think>/<thinking> blocks before classifying."""return re.sub(r"<think(?:ing)?>.*?</think(?:ing)?>","", text, flags=re.DOTALL).strip()text = """I'd be happy to help! Neural networks arecomputational models inspired by the human brain..."""# Strip thought tags first (the API does this too,# but saves bandwidth to do it client-side)cleaned = strip_think_tags(text)response = requests.post(API_URL, json={"text": cleaned,"top_n": 5})data = response.json()print(f"Provider: {data['provider']} ({data['confidence']:.1f}%)")for p in data["top_providers"]:print(f" {p['name']:<20s} {p['confidence']:5.1f}%")</pre></div><h3>JavaScript (fetch)</h3><div class="docs-code-block"><div class="docs-code-header"><span>JavaScript</span><button class="docs-copy-btn" onclick="copyCode(this)">Copy</button></div><pre>const API_URL = "https://huggingface.co/spaces/CompactAI/AIFinder/v1/classify";function stripThinkTags(text) {return text.replace(/<think(?:ing)?>[\s\S]*?<\/think(?:ing)?>/g, "").trim();}async function classify(text, topN = 5) {const cleaned = stripThinkTags(text);const res = await fetch(API_URL, {method: "POST",headers: { "Content-Type": "application/json" },body: JSON.stringify({ text: cleaned, top_n: topN })});return res.json();}// Usageclassify("I'd be happy to help you understand...").then(data => {console.log(`Provider: ${data.provider} (${data.confidence}%)`);data.top_providers.forEach(p =>console.log(` ${p.name}: ${p.confidence}%`));});</pre></div><h3>Node.js</h3><div class="docs-code-block"><div class="docs-code-header"><span>JavaScript (Node)</span><button class="docs-copy-btn" onclick="copyCode(this)">Copy</button></div><pre>const API_URL = "https://huggingface.co/spaces/CompactAI/AIFinder/v1/classify";async function classify(text, topN = 5) {const cleaned = text.replace(/<think(?:ing)?>[\s\S]*?<\/think(?:ing)?>/g, "").trim();const res = await fetch(API_URL, {method: "POST",headers: { "Content-Type": "application/json" },body: JSON.stringify({ text: cleaned, top_n: topN })});if (!res.ok) {const err = await res.json();throw new Error(err.error || `HTTP ${res.status}`);}return res.json();}// Example(async () => {const result = await classify("Let me think about this step by step...",3);console.log(result);})();</pre></div></div><!-- ββ Try It ββ --><div class="docs-section"><h2>Try It</h2><p>Test the API right here β paste any AI-generated text and hit Send.</p><div class="docs-try-it"><textarea id="docsTestInput" placeholder="Paste AI-generated text here..."></textarea><div class="btn-group"><button class="btn btn-primary" id="docsTestBtn">Send Request</button></div><div class="docs-try-output" id="docsTestOutput"></div></div></div><!-- ββ Providers ββ --><div class="docs-section"><h2>Supported Providers</h2><p>The classifier currently supports these providers:</p><div id="docsProviderList" style="display: flex; flex-wrap: wrap; gap: 0.5rem; margin-top: 0.5rem;"></div></div></div><div class="footer"><p>AIFinder — Train on corrections to improve accuracy</p><p style="margin-top: 0.5rem;">245 unmodified lines}});// ββ Tab switching ββdocument.querySelectorAll('.tab').forEach(tab => {tab.addEventListener('click', () => {document.querySelectorAll('.tab').forEach(t => t.classList.remove('active'));document.querySelectorAll('.tab-content').forEach(c => c.classList.remove('active'));tab.classList.add('active');document.getElementById('tab-' + tab.dataset.tab).classList.add('active');});});// ββ Copy button for code blocks ββfunction copyCode(btn) {const pre = btn.closest('.docs-code-block').querySelector('pre');navigator.clipboard.writeText(pre.textContent).then(() => {btn.textContent = 'Copied!';setTimeout(() => { btn.textContent = 'Copy'; }, 1500);});}// ββ Docs: populate provider badges ββfunction populateDocsProviders() {const list = document.getElementById('docsProviderList');if (!list || !providers.length) return;list.innerHTML = providers.map(p =>`<span class="docs-inline-code" style="padding:0.3rem 0.75rem;">${p}</span>`).join('');}// ββ Docs: "Try It" live tester ββconst docsTestBtn = document.getElementById('docsTestBtn');const docsTestInput = document.getElementById('docsTestInput');const docsTestOutput = document.getElementById('docsTestOutput');if (docsTestBtn) {docsTestBtn.addEventListener('click', async () => {const text = docsTestInput.value.trim();if (text.length < 20) {docsTestOutput.textContent = '{"error": "Text too short (minimum 20 characters)"}';docsTestOutput.classList.add('visible');return;}docsTestBtn.disabled = true;docsTestBtn.innerHTML = '<span class="loading"></span>';try {const res = await fetch(`${API_BASE}/v1/classify`, {method: 'POST',headers: { 'Content-Type': 'application/json' },body: JSON.stringify({ text, top_n: 5 })});const data = await res.json();docsTestOutput.textContent = JSON.stringify(data, null, 2);} catch (e) {docsTestOutput.textContent = `{"error": "${e.message}"}`;}docsTestOutput.classList.add('visible');docsTestBtn.disabled = false;docsTestBtn.textContent = 'Send Request';});}// Hook provider list population into the existing load flowconst _origLoadProviders = loadProviders;loadProviders = async function() {await _origLoadProviders();populateDocsProviders();};checkStatus();</script></body>
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305"""AIFinder Training ScriptLoads data, trains a two-headed GPU classifier, reports metrics, and saves the model.
Usage: python3 train.py"""
import osimport sysimport timeimport joblibimport numpy as npimport torchimport torch.nn as nnfrom torch.utils.data import TensorDataset, DataLoaderfrom sklearn.model_selection import train_test_splitfrom sklearn.metrics import classification_reportfrom sklearn.preprocessing import LabelEncoderfrom sklearn.utils.class_weight import compute_class_weight
from config import ( MODEL_DIR, TEST_SIZE, RANDOM_STATE, HIDDEN_DIM, EMBED_DIM, DROPOUT, BATCH_SIZE, EPOCHS, LEARNING_RATE, WEIGHT_DECAY, EARLY_STOP_PATIENCE,)from data_loader import load_all_datafrom features import FeaturePipelinefrom model import AIFinderNet
def _log(msg, t0=None): """Print a timestamped log message, optionally with elapsed time.""" ts = time.strftime("%H:%M:%S") if t0 is not None: elapsed = time.time() - t0 print(f" [{ts}] {msg} ({elapsed:.1f}s)") else: print(f" [{ts}] {msg}")
def main(): t_start = time.time()
print("=" * 60) print("AIFinder Training - Provider Classification") print("=" * 60)
# ββ GPU check ββββββββββββββββββββββββββββββββββββββββββββββ if torch.cuda.is_available(): device = torch.device("cuda") gpu_name = torch.cuda.get_device_name(0) gpu_mem = torch.cuda.get_device_properties(0).total_memory / 1024**3 _log(f"GPU: {gpu_name} ({gpu_mem:.1f} GB)") else: device = torch.device("cpu") _log("No GPU available, using CPU")
# ββ Load data ββββββββββββββββββββββββββββββββββββββββββββββ _log("Starting data load...") t0 = time.time() texts, providers, models, _is_ai = load_all_data() _log("Data load complete", t0)
if len(texts) < 100: print("ERROR: Not enough data loaded. Check dataset access.") sys.exit(1)
# ββ Encode labels ββββββββββββββββββββββββββββββββββββββββββ _log("Encoding labels...") t0 = time.time() provider_enc = LabelEncoder() provider_labels = provider_enc.fit_transform(providers) num_providers = len(provider_enc.classes_) _log(f"Labels encoded β {num_providers} providers", t0)
# ββ Train/test split βββββββββββββββββββββββββββββββββββββββ _log("Splitting train/test...") t0 = time.time() indices = np.arange(len(texts)) train_idx, test_idx = train_test_split( indices, test_size=TEST_SIZE, random_state=RANDOM_STATE, stratify=provider_labels, ) train_texts = [texts[i] for i in train_idx] test_texts = [texts[i] for i in test_idx] _log(f"Split: {len(train_texts)} train / {len(test_texts)} test", t0)
# ββ Build features βββββββββββββββββββββββββββββββββββββββββ _log("Building feature pipeline (fit on train)...") t0 = time.time() pipeline = FeaturePipeline() X_train = pipeline.fit_transform(train_texts) _log(f"Train features: {X_train.shape}", t0)
_log("Transforming test set...") t0 = time.time() X_test = pipeline.transform(test_texts) _log(f"Test features: {X_test.shape}", t0)
input_dim = X_train.shape[1]
# ββ Move to device βββββββββββββββββββββββββββββββββββββββββ _log(f"Moving data to {device}...") t0 = time.time() X_train_t = torch.tensor(X_train.toarray(), dtype=torch.float32).to(device) X_test_t = torch.tensor(X_test.toarray(), dtype=torch.float32).to(device) y_prov_train = torch.tensor(provider_labels[train_idx], dtype=torch.long).to(device) y_prov_test = torch.tensor(provider_labels[test_idx], dtype=torch.long).to(device) if device.type == "cuda": mem_used = torch.cuda.memory_allocated() / 1024**3 _log(f"GPU memory used: {mem_used:.2f} GB", t0) else: _log(f"Data on {device}", t0)
# ββ DataLoaders ββββββββββββββββββββββββββββββββββββββββββββ batch_size = min(BATCH_SIZE, 512) if device.type == "cpu" else BATCH_SIZE train_ds = TensorDataset(X_train_t, y_prov_train) train_loader = DataLoader(train_ds, batch_size=batch_size, shuffle=True) val_ds = TensorDataset(X_test_t, y_prov_test) val_loader = DataLoader(val_ds, batch_size=batch_size, shuffle=False)
# ββ Model ββββοΏ½οΏ½οΏ½βββββββββββββββββββββββββββββββββββββββββββββ _log("Building model...") net = AIFinderNet( input_dim=input_dim, num_providers=num_providers, hidden_dim=HIDDEN_DIM, embed_dim=EMBED_DIM, dropout=DROPOUT, ).to(device) n_params = sum(p.numel() for p in net.parameters()) _log(f"Model: {n_params:,} parameters")
# ββ Class-weighted loss ββββββββββββββββββββββββββββββββββββ prov_weights = compute_class_weight( "balanced", classes=np.arange(num_providers), y=provider_labels[train_idx] ) prov_criterion = nn.CrossEntropyLoss( weight=torch.tensor(prov_weights, dtype=torch.float32).to(device) )
# ββ Optimizer + scheduler ββββββββββββββββββββββββββββββββββ optimizer = torch.optim.AdamW( net.parameters(), lr=LEARNING_RATE, weight_decay=WEIGHT_DECAY ) scheduler = torch.optim.lr_scheduler.OneCycleLR( optimizer, max_lr=LEARNING_RATE, epochs=EPOCHS, steps_per_epoch=len(train_loader), ) use_amp = device.type == "cuda" scaler = torch.amp.GradScaler() if use_amp else None
# ββ Training loop ββββββββββββββββββββββββββββββββββββββββββ _log( f"Training for {EPOCHS} epochs, batch_size={batch_size}, " f"early_stop_patience={EARLY_STOP_PATIENCE}..." ) t0 = time.time()
best_val_loss = float("inf") best_state = None patience_counter = 0
for epoch in range(EPOCHS): # ββ Train phase βββββββββββββββββββββββββββββββββββββββ net.train() epoch_loss = 0.0 n_batches = 0
for batch_X, batch_prov in train_loader: optimizer.zero_grad(set_to_none=True) if use_amp: with torch.amp.autocast(device_type="cuda"): prov_logits = net(batch_X) loss = prov_criterion(prov_logits, batch_prov) scaler.scale(loss).backward() scaler.unscale_(optimizer) torch.nn.utils.clip_grad_norm_(net.parameters(), max_norm=1.0) scaler.step(optimizer) scaler.update() else: prov_logits = net(batch_X) loss = prov_criterion(prov_logits, batch_prov) loss.backward() torch.nn.utils.clip_grad_norm_(net.parameters(), max_norm=1.0) optimizer.step() scheduler.step() epoch_loss += loss.item() n_batches += 1
avg_train_loss = epoch_loss / n_batches
# ββ Validation phase ββββββββββββββββββββββββββββββββββ net.eval() val_loss = 0.0 val_batches = 0 with torch.no_grad(): for batch_X, batch_prov in val_loader: prov_logits = net(batch_X) loss = prov_criterion(prov_logits, batch_prov) val_loss += loss.item() val_batches += 1 avg_val_loss = val_loss / val_batches
# ββ Early stopping check ββββββββββββββββββββββββββββββ if avg_val_loss < best_val_loss: best_val_loss = avg_val_loss best_state = {k: v.clone() for k, v in net.state_dict().items()} patience_counter = 0 else: patience_counter += 1
# ββ Logging βββββββββββββββββββββββββββββββββββββββββββ if (epoch + 1) % 5 == 0 or epoch == 0: lr = scheduler.get_last_lr()[0] marker = " *" if patience_counter == 0 else "" _log( f"Epoch {epoch + 1:>3d}/{EPOCHS} " f"train={avg_train_loss:.4f} " f"val={avg_val_loss:.4f} " f"lr={lr:.2e}{marker}" )
if patience_counter >= EARLY_STOP_PATIENCE: _log( f"Early stopping at epoch {epoch + 1} " f"(best val_loss={best_val_loss:.4f})" ) break
# Restore best weights if best_state is not None: net.load_state_dict(best_state) _log(f"Restored best weights (val_loss={best_val_loss:.4f})")
_log("Training complete", t0)
# ββ Evaluate βββββββββββββββββββββββββββββββββββββββββββββββ _log("Evaluating...") net.eval() with torch.no_grad(): prov_logits = net(X_test_t)
prov_preds = prov_logits.argmax(dim=1).cpu().numpy() prov_true = y_prov_test.cpu().numpy()
print("\n === Provider Classification ===") print( classification_report( prov_true, prov_preds, target_names=provider_enc.classes_, zero_division=0, ) )
# ββ Save βββββββββββββββββββββββββββββββββββββββββββββββββββ _log(f"Saving to {MODEL_DIR}/ ...") t0 = time.time() os.makedirs(MODEL_DIR, exist_ok=True)
checkpoint = { "input_dim": input_dim, "num_providers": num_providers, "hidden_dim": HIDDEN_DIM, "embed_dim": EMBED_DIM, "dropout": DROPOUT, "state_dict": net.state_dict(), } torch.save(checkpoint, os.path.join(MODEL_DIR, "classifier.pt")) _log(" Saved classifier.pt")
joblib.dump(pipeline, os.path.join(MODEL_DIR, "feature_pipeline.joblib")) _log(" Saved feature_pipeline.joblib") joblib.dump(provider_enc, os.path.join(MODEL_DIR, "provider_enc.joblib")) _log(" Saved provider_enc.joblib")
_log("All artifacts saved", t0)
elapsed = time.time() - t_start if device.type == "cuda": mem_peak = torch.cuda.max_memory_allocated() / 1024**3 print(f"\n{'=' * 60}") print(f"Training complete in {elapsed:.1f}s (peak GPU mem: {mem_peak:.2f} GB)") print(f"{'=' * 60}") else: print(f"\n{'=' * 60}") print(f"Training complete in {elapsed:.1f}s") print(f"{'=' * 60}")
if __name__ == "__main__": main()app.py+78
example_api.pyAdded+89
models/aifinder_trained.pt+2-2
requirements.txt+1
static/index.html+626-43
train.pyAdded+305