Spaces:
Running
Running
Upload 8 files
Browse filesFiles changed (9)
- .gitattributes+1
- app.py+98-162
- config.py+77-32
- inference.pyAdded+52
- models/1773449581 (1).pngAdded
- models/enc_4provider.joblibAdded+3
- models/pipeline_4provider.joblibAdded+3
- models/rf_4provider.joblibAdded+3
- templates/index.htmlAdded+1373
32 unmodified lines3334353632 unmodified lines*.zip filter=lfs diff=lfs merge=lfs -text*.zst filter=lfs diff=lfs merge=lfs -text*tfevents* filter=lfs diff=lfs merge=lfs -textmodels/1773449581[[:space:]](1).png filter=lfs diff=lfs merge=lfs -text12345672345671213891016171811121314151617242518192720212922233124252627333435363728293031323334414243444546474849505152535455565758596061626364656667686970717273747576777879808182838435363738394041424344458687468990919293949596979899100101102103104105106474849505111052535455565758596061626364118119120121122123124125126127128129130131132133134135136656667686970143717273747576771491501511521531541557879808182831578485861598716116216316416588899091927 unmodified lines1001011021791801811821831841851861871881891901031041051061071921931941081091101111961971981991121131142012021151161171181192042052062072082091201211222111231241251261272131281292151301311321331342202212222231351361371381392252261402281411421431441451461471481491502331511521531541551561572391581591602422431611621631641651661671681691701711721731741751761771781791 unmodified line181182183251184185186187188"""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.AIFinder Flask APIServes the trained sklearn ensemble via the AIFinder inference class."""
import osimport reimport sysimport json
import joblibimport numpy as npimport torchimport torch.nn as nnfrom flask import Flask, request, jsonify, send_from_directoryfrom sklearn.ensemble import RandomForestClassifierfrom flask import Flask, jsonify, request, send_from_directory, render_templatefrom flask_cors import CORSfrom flask_limiter import Limiterfrom flask_limiter.util import get_remote_address
from config import MODEL_DIRfrom model import AIFinderNetfrom features import FeaturePipelinefrom inference import AIFinder
app = Flask(__name__, static_folder="static", static_url_path="")app = Flask(__name__)CORS(app)limiter = Limiter(get_remote_address, app=app, default_limits=[])limiter = Limiter(get_remote_address, app=app)
DEFAULT_TOP_N = 5finder: AIFinder | None = Nonecommunity_finder: AIFinder | None = Noneusing_community = False
pipeline = Noneprovider_enc = Nonenet = Nonedevice = Nonecheckpoint = NoneDEFAULT_TOP_N = 4COMMUNITY_DIR = os.path.join(MODEL_DIR, "community")CORRECTIONS_FILE = os.path.join(COMMUNITY_DIR, "corrections.joblib")corrections: list[dict] = []
def load_models(): global pipeline, provider_enc, net, device, checkpoint
pipeline = joblib.load(os.path.join(MODEL_DIR, "feature_pipeline.joblib")) provider_enc = joblib.load(os.path.join(MODEL_DIR, "provider_enc.joblib"))
checkpoint = torch.load( os.path.join(MODEL_DIR, "classifier.pt"), map_location="cpu", weights_only=True, ) device = torch.device("cuda" if torch.cuda.is_available() else "cpu") net = AIFinderNet( input_dim=checkpoint["input_dim"], num_providers=checkpoint["num_providers"], hidden_dim=checkpoint["hidden_dim"], embed_dim=checkpoint["embed_dim"], dropout=checkpoint["dropout"], ).to(device) net.load_state_dict(checkpoint["state_dict"], strict=False) net.eval()
@app.route("/")def index(): return send_from_directory("static", "index.html")
@app.route("/api/providers", methods=["GET"])def get_providers(): """Return list of available providers.""" return jsonify({"providers": sorted(provider_enc.classes_.tolist())})
@app.route("/api/classify", methods=["POST"])def classify(): """Classify text and return provider predictions.""" data = request.json text = data.get("text", "")
if len(text) < 20: return jsonify({"error": "Text too short (minimum 20 characters)"}), 400
X = pipeline.transform([text]) X_t = torch.tensor(X.toarray(), dtype=torch.float32).to(device) global finder, community_finder, corrections finder = AIFinder(model_dir=MODEL_DIR) os.makedirs(COMMUNITY_DIR, exist_ok=True) if os.path.exists(CORRECTIONS_FILE): corrections = joblib.load(CORRECTIONS_FILE) if os.path.exists(os.path.join(COMMUNITY_DIR, "rf_4provider.joblib")): try: community_finder = AIFinder(model_dir=COMMUNITY_DIR) except Exception: community_finder = None
with torch.no_grad(): prov_logits = net(X_t)
prov_proba = torch.softmax(prov_logits.float(), dim=1)[0].cpu().numpy()
top_prov_idxs = np.argsort(prov_proba)[::-1][:5] top_providers = [ { "name": provider_enc.inverse_transform([i])[0], "confidence": float(prov_proba[i] * 100), } for i in top_prov_idxs ]
return jsonify( { "provider": top_providers[0]["name"], "confidence": top_providers[0]["confidence"], "top_providers": top_providers, } )def _active_finder(): return community_finder if using_community and community_finder else finder
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("/")def index(): return render_template("index.html")
@app.route("/api/classify", methods=["POST"])@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 be stripped 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 BEFORE sending the text. This endpoint does it for you automatically, but doing 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."}), 400
raw_text = data["text"] text = _strip_think_tags(raw_text) top_n = data.get("top_n", DEFAULT_TOP_N) af = _active_finder() top_n = min(data.get("top_n", DEFAULT_TOP_N), len(af.le.classes_))
if not isinstance(top_n, int) or top_n < 1: top_n = DEFAULT_TOP_N
if len(text) < 20: return jsonify({"error": "Text too short (minimum 20 characters after stripping think tags)."}), 400
X = pipeline.transform([text]) X_t = torch.tensor(X.toarray(), dtype=torch.float32).to(device)
with torch.no_grad(): prov_logits = net(X_t) return jsonify( { "error": "Text too short (minimum 20 characters after stripping think tags)." } ), 400
prov_proba = torch.softmax(prov_logits.float(), dim=1)[0].cpu().numpy() proba = af.predict_proba(text) sorted_providers = sorted(proba.items(), key=lambda x: x[1], reverse=True)[:top_n]
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 {"name": name, "confidence": round(float(conf * 100), 2)} for name, conf in sorted_providers ]
return jsonify(7 unmodified lines
@app.route("/api/correct", methods=["POST"])def correct(): """Train on a corrected example.""" data = request.json text = data.get("text", "") correct_provider = data.get("correct_provider", "")
if not text or not correct_provider: return jsonify({"error": "Missing text or correct_provider"}), 400
try: prov_idx = provider_enc.transform([correct_provider])[0] except ValueError as e: return jsonify({"error": f"Unknown provider: {e}"}), 400 global community_finder data = request.get_json(silent=True) if not data or "text" not in data or "correct_provider" not in data: return jsonify({"error": "Need 'text' and 'correct_provider'."}), 400
X = pipeline.transform([text]) X_t = torch.tensor(X.toarray(), dtype=torch.float32).to(device) y_prov = torch.tensor([prov_idx], dtype=torch.long).to(device) provider = data["correct_provider"] if provider not in list(finder.le.classes_): return jsonify({"error": f"Unknown provider: {provider}"}), 400
net.train() for module in net.modules(): if isinstance(module, nn.modules.batchnorm._BatchNorm): module.eval() text = _strip_think_tags(data["text"]) corrections.append({"text": text, "provider": provider})
optimizer = torch.optim.AdamW(net.parameters(), lr=1e-4, weight_decay=1e-4) optimizer.zero_grad(set_to_none=True) texts = [c["text"] for c in corrections] providers = [c["provider"] for c in corrections] X = finder.pipeline.transform(texts) y = finder.le.transform(providers)
prov_criterion = nn.CrossEntropyLoss() prov_logits = net(X_t) loss = prov_criterion(prov_logits, y_prov) loss.backward() torch.nn.utils.clip_grad_norm_(net.parameters(), max_norm=1.0) optimizer.step() rf = RandomForestClassifier(n_estimators=100, random_state=42, n_jobs=-1) rf.fit(X, y)
net.eval() joblib.dump([rf], os.path.join(COMMUNITY_DIR, "rf_4provider.joblib")) joblib.dump(finder.pipeline, os.path.join(COMMUNITY_DIR, "pipeline_4provider.joblib")) joblib.dump(finder.le, os.path.join(COMMUNITY_DIR, "enc_4provider.joblib")) joblib.dump(corrections, CORRECTIONS_FILE)
checkpoint["state_dict"] = net.state_dict() community_finder = AIFinder(model_dir=COMMUNITY_DIR)
return jsonify({"success": True, "loss": float(loss.item())}) return jsonify({"status": "ok", "loss": 0.0, "corrections": len(corrections)})
@app.route("/api/save", methods=["POST"])def save_model(): """Save the current model state to a file for export.""" global checkpoint data = request.json filename = data.get("filename", "aifinder_model.pt") if community_finder is None: return jsonify({"error": "No community model trained yet."}), 400 filename = "community_rf_4provider.joblib" return jsonify({"status": "ok", "filename": filename})
save_path = os.path.join(MODEL_DIR, filename) torch.save(checkpoint, save_path)
return jsonify({"success": True, "filename": filename})@app.route("/api/toggle_community", methods=["POST"])def toggle_community(): global using_community data = request.get_json(silent=True) or {} using_community = bool(data.get("enabled", not using_community)) return jsonify({"using_community": using_community, "available": community_finder is not None})
@app.route("/models/<filename>")def download_model(filename): """Download exported model file.""" if filename.startswith("community_"): return send_from_directory(COMMUNITY_DIR, filename.replace("community_", "", 1)) return send_from_directory(MODEL_DIR, filename)
@app.route("/api/status", methods=["GET"])def status(): """Check if models are loaded.""" af = _active_finder() return jsonify( { "loaded": net is not None, "device": str(device) if device else None, "loaded": af is not None, "device": "cpu", "providers": list(af.le.classes_) if af else [], "num_providers": len(af.le.classes_) if af else 0, "using_community": using_community, "community_available": community_finder is not None, "corrections_count": len(corrections), } )
@app.route("/api/providers", methods=["GET"])def providers(): return jsonify( { "providers": list(finder.le.classes_) if finder else [], } )
1 unmodified lineif __name__ == "__main__": print("Loading models...") load_models() print(f"Ready on {device}") print( f"Ready on cpu β {len(finder.le.classes_)} providers: " f"{', '.join(finder.le.classes_)}" ) app.run(host="0.0.0.0", port=7860)14 unmodified lines15161718192018192021222324252627282930313233343527363738313940414243444546473548493850515253545556575842596061466263496451656653675556686970717273747559767762787980818283848586876788899091929394959697989910072731011021031041051061071081091101111121131141151168011711811912012112212312487881251261271281291301311321331341359394136137138139140141989910010110210310410514214314414514614714814915014 unmodified linesDATASET_REGISTRY = [ # Anthropic ("TeichAI/claude-4.5-opus-high-reasoning-250x", "Anthropic", "Claude 4.5 Opus", {}), ("TeichAI/claude-sonnet-4.5-high-reasoning-250x", "Anthropic", "Claude Sonnet 4.5", {}), ("Roman1111111/claude-opus-4.6-10000x", "Anthropic", "Claude Opus 4.6", {"max_samples": 1500}),
( "TeichAI/claude-sonnet-4.5-high-reasoning-250x", "Anthropic", "Claude Sonnet 4.5", {}, ), ( "Roman1111111/claude-opus-4.6-10000x", "Anthropic", "Claude Opus 4.6", {"max_samples": 1500}, ), # OpenAI ("TeichAI/gpt-5.2-high-reasoning-250x", "OpenAI", "GPT-5.2", {}), ("TeichAI/gpt-5.1-high-reasoning-1000x", "OpenAI", "GPT-5.1", {}), ("TeichAI/gpt-5.1-codex-max-1000x", "OpenAI", "GPT-5.1 Codex Max", {}), ("TeichAI/gpt-5-codex-250x", "OpenAI", "GPT-5 Codex", {}), ("TeichAI/gpt-5-codex-1000x", "OpenAI", "GPT-5 Codex", {}),
# Google ("TeichAI/gemini-3-pro-preview-high-reasoning-1000x", "Google", "Gemini 3 Pro", {}), ("TeichAI/gemini-3-pro-preview-high-reasoning-250x", "Google", "Gemini 3 Pro", {}), ("TeichAI/gemini-2.5-flash-11000x", "Google", "Gemini 2.5 Flash", {"max_samples": 1500}), ( "TeichAI/gemini-2.5-flash-11000x", "Google", "Gemini 2.5 Flash", {"max_samples": 1500}, ), ("TeichAI/Gemini-3-Flash-Preview-VIBE", "Google", "Gemini 3 Flash", {}), ("TeichAI/gemini-3-flash-preview-1000x", "Google", "Gemini 3 Flash", {}), ("TeichAI/gemini-3-flash-preview-complex-1000x", "Google", "Gemini 3 Flash", {}),
# xAI ("TeichAI/brainstorm-v3.1-grok-4-fast-200x", "xAI", "Grok 4 Fast", {}), ("TeichAI/sherlock-thinking-alpha-11000x", "xAI", "Grok 4.1 Fast", {"max_samples": 1500}), ( "TeichAI/sherlock-thinking-alpha-11000x", "xAI", "Grok 4.1 Fast", {"max_samples": 1500}, ), ("TeichAI/sherlock-dash-alpha-1000x", "xAI", "Grok 4.1 Fast", {}), ("TeichAI/sherlock-think-alpha-1000x", "xAI", "Grok 4.1 Fast", {}), ("TeichAI/grok-code-fast-1-1000x", "xAI", "Grok Code Fast 1", {}),
# MoonshotAI ("TeichAI/kimi-k2-thinking-250x", "MoonshotAI", "Kimi K2", {}), ("TeichAI/kimi-k2-thinking-1000x", "MoonshotAI", "Kimi K2", {}),
# Mistral ("TeichAI/mistral-small-creative-500x", "Mistral", "Mistral Small", {}),
# MiniMax ("TeichAI/MiniMax-M2.1-Code-SFT", "MiniMax", "MiniMax M2.1", {}), ("TeichAI/MiniMax-M2.1-Code-SFT", "MiniMax", "MiniMax M2.1", {"max_samples": 1500}), ("TeichAI/convo-v1", "MiniMax", "MiniMax M2.1", {}),
# StepFun ("TeichAI/Step-3.5-Flash-2600x", "StepFun", "Step 3.5 Flash", {"max_samples": 1500}),
( "TeichAI/Step-3.5-Flash-2600x", "StepFun", "Step 3.5 Flash", {"max_samples": 1500}, ), # Zhipu ("TeichAI/Pony-Alpha-15k", "Zhipu", "GLM-5", {"max_samples": 1500}),
# DeepSeek (TeichAI) ("TeichAI/deepseek-v3.2-speciale-1000x", "DeepSeek", "DeepSeek V3.2 Speciale", {}), ("TeichAI/deepseek-v3.2-speciale-openr1-math-3k", "DeepSeek", "DeepSeek V3.2 Speciale", {"max_samples": 1500}), ( "TeichAI/deepseek-v3.2-speciale-openr1-math-3k", "DeepSeek", "DeepSeek V3.2 Speciale", {"max_samples": 1500}, ),]
# DeepSeek (a-m-team) β different format, handled separatelyDEEPSEEK_AM_DATASETS = [ ("a-m-team/AM-DeepSeek-R1-Distilled-1.4M", "DeepSeek", "DeepSeek R1", {"name": "am_0.9M_sample_1k", "max_samples": 1000}), ( "a-m-team/AM-DeepSeek-R1-Distilled-1.4M", "DeepSeek", "DeepSeek R1", {"name": "am_0.9M", "max_samples": 1000}, ),]
# Conversational datasets disabledCONVERSATIONAL_DATASETS = []
# --- All providers and models ---PROVIDERS = [ "Anthropic", "OpenAI", "Google", "xAI", "MoonshotAI", "Mistral", "MiniMax", "StepFun", "Zhipu", "DeepSeek" "Anthropic", "OpenAI", "Google", "xAI", "MoonshotAI", "Mistral", "MiniMax", "StepFun", "Zhipu", "DeepSeek",]
# --- Feature parameters ---TFIDF_WORD_PARAMS = { "analyzer": "word", "ngram_range": (1, 2), "max_features": 20000, "max_features": 20, "sublinear_tf": True, "min_df": 3, "max_df": 0.7,}
TFIDF_CHAR_PARAMS = { "analyzer": "char_wb", "ngram_range": (3, 5), "max_features": 20000, "ngram_range": (2, 4), "max_features": 20, "sublinear_tf": True, "min_df": 3, "max_df": 0.7, "smooth_idf": True,}
# Equal samples per providerMAX_SAMPLES_PER_PROVIDER = 1000
# --- Train/test split ---TEST_SIZE = 0.2# --- Train/val/test split ---TEST_SIZE = 0.15VAL_SIZE = 0.10RANDOM_STATE = 42
# --- Neural Network ---HIDDEN_DIM = 1024EMBED_DIM = 256DROPOUT = 0.3BATCH_SIZE = 2048EPOCHS = 50EARLY_STOP_PATIENCE = 8LEARNING_RATE = 1e-3WEIGHT_DECAY = 1e-4HIDDEN_DIM = 256EMBED_DIM = 128DROPOUT = 0.7BATCH_SIZE = 128EPOCHS = 80EARLY_STOP_PATIENCE = 25LEARNING_RATE = 3e-5WEIGHT_DECAY = 8e-2LABEL_SMOOTHING = 0.312345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152"""AIFinder Inference ModuleLoad the trained model and predict AI provider"""
import joblibimport numpy as np
from config import MODEL_DIR
class AIFinder: def __init__(self, model_dir=MODEL_DIR): self.models = joblib.load(f"{model_dir}/rf_4provider.joblib") self.pipeline = joblib.load(f"{model_dir}/pipeline_4provider.joblib") self.le = joblib.load(f"{model_dir}/enc_4provider.joblib")
def predict(self, text): """Predict the provider for a given text""" X = self.pipeline.transform([text]) proba = np.mean([m.predict_proba(X) for m in self.models], axis=0) pred_idx = np.argmax(proba[0]) return self.le.classes_[pred_idx]
def predict_proba(self, text): """Get prediction probabilities""" X = self.pipeline.transform([text]) proba = np.mean([m.predict_proba(X) for m in self.models], axis=0) return dict(zip(self.le.classes_, proba[0]))
def predict_with_confidence(self, text): """Predict with confidence score""" proba = self.predict_proba(text) provider = max(proba, key=proba.get) confidence = proba[provider] return provider, confidence
if __name__ == "__main__": finder = AIFinder()
test_texts = [ "AI is like a really smart robot helper.", "Yes, coding is one of my stronger skills!", "A lot, depending on what you need.", ]
for text in test_texts: provider, conf = finder.predict_with_confidence(text) print(f"Text: {text[:50]}...") print(f"Provider: {provider} (confidence: {conf:.2f})") print()123version https://git-lfs.github.com/spec/v1oid sha256:9125a24e56ba5808ed41a62f5d321134e5cc6b23b862679ea15f09ea6dc64985size 471123version https://git-lfs.github.com/spec/v1oid sha256:86b1810b0c76194f98e785c24cecb911948f21f3410cf57d43e74def8f967b20size 5015123version https://git-lfs.github.com/spec/v1oid sha256:c24c29e35c11b789f9b1eb5dc562f68d0621a963b598c0b391aaad0b02162a73size 4412175412345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>AIFinder - Identify AI Responses</title> <style> @import url('https://fonts.googleapis.com/css2?family=JetBrains+Mono:wght@400;500;600&family=Outfit:wght@300;400;500;600;700&display=swap'); * { margin: 0; padding: 0; box-sizing: border-box; } :root { --bg-primary: #0d0d0d; --bg-secondary: #171717; --bg-tertiary: #1f1f1f; --bg-elevated: #262626; --text-primary: #f5f5f5; --text-secondary: #a3a3a3; --text-muted: #737373; --accent: #e85d04; --accent-hover: #f48c06; --accent-muted: #9c4300; --success: #22c55e; --success-muted: #166534; --border: #333333; --border-light: #404040; } body { font-family: 'Outfit', -apple-system, sans-serif; background: var(--bg-primary); color: var(--text-primary); min-height: 100vh; line-height: 1.6; } .container { max-width: 900px; margin: 0 auto; padding: 2rem 1.5rem; } header { text-align: center; margin-bottom: 3rem; padding-top: 1rem; } .logo { font-size: 2.5rem; font-weight: 700; letter-spacing: -0.05em; margin-bottom: 0.5rem; } .logo span { color: var(--accent); } .tagline { color: var(--text-secondary); font-size: 1rem; font-weight: 300; } .card { background: var(--bg-secondary); border: 1px solid var(--border); border-radius: 12px; padding: 1.5rem; margin-bottom: 1.5rem; transition: border-color 0.2s ease; } .card:focus-within { border-color: var(--border-light); } .card-label { font-size: 0.75rem; text-transform: uppercase; letter-spacing: 0.1em; color: var(--text-muted); margin-bottom: 0.75rem; font-weight: 500; } textarea { width: 100%; background: var(--bg-tertiary); border: 1px solid var(--border); border-radius: 8px; padding: 1rem; color: var(--text-primary); font-family: 'JetBrains Mono', monospace; font-size: 0.875rem; resize: vertical; min-height: 180px; transition: border-color 0.2s ease; } textarea:focus { outline: none; border-color: var(--accent-muted); } textarea::placeholder { color: var(--text-muted); } .btn { display: inline-flex; align-items: center; justify-content: center; gap: 0.5rem; padding: 0.75rem 1.5rem; border-radius: 8px; font-family: 'Outfit', sans-serif; font-size: 0.9rem; font-weight: 500; cursor: pointer; transition: all 0.2s ease; border: none; } .btn-primary { background: var(--accent); color: white; } .btn-primary:hover:not(:disabled) { background: var(--accent-hover); } .btn-primary:disabled { opacity: 0.5; cursor: not-allowed; } .btn-secondary { background: var(--bg-tertiary); color: var(--text-primary); border: 1px solid var(--border); } .btn-secondary:hover:not(:disabled) { background: var(--bg-elevated); border-color: var(--border-light); } .btn-group { display: flex; gap: 0.75rem; flex-wrap: wrap; } .results { display: none; } .results.visible { display: block; animation: fadeIn 0.3s ease; } @keyframes fadeIn { from { opacity: 0; transform: translateY(10px); } to { opacity: 1; transform: translateY(0); } } .result-main { display: flex; align-items: center; justify-content: space-between; padding: 1.25rem; background: var(--bg-tertiary); border-radius: 8px; margin-bottom: 1rem; } .result-provider { font-size: 1.5rem; font-weight: 600; } .result-confidence { font-size: 1.25rem; font-weight: 500; color: var(--accent); } .result-bar { height: 8px; background: var(--bg-elevated); border-radius: 4px; margin-bottom: 1rem; overflow: hidden; } .result-bar-fill { height: 100%; background: var(--accent); border-radius: 4px; transition: width 0.5s ease; } .result-list { list-style: none; } .result-item { display: flex; align-items: center; justify-content: space-between; padding: 0.75rem 0; border-bottom: 1px solid var(--border); } .result-item:last-child { border-bottom: none; } .result-name { font-weight: 500; } .result-percent { font-family: 'JetBrains Mono', monospace; color: var(--text-secondary); font-size: 0.875rem; } .correction { display: none; margin-top: 1.5rem; padding-top: 1.5rem; border-top: 1px solid var(--border); } .correction.visible { display: block; animation: fadeIn 0.3s ease; } .correction-title { font-size: 0.875rem; font-weight: 500; margin-bottom: 0.75rem; color: var(--text-secondary); } select { width: 100%; padding: 0.75rem 1rem; background: var(--bg-tertiary); border: 1px solid var(--border); border-radius: 8px; color: var(--text-primary); font-family: 'Outfit', sans-serif; font-size: 0.9rem; margin-bottom: 0.75rem; cursor: pointer; } select:focus { outline: none; border-color: var(--accent-muted); } .stats { display: flex; gap: 1.5rem; margin-bottom: 1.5rem; flex-wrap: wrap; } .stat { background: var(--bg-secondary); border: 1px solid var(--border); border-radius: 8px; padding: 1rem 1.25rem; flex: 1; min-width: 120px; } .stat-value { font-size: 1.5rem; font-weight: 600; color: var(--accent); } .stat-label { font-size: 0.75rem; color: var(--text-muted); text-transform: uppercase; letter-spacing: 0.05em; } .actions { display: flex; gap: 0.75rem; margin-top: 1rem; } .toast { position: fixed; bottom: 2rem; right: 2rem; background: var(--bg-elevated); border: 1px solid var(--border); border-radius: 8px; padding: 1rem 1.5rem; color: var(--text-primary); font-size: 0.9rem; opacity: 0; transform: translateY(20px); transition: all 0.3s ease; z-index: 1000; } .toast.visible { opacity: 1; transform: translateY(0); } .toast.success { border-color: var(--success-muted); } .footer { text-align: center; margin-top: 3rem; padding: 1.5rem; color: var(--text-muted); font-size: 0.8rem; } .footer a { color: var(--text-secondary); text-decoration: none; } .footer a:hover { color: var(--accent); } .loading { display: inline-block; width: 16px; height: 16px; border: 2px solid var(--text-muted); border-top-color: var(--accent); border-radius: 50%; animation: spin 0.8s linear infinite; } @keyframes spin { to { transform: rotate(360deg); } } .status-indicator { display: inline-flex; align-items: center; gap: 0.5rem; font-size: 0.8rem; color: var(--text-muted); margin-bottom: 1rem; } .status-dot { width: 8px; height: 8px; border-radius: 50%; background: var(--success); } .status-dot.loading { background: var(--accent); animation: pulse 1s ease infinite; } @keyframes pulse { 0%, 100% { opacity: 1; } 50% { opacity: 0.5; } } .empty-state { text-align: center; padding: 3rem 1rem; color: var(--text-muted); } .empty-state-icon { font-size: 3rem; margin-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; } .logo { font-size: 2rem; } .btn-group { flex-direction: column; } .btn { width: 100%; } .result-main { flex-direction: column; gap: 0.5rem; text-align: center; } } </style></head><body> <div class="container"> <header> <div class="logo">AI<span>Finder</span></div> <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="communityBtn" style="display:none;">Use Community Model</button> <button class="btn btn-secondary" id="resetBtn">Reset Training</button> </div>
<div id="communityWarning" style="display:none; margin-top:1rem; background:rgba(232,93,4,0.12); border:1px solid var(--accent-muted); border-radius:8px; padding:1rem 1.25rem; font-size:0.85rem; color:var(--text-secondary); line-height:1.7;"> β οΈ <strong style="color:var(--accent-hover);">Community Model Active</strong> β This is a community-trained version. It could be <strong style="color:var(--accent-hover);">VERY wrong</strong>. Results may be unreliable. Use at your own risk. </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 should remove 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 requests
API_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;"> Want to contribute? Test this and post to the <a href="https://huggingface.co/spaces" target="_blank">HuggingFace Spaces Community</a> if you want it merged! </p> </div> </div> <div class="toast" id="toast"></div> <script> const API_BASE = window.location.hostname === 'localhost' || window.location.hostname === '127.0.0.1' ? 'http://localhost:7860' : ''; let providers = []; let correctionsCount = 0; let sessionCorrections = 0; const inputText = document.getElementById('inputText'); const classifyBtn = document.getElementById('classifyBtn'); const classifyBtnText = document.getElementById('classifyBtnText'); const clearBtn = document.getElementById('clearBtn'); const results = document.getElementById('results'); const resultProvider = document.getElementById('resultProvider'); const resultConfidence = document.getElementById('resultConfidence'); const resultBar = document.getElementById('resultBar'); const resultList = document.getElementById('resultList'); const correction = document.getElementById('correction'); const providerSelect = document.getElementById('providerSelect'); const trainBtn = document.getElementById('trainBtn'); const stats = document.getElementById('stats'); const correctionsCountEl = document.getElementById('correctionsCount'); const sessionCountEl = document.getElementById('sessionCount'); const actions = document.getElementById('actions'); const exportBtn = document.getElementById('exportBtn'); const communityBtn = document.getElementById('communityBtn'); const communityWarning = document.getElementById('communityWarning'); const resetBtn = document.getElementById('resetBtn'); const toast = document.getElementById('toast'); const statusDot = document.getElementById('statusDot'); const statusText = document.getElementById('statusText'); let usingCommunity = false; function showToast(message, type = 'info') { toast.textContent = message; toast.className = 'toast visible' + (type === 'success' ? ' success' : ''); setTimeout(() => { toast.classList.remove('visible'); }, 3000); } async function checkStatus() { try { const res = await fetch(`${API_BASE}/api/status`); const data = await res.json(); if (data.loaded) { statusDot.classList.remove('loading'); statusText.textContent = data.using_community ? 'Ready β Community Model (cpu)' : `Ready (${data.device})`; classifyBtn.disabled = false; usingCommunity = data.using_community; updateCommunityUI(data.community_available); if (data.corrections_count > 0) { correctionsCount = data.corrections_count; correctionsCountEl.textContent = correctionsCount; stats.style.display = 'flex'; actions.style.display = 'flex'; } loadProviders(); loadStats(); } else { setTimeout(checkStatus, 1000); } } catch (e) { statusDot.classList.add('loading'); statusText.textContent = 'Connecting to API...'; setTimeout(checkStatus, 2000); } } function updateCommunityUI(available) { if (available) { communityBtn.style.display = ''; communityBtn.textContent = usingCommunity ? 'Use Official Model' : 'Use Community Model'; communityWarning.style.display = usingCommunity ? 'block' : 'none'; actions.style.display = 'flex'; } else { communityBtn.style.display = 'none'; communityWarning.style.display = 'none'; } } async function loadProviders() { const res = await fetch(`${API_BASE}/api/providers`); const data = await res.json(); providers = data.providers; providerSelect.innerHTML = providers.map(p => `<option value="${p}">${p}</option>` ).join(''); } function loadStats() { const saved = localStorage.getItem('aifinder_corrections'); if (saved) { correctionsCount = parseInt(saved, 10); correctionsCountEl.textContent = correctionsCount; stats.style.display = 'flex'; actions.style.display = 'flex'; } sessionCountEl.textContent = sessionCorrections; } function saveStats() { localStorage.setItem('aifinder_corrections', correctionsCount.toString()); } async function classify() { const text = inputText.value.trim(); if (text.length < 20) { showToast('Text must be at least 20 characters'); return; } classifyBtn.disabled = true; classifyBtnText.innerHTML = '<span class="loading"></span>'; try { const res = await fetch(`${API_BASE}/api/classify`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ text }) }); if (!res.ok) { throw new Error('Classification failed'); } const data = await res.json(); showResults(data); } catch (e) { showToast('Error: ' + e.message); } finally { classifyBtn.disabled = false; classifyBtnText.textContent = 'Classify'; } } function showResults(data) { resultProvider.textContent = data.provider; resultConfidence.textContent = data.confidence.toFixed(1) + '%'; resultBar.style.width = data.confidence + '%'; resultList.innerHTML = data.top_providers.map(p => ` <li class="result-item"> <span class="result-name">${p.name}</span> <span class="result-percent">${p.confidence.toFixed(1)}%</span> </li> `).join(''); providerSelect.value = data.provider; results.classList.add('visible'); correction.classList.add('visible'); if (correctionsCount > 0 || sessionCorrections > 0) { stats.style.display = 'flex'; actions.style.display = 'flex'; } } async function train() { const text = inputText.value.trim(); const correctProvider = providerSelect.value; trainBtn.disabled = true; trainBtn.innerHTML = '<span class="loading"></span>'; try { const res = await fetch(`${API_BASE}/api/correct`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ text, correct_provider: correctProvider }) }); if (!res.ok) { throw new Error('Training failed'); } const data = await res.json(); correctionsCount = data.corrections || correctionsCount + 1; sessionCorrections++; saveStats(); correctionsCountEl.textContent = correctionsCount; sessionCountEl.textContent = sessionCorrections; showToast('Correction saved & community model retrained!', 'success'); stats.style.display = 'flex'; actions.style.display = 'flex'; updateCommunityUI(true); classify(); } catch (e) { showToast('Error: ' + e.message); } finally { trainBtn.disabled = false; trainBtn.textContent = 'Train & Save'; } } async function exportModel() { exportBtn.disabled = true; exportBtn.innerHTML = '<span class="loading"></span>'; try { const res = await fetch(`${API_BASE}/api/save`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ filename: 'aifinder_trained.pt' }) }); if (!res.ok) { throw new Error('Save failed'); } const data = await res.json(); const link = document.createElement('a'); link.href = `${API_BASE}/models/${data.filename}`; link.download = data.filename; link.click(); showToast('Model exported!', 'success'); } catch (e) { showToast('Error: ' + e.message); } finally { exportBtn.disabled = false; exportBtn.textContent = 'Export Trained Model'; } } function resetTraining() { if (!confirm('Reset all training data? This cannot be undone.')) { return; } correctionsCount = 0; sessionCorrections = 0; localStorage.removeItem('aifinder_corrections'); correctionsCountEl.textContent = '0'; sessionCountEl.textContent = '0'; stats.style.display = 'none'; actions.style.display = 'none'; showToast('Training data reset'); } classifyBtn.addEventListener('click', classify); clearBtn.addEventListener('click', () => { inputText.value = ''; results.classList.remove('visible'); correction.classList.remove('visible'); }); trainBtn.addEventListener('click', train); exportBtn.addEventListener('click', exportModel); resetBtn.addEventListener('click', resetTraining); communityBtn.addEventListener('click', async () => { communityBtn.disabled = true; try { const res = await fetch(`${API_BASE}/api/toggle_community`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ enabled: !usingCommunity }) }); const data = await res.json(); usingCommunity = data.using_community; updateCommunityUI(data.available); statusText.textContent = usingCommunity ? 'Ready β Community Model (cpu)' : 'Ready (cpu)'; showToast(usingCommunity ? 'Switched to community model' : 'Switched to official model', 'success'); } catch (e) { showToast('Error: ' + e.message); } finally { communityBtn.disabled = false; } }); inputText.addEventListener('keydown', (e) => { if (e.key === 'Enter' && e.ctrlKey) { classify(); } }); // ββ 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 flow const _origLoadProviders = loadProviders; loadProviders = async function() { await _origLoadProviders(); populateDocsProviders(); };
checkStatus(); </script></body></html>.gitattributes+1
app.py+98-162
config.py+77-32
inference.pyAdded+52
models/1773449581 (1).pngAdded
.png)
Large File Pointer Details
- SHA256: c4040e312991db4fff1cb3aa18184f4b7477878e5642666748b13b98d60815db
- Pointer size: 132 Bytes
- Size of remote file: 2.08 MB
models/enc_4provider.joblibAdded+3
models/pipeline_4provider.joblibAdded+3
models/rf_4provider.joblibAdded+3
templates/index.htmlAdded+1373