Upload 2 files
Browse files- app.py +65 -0
- requirements.txt +4 -0
app.py
ADDED
@@ -0,0 +1,65 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import gradio as gr
|
2 |
+
import joblib
|
3 |
+
import numpy as np
|
4 |
+
import pandas as pd
|
5 |
+
from openai import OpenAI
|
6 |
+
from huggingface_hub import hf_hub_download
|
7 |
+
|
8 |
+
# Load your pre-trained model and label names
|
9 |
+
model_path = hf_hub_download(repo_id="govtech/zoo-entry-001", filename="model.joblib")
|
10 |
+
model_data = joblib.load(model_path)
|
11 |
+
model = model_data['model']
|
12 |
+
label_names = model_data['label_names']
|
13 |
+
|
14 |
+
# Initialize OpenAI client
|
15 |
+
client = OpenAI()
|
16 |
+
|
17 |
+
def get_embedding(text, embedding_model="text-embedding-3-large"):
|
18 |
+
"""
|
19 |
+
Get embedding for the input text from OpenAI.
|
20 |
+
Replace newlines in the text, then call the API.
|
21 |
+
"""
|
22 |
+
text = text.replace("\n", " ")
|
23 |
+
response = client.embeddings.create(
|
24 |
+
input=[text],
|
25 |
+
model=embedding_model
|
26 |
+
)
|
27 |
+
# Extract embedding vector from response
|
28 |
+
embedding = response.data[0].embedding
|
29 |
+
return np.array(embedding)
|
30 |
+
|
31 |
+
def classify_text(text):
|
32 |
+
"""
|
33 |
+
Get the OpenAI embedding for the provided text, classify it using your model,
|
34 |
+
and return an updated DataFrame component with the predictions and probabilities.
|
35 |
+
"""
|
36 |
+
embedding = get_embedding(text)
|
37 |
+
# Add batch dimension
|
38 |
+
X = np.array(embedding)[None, :]
|
39 |
+
# Get probabilities from the model
|
40 |
+
probabilities = model.predict(X)
|
41 |
+
# Create a DataFrame with probabilities, labels, and binary predictions
|
42 |
+
df = pd.DataFrame({
|
43 |
+
'Label': label_names,
|
44 |
+
'Probability': probabilities[0],
|
45 |
+
'Prediction': (probabilities[0] > 0.5).astype(int)
|
46 |
+
})
|
47 |
+
# Return an update to the DataFrame component to make it visible with the results
|
48 |
+
return gr.update(value=df, visible=True)
|
49 |
+
|
50 |
+
with gr.Blocks(title="Zoo Entry 001") as iface:
|
51 |
+
|
52 |
+
with gr.Row():
|
53 |
+
input_text = gr.Textbox(lines=5, label="Input Text")
|
54 |
+
|
55 |
+
with gr.Row():
|
56 |
+
submit_btn = gr.Button("Submit")
|
57 |
+
|
58 |
+
# Initialize the table as hidden
|
59 |
+
with gr.Row():
|
60 |
+
output_table = gr.DataFrame(label="Classification Results", visible=False)
|
61 |
+
|
62 |
+
submit_btn.click(fn=classify_text, inputs=input_text, outputs=output_table)
|
63 |
+
|
64 |
+
if __name__ == "__main__":
|
65 |
+
iface.launch()
|
requirements.txt
ADDED
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
1 |
+
keras
|
2 |
+
openai
|
3 |
+
tensorflow
|
4 |
+
joblib
|