File size: 5,815 Bytes
dd095ab | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 | # -*- coding: utf-8 -*-
"""
DEVIPUTRA AI // HUGGING FACE SPACES ZERO-GPU INFERENCE ENGINE
Full-stack Gradio + Cyberpunk HUD integration with Fine-Tuned Multilingual BERT (RTX-5050).
"""
# IMPORTANT: ZeroGPU requires importing spaces before torch or CUDA initialization
try:
import spaces
except ImportError:
spaces = None
import os
import sys
import base64
from fastapi import FastAPI, Request
from fastapi.responses import JSONResponse
import gradio as gr
import torch
# Ensure src modules are discoverable
current_dir = os.path.dirname(os.path.abspath(__file__))
if current_dir not in sys.path:
sys.path.insert(0, current_dir)
from src.predict import HateSpeechPredictor
print("⚡ [Hugging Face Spaces] Initializing DEVIPUTRA AI Predictor...")
predictor = HateSpeechPredictor(models_dir=os.path.join(current_dir, 'models'))
# Prediction Function for Gradio
def analyze_text(text: str):
if not text or not text.strip():
return "Please input some text to analyze.", "Standby", {}
result = predictor.predict(text)
prediction = result.get('prediction', 'Normal')
context = result.get('context')
explanation = ""
if context and context.get('reason'):
explanation = f"\n\n🔍 Context Reason: {context.get('reason')}"
status_message = f"Verdict: {prediction.upper()} {explanation}"
if 'scores' in result and result['scores']:
confidences = result['scores']
elif prediction == 'Hate Speech':
confidences = {'Hate Speech': 0.98, 'Offensive': 0.015, 'Normal': 0.005}
elif prediction == 'Offensive':
confidences = {'Offensive': 0.92, 'Hate Speech': 0.05, 'Normal': 0.03}
else:
confidences = {'Normal': 0.96, 'Offensive': 0.03, 'Hate Speech': 0.01}
return status_message, prediction, confidences
# ZeroGPU decorator
if spaces is not None:
analyze_text = spaces.GPU(analyze_text)
# Load Cyberpunk HUD HTML with embedded graphics
hud_file = os.path.join(current_dir, 'cyberpunk_hud.html')
hud_content = ""
if os.path.exists(hud_file):
with open(hud_file, 'r', encoding='utf-8') as f:
hud_content = f.read()
vagabond_path = os.path.join(current_dir, 'vagabond.jpg')
if os.path.exists(vagabond_path):
with open(vagabond_path, 'rb') as img_f:
b64_img = f"data:image/jpeg;base64,{base64.b64encode(img_f.read()).decode()}"
hud_content = hud_content.replace('src="./vagabond.jpg"', f'src="{b64_img}"')
# Gradio Interface Blocks - Cyberpunk HUD is now the primary hero tab!
with gr.Blocks(title="DEVIPUTRA AI // Cyberpunk HUD & Multilingual BERT") as demo:
gr.Markdown("""
# ⚡ DEVIPUTRA AI // MULTILINGUAL BERT INFERENCE LAB
### Fine-Tuned on Hinglish, Hindi, Telugu, and English Hate Speech & Dual-Meaning Slangs
""")
if hud_content:
with gr.Tab("🕹️ Cyberpunk HUD Deck (Interactive Neural HUD)"):
gr.HTML(f"""
<div style="width: 100%; height: 980px; overflow: auto; border: 1px solid #00f0ff; border-radius: 8px;">
<iframe srcdoc="{hud_content.replace('"', '"')}" style="width: 100%; height: 100%; border: none;"></iframe>
</div>
""")
with gr.Tab("🧪 Real-Time BERT Model Scanner"):
with gr.Row():
with gr.Column(scale=1):
input_text = gr.Textbox(
label="Input Text (Hindi, Hinglish, English, Telugu)",
placeholder="e.g., Mandir mein ghanta baj raha hai / I will hurt you...",
lines=3
)
analyze_btn = gr.Button("⚡ Run Deep Neural Scan", variant="primary")
gr.Examples(
examples=[
["Mandir mein aarti ke waqt bada ghanta baj raha hai."],
["Tujhe ghanta farak nahi padta yahan se nikal."],
["Mera kutta bahut cute aur loyal pet hai."],
["Tu kutta hai chup baith ekdum."],
["I will murder you tonight and destroy everything."],
["Bhai tu bohot accha insaan hai yaar."]
],
inputs=input_text
)
with gr.Column(scale=1):
output_verdict = gr.Textbox(label="Decision & Context Analysis", interactive=False)
output_label = gr.Label(label="Confidence Spectrum", num_top_classes=3)
hidden_pred = gr.Textbox(visible=False)
analyze_btn.click(
fn=analyze_text,
inputs=input_text,
outputs=[output_verdict, hidden_pred, output_label]
)
# FastAPI Backend server providing the /predict endpoint for the Cyberpunk HUD
server = FastAPI()
@server.post("/predict")
async def api_predict(request: Request):
data = await request.json()
text = data.get("text", "")
res = predictor.predict(text)
pred = res.get('prediction', 'Normal')
ctx = res.get('context') or {}
reason = ctx.get('reason', f"Contextual reasoning: {pred}")
scores = res.get('scores', {})
if not scores:
if pred == 'Hate Speech':
scores = {'Hate Speech': 0.98, 'Offensive': 0.015, 'Normal': 0.005}
elif pred == 'Offensive':
scores = {'Offensive': 0.92, 'Hate Speech': 0.05, 'Normal': 0.03}
else:
scores = {'Normal': 0.96, 'Offensive': 0.03, 'Hate Speech': 0.01}
conf = scores.get(pred, 0.95)
return {
"prediction": pred,
"confidence": conf,
"model_used": "Multilingual BERT (HingBERT)",
"reason": reason,
"scores": scores
}
# Mount Gradio into FastAPI
app = gr.mount_gradio_app(server, demo, path="/")
if __name__ == "__main__":
demo.launch()
|