kaliputra1's picture
Upload 2 files
397ed00 verified
Raw History Blame Contribute Delete
5.82 kB
# -*- 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('"', '&quot;')}" 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()