AbstractPhil commited on
Commit
535151e
·
verified ·
1 Parent(s): c7cb997

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +84 -59
app.py CHANGED
@@ -1,64 +1,89 @@
 
 
 
 
 
1
  import gradio as gr
2
- from huggingface_hub import InferenceClient
3
-
4
- """
5
- For more information on `huggingface_hub` Inference API support, please check the docs: https://huggingface.co/docs/huggingface_hub/v0.22.2/en/guides/inference
6
- """
7
- client = InferenceClient("HuggingFaceH4/zephyr-7b-beta")
8
-
9
-
10
- def respond(
11
- message,
12
- history: list[tuple[str, str]],
13
- system_message,
14
- max_tokens,
15
- temperature,
16
- top_p,
17
- ):
18
- messages = [{"role": "system", "content": system_message}]
19
-
20
- for val in history:
21
- if val[0]:
22
- messages.append({"role": "user", "content": val[0]})
23
- if val[1]:
24
- messages.append({"role": "assistant", "content": val[1]})
25
-
26
- messages.append({"role": "user", "content": message})
27
-
28
- response = ""
29
-
30
- for message in client.chat_completion(
31
- messages,
32
- max_tokens=max_tokens,
33
- stream=True,
34
- temperature=temperature,
35
- top_p=top_p,
36
- ):
37
- token = message.choices[0].delta.content
38
-
39
- response += token
40
- yield response
41
-
42
-
43
- """
44
- For information on how to customize the ChatInterface, peruse the gradio docs: https://www.gradio.app/docs/chatinterface
45
- """
46
- demo = gr.ChatInterface(
47
- respond,
48
- additional_inputs=[
49
- gr.Textbox(value="You are a friendly Chatbot.", label="System message"),
50
- gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"),
51
- gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),
52
- gr.Slider(
53
- minimum=0.1,
54
- maximum=1.0,
55
- value=0.95,
56
- step=0.05,
57
- label="Top-p (nucleus sampling)",
58
- ),
59
- ],
60
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
61
 
62
 
63
  if __name__ == "__main__":
 
64
  demo.launch()
 
1
+ # app.py
2
+
3
+ from huggingface_hub import snapshot_download
4
+ from transformers import AutoTokenizer, AutoModelForMaskedLM
5
+ import torch
6
  import gradio as gr
7
+ import re
8
+ from dataclasses import dataclass
9
+ from pathlib import Path
10
+ import spaces
11
+
12
+ @spaces.GPU
13
+ @dataclass
14
+ class SymbolicConfig:
15
+ repo_id: str = "AbstractPhil/bert-beatrix-2048"
16
+ symbolic_roles: list = (
17
+ "<subject>", "<subject1>", "<subject2>", "<pose>", "<emotion>",
18
+ "<surface>", "<lighting>", "<material>", "<accessory>", "<footwear>",
19
+ "<upper_body_clothing>", "<hair_style>", "<hair_length>", "<headwear>",
20
+ "<texture>", "<pattern>", "<grid>", "<zone>", "<offset>",
21
+ "<object_left>", "<object_right>", "<relation>", "<intent>", "<style>",
22
+ "<fabric>", "<jewelry>"
23
+ )
24
+
25
+ config = SymbolicConfig()
26
+ model_dir = snapshot_download(repo_id=config.repo_id)
27
+ tokenizer = AutoTokenizer.from_pretrained(model_dir)
28
+ model = AutoModelForMaskedLM.from_pretrained(model_dir).eval().cuda()
29
+
30
+
31
+ MASK_TOKEN = tokenizer.mask_token or "[MASK]"
32
+
33
+ def mask_and_predict(text: str, selected_roles: list[str]):
34
+ results = []
35
+ masked_text = text
36
+ token_ids = tokenizer.encode(text, return_tensors="pt").cuda()
37
+
38
+ for role in selected_roles:
39
+ role_pattern = re.escape(role)
40
+ masked_text = re.sub(role_pattern, MASK_TOKEN, masked_text)
41
+
42
+ masked_ids = tokenizer.encode(masked_text, return_tensors="pt").cuda()
43
+ with torch.no_grad():
44
+ outputs = model(input_ids=masked_ids)
45
+ logits = outputs.logits[0]
46
+ predictions = torch.argmax(logits, dim=-1)
47
+
48
+ original_ids = tokenizer.convert_ids_to_tokens(token_ids[0])
49
+ predicted_ids = tokenizer.convert_ids_to_tokens(predictions)
50
+ masked_ids_tokens = tokenizer.convert_ids_to_tokens(masked_ids[0])
51
+
52
+ for i, token in enumerate(masked_ids_tokens):
53
+ if token == MASK_TOKEN:
54
+ results.append({
55
+ "Position": i,
56
+ "Masked Token": MASK_TOKEN,
57
+ "Predicted": predicted_ids[i],
58
+ "Original": original_ids[i] if i < len(original_ids) else "",
59
+ "Match": "✅" if predicted_ids[i] == original_ids[i] else "❌"
60
+ })
61
+
62
+ accuracy = sum(1 for r in results if r["Match"] == "✅") / max(len(results), 1)
63
+ return results, f"Accuracy: {accuracy:.1%}"
64
+
65
+ def build_interface():
66
+ role_checkboxes = [gr.Checkbox(label=role, value=False) for role in config.symbolic_roles]
67
+
68
+ with gr.Blocks() as demo:
69
+ gr.Markdown("## 🔎 Symbolic BERT Inference Test")
70
+ with gr.Row():
71
+ with gr.Column():
72
+ input_text = gr.Textbox(label="Symbolic Input Caption", lines=3)
73
+ selected_roles = gr.CheckboxGroup(
74
+ choices=config.symbolic_roles,
75
+ label="Mask these symbolic roles"
76
+ )
77
+ run_btn = gr.Button("Run Mask Inference")
78
+ with gr.Column():
79
+ output_table = gr.Dataframe(headers=["Position", "Masked Token", "Predicted", "Original", "Match"], interactive=False)
80
+ accuracy_score = gr.Textbox(label="Mask Accuracy")
81
+
82
+ run_btn.click(fn=mask_and_predict, inputs=[input_text, selected_roles], outputs=[output_table, accuracy_score])
83
+
84
+ return demo
85
 
86
 
87
  if __name__ == "__main__":
88
+ demo = build_interface()
89
  demo.launch()