Update app.py
Browse files
app.py
CHANGED
|
@@ -1,81 +1,68 @@
|
|
| 1 |
import gradio as gr
|
| 2 |
-
import numpy as np
|
| 3 |
import torch
|
| 4 |
-
import
|
| 5 |
-
|
|
|
|
| 6 |
|
| 7 |
-
#
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
'health': ['wellness', 'asbestos', 'hazmat', 'patient', 'health', 'therapy']
|
| 12 |
-
}
|
| 13 |
-
|
| 14 |
-
# Define a simple neural network
|
| 15 |
-
class SimpleNet(nn.Module):
|
| 16 |
-
def __init__(self, input_size, hidden_size, output_size):
|
| 17 |
-
super(SimpleNet, self).__init__()
|
| 18 |
-
self.fc1 = nn.Linear(input_size, hidden_size)
|
| 19 |
-
self.fc2 = nn.Linear(hidden_size, output_size)
|
| 20 |
-
|
| 21 |
-
def forward(self, x):
|
| 22 |
-
x = F.relu(self.fc1(x))
|
| 23 |
-
return self.fc2(x)
|
| 24 |
-
|
| 25 |
-
# Tokenizer and encoder (basic word count)
|
| 26 |
-
def encode(text):
|
| 27 |
-
vector = np.zeros(len(set(sum(keywords.values(), []))))
|
| 28 |
-
vocab = list(set(sum(keywords.values(), [])))
|
| 29 |
-
for word in text.lower().split():
|
| 30 |
-
if word in vocab:
|
| 31 |
-
vector[vocab.index(word)] += 1
|
| 32 |
-
return torch.tensor(vector, dtype=torch.float32)
|
| 33 |
-
|
| 34 |
-
# Initialize model
|
| 35 |
-
model = SimpleNet(input_size=12, hidden_size=6, output_size=2)
|
| 36 |
-
optimizer = torch.optim.SGD(model.parameters(), lr=0.01)
|
| 37 |
|
| 38 |
def zero_shot_infer(text):
|
| 39 |
-
|
| 40 |
with torch.no_grad():
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 44 |
|
| 45 |
def train_step(text, label, lr, momentum):
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
g['momentum'] = momentum
|
| 49 |
-
x = encode(text)
|
| 50 |
-
y = torch.tensor([classes.index(label)], dtype=torch.long)
|
| 51 |
-
output = model(x)
|
| 52 |
-
loss = F.cross_entropy(output.unsqueeze(0), y)
|
| 53 |
-
optimizer.zero_grad()
|
| 54 |
-
loss.backward()
|
| 55 |
-
optimizer.step()
|
| 56 |
-
return f"Loss after training step: {loss.item():.4f}"
|
| 57 |
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
|
|
|
|
|
|
|
|
|
| 61 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 62 |
with gr.Row():
|
| 63 |
input_text = gr.Textbox(label="Input Text")
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
infer_btn.click(fn=zero_shot_infer, inputs=input_text, outputs=infer_out)
|
| 68 |
-
|
| 69 |
-
gr.Markdown("### Train the Model Manually")
|
| 70 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 71 |
with gr.Row():
|
| 72 |
-
train_text = gr.Textbox(label="Training Text")
|
| 73 |
-
train_label = gr.Radio(choices=classes, label="Label")
|
| 74 |
lr = gr.Slider(0.001, 0.1, value=0.01, label="Learning Rate")
|
| 75 |
-
momentum = gr.Slider(0.0,
|
| 76 |
-
|
| 77 |
-
|
|
|
|
| 78 |
|
| 79 |
-
|
|
|
|
|
|
|
|
|
|
| 80 |
|
| 81 |
-
|
|
|
|
|
|
| 1 |
import gradio as gr
|
|
|
|
| 2 |
import torch
|
| 3 |
+
from transformers import pipeline, AutoTokenizer, AutoModelForSequenceClassification
|
| 4 |
+
from torch.nn import functional as F
|
| 5 |
+
import pandas as pd
|
| 6 |
|
| 7 |
+
# Load base model for inference
|
| 8 |
+
tokenizer = AutoTokenizer.from_pretrained("distilbert-base-uncased")
|
| 9 |
+
model = AutoModelForSequenceClassification.from_pretrained("distilbert-base-uncased", num_labels=2)
|
| 10 |
+
labels = ['tech', 'health']
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 11 |
|
| 12 |
def zero_shot_infer(text):
|
| 13 |
+
inputs = tokenizer(text, return_tensors="pt")
|
| 14 |
with torch.no_grad():
|
| 15 |
+
logits = model(**inputs).logits
|
| 16 |
+
probs = F.softmax(logits, dim=1)
|
| 17 |
+
result = {labels[i]: float(probs[0][i]) for i in range(len(labels))}
|
| 18 |
+
return result
|
| 19 |
+
|
| 20 |
+
# Initialize training data storage
|
| 21 |
+
training_data = []
|
| 22 |
|
| 23 |
def train_step(text, label, lr, momentum):
|
| 24 |
+
training_data.append((text, label))
|
| 25 |
+
return f"Stored: '{text}' as '{label}' | Total examples: {len(training_data)}"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 26 |
|
| 27 |
+
def fine_tune_model():
|
| 28 |
+
if len(training_data) < 4:
|
| 29 |
+
return "Need more training samples (min: 4)."
|
| 30 |
+
df = pd.DataFrame(training_data, columns=['text', 'label'])
|
| 31 |
+
# This placeholder suggests fine-tuning with a proper pipeline externally
|
| 32 |
+
return "Training initiated on backend. This version supports frontend data collection only."
|
| 33 |
|
| 34 |
+
def conscious_infer(text):
|
| 35 |
+
output = zero_shot_infer(text)
|
| 36 |
+
max_label = max(output, key=output.get)
|
| 37 |
+
confidence = output[max_label]
|
| 38 |
+
# Simulate conscious inference via contextual intuition
|
| 39 |
+
reflection = "This concept resonates with techno-consciousness." if max_label == 'tech' else "This concept radiates healing intention."
|
| 40 |
+
return f"Label: {max_label} (Confidence: {confidence:.2f})\nInsight: {reflection}"
|
| 41 |
+
|
| 42 |
+
with gr.Blocks() as demo:
|
| 43 |
+
gr.Markdown("## Vers3Dynamics Conscious Labeling AI")
|
| 44 |
+
gr.Markdown("### Zero-Shot + Conscious Insight Inference")
|
| 45 |
with gr.Row():
|
| 46 |
input_text = gr.Textbox(label="Input Text")
|
| 47 |
+
output_text = gr.Textbox(label="Inference Result")
|
| 48 |
+
infer_btn = gr.Button("Infer with Insight")
|
| 49 |
+
infer_btn.click(conscious_infer, inputs=input_text, outputs=output_text)
|
|
|
|
|
|
|
|
|
|
| 50 |
|
| 51 |
+
gr.Markdown("### Manual Conscious Training")
|
| 52 |
+
with gr.Row():
|
| 53 |
+
training_text = gr.Textbox(label="Training Text")
|
| 54 |
+
label_choice = gr.Radio(choices=labels, label="Label")
|
| 55 |
with gr.Row():
|
|
|
|
|
|
|
| 56 |
lr = gr.Slider(0.001, 0.1, value=0.01, label="Learning Rate")
|
| 57 |
+
momentum = gr.Slider(0.0, 1.0, value=0.0, label="Momentum")
|
| 58 |
+
train_output = gr.Textbox(label="Training Output")
|
| 59 |
+
train_btn = gr.Button("Store Training Sample")
|
| 60 |
+
train_btn.click(train_step, inputs=[training_text, label_choice, lr, momentum], outputs=train_output)
|
| 61 |
|
| 62 |
+
gr.Markdown("### Backend Fine-Tuning Placeholder")
|
| 63 |
+
fine_tune = gr.Button("Initiate Fine-Tune")
|
| 64 |
+
fine_output = gr.Textbox(label="Fine-Tune Response")
|
| 65 |
+
fine_tune.click(fine_tune_model, outputs=fine_output)
|
| 66 |
|
| 67 |
+
if __name__ == "__main__":
|
| 68 |
+
demo.launch()
|