Spaces:
Sleeping
Sleeping
Alon Albalak
commited on
Commit
·
36d5e94
1
Parent(s):
f61e414
major update: data saved to hf, user sessions maintain separation, fixed scoring bug
Browse files- app.py +15 -24
- data/prompts.jsonl +0 -0
- data/results.jsonl +0 -3
- src/models/data_manager.py +64 -3
- src/models/llm_manager.py +3 -8
- src/scoring/scorer.py +7 -6
- src/scoring/statistics.py +1 -1
- src/session/session_manager.py +3 -4
- src/ui/interface_builder.py +33 -31
- src/ui/page_handlers.py +59 -31
app.py
CHANGED
|
@@ -5,34 +5,24 @@ from src.models.data_manager import DataManager
|
|
| 5 |
from src.scoring.scorer import Scorer
|
| 6 |
from src.scoring.statistics import StatisticsCalculator
|
| 7 |
from src.scoring.achievements import AchievementSystem
|
| 8 |
-
from src.session.session_manager import SessionManager
|
| 9 |
from src.ui.template_renderer import TemplateRenderer
|
| 10 |
from src.ui.page_handlers import PageHandlers
|
| 11 |
from src.ui.interface_builder import InterfaceBuilder
|
| 12 |
|
| 13 |
class CollaborativeDecodingApp:
|
| 14 |
def __init__(self):
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
# Initialize managers
|
| 18 |
self.llm_manager = LLMManager()
|
| 19 |
self.similarity_calculator = SimilarityCalculator()
|
| 20 |
self.data_manager = DataManager()
|
| 21 |
self.scorer = Scorer()
|
| 22 |
self.statistics_calculator = StatisticsCalculator()
|
| 23 |
self.achievement_system = AchievementSystem()
|
| 24 |
-
self.session_manager = SessionManager(
|
| 25 |
-
data_manager=self.data_manager,
|
| 26 |
-
achievement_system=self.achievement_system
|
| 27 |
-
)
|
| 28 |
|
| 29 |
# Initialize UI components
|
| 30 |
self.template_renderer = TemplateRenderer()
|
| 31 |
self.page_handlers = PageHandlers(self)
|
| 32 |
self.interface_builder = InterfaceBuilder(self, self.page_handlers)
|
| 33 |
-
|
| 34 |
-
# Use session manager's session ID
|
| 35 |
-
self.session_id = self.session_manager.session_id
|
| 36 |
|
| 37 |
def load_data(self):
|
| 38 |
self.data_manager.load_prompts_data()
|
|
@@ -42,14 +32,15 @@ class CollaborativeDecodingApp:
|
|
| 42 |
self.similarity_calculator.load_model()
|
| 43 |
|
| 44 |
def get_random_prompt(self):
|
| 45 |
-
|
| 46 |
-
return self.
|
| 47 |
|
| 48 |
def validate_user_input(self, user_input):
|
|
|
|
| 49 |
return self.llm_manager.validate_user_input(user_input)
|
| 50 |
|
| 51 |
-
def process_submission(self, user_input):
|
| 52 |
-
"""Process user submission and return results"""
|
| 53 |
# Validation
|
| 54 |
if not user_input.strip():
|
| 55 |
return "Please enter some text to continue the response.", None, None, None, None, None, None
|
|
@@ -57,34 +48,34 @@ class CollaborativeDecodingApp:
|
|
| 57 |
if not self.validate_user_input(user_input):
|
| 58 |
return "Please keep your input to 5 tokens or less.", None, None, None, None, None, None
|
| 59 |
|
| 60 |
-
if not
|
| 61 |
return "Error: No prompt loaded. Please refresh the page.", None, None, None, None, None, None
|
| 62 |
|
| 63 |
# Generate response
|
| 64 |
try:
|
| 65 |
generated_response = self.llm_manager.generate_response_from_user_input(
|
| 66 |
-
|
| 67 |
-
|
| 68 |
user_input
|
| 69 |
)
|
| 70 |
except Exception as e:
|
| 71 |
return f"Error generating response: {str(e)}", None, None, None, None, None, None
|
| 72 |
|
| 73 |
# Calculate similarity score
|
| 74 |
-
original_full =
|
| 75 |
cosine_distance = self.similarity_calculator.compute_cosine_distance(original_full, generated_response)
|
| 76 |
|
| 77 |
# Save interaction with token count
|
| 78 |
num_user_tokens = self.llm_manager.count_tokens(user_input)
|
| 79 |
-
self.data_manager.
|
| 80 |
-
|
| 81 |
-
cosine_distance,
|
| 82 |
)
|
| 83 |
|
| 84 |
# Calculate additional metrics for results display
|
| 85 |
-
all_results = self.data_manager.
|
| 86 |
prompt_results = self.data_manager.filter_results_by_partial_response(
|
| 87 |
-
all_results,
|
| 88 |
)
|
| 89 |
|
| 90 |
# Calculate rank and percentile
|
|
|
|
| 5 |
from src.scoring.scorer import Scorer
|
| 6 |
from src.scoring.statistics import StatisticsCalculator
|
| 7 |
from src.scoring.achievements import AchievementSystem
|
|
|
|
| 8 |
from src.ui.template_renderer import TemplateRenderer
|
| 9 |
from src.ui.page_handlers import PageHandlers
|
| 10 |
from src.ui.interface_builder import InterfaceBuilder
|
| 11 |
|
| 12 |
class CollaborativeDecodingApp:
|
| 13 |
def __init__(self):
|
| 14 |
+
# Initialize shared managers (no per-user state)
|
|
|
|
|
|
|
| 15 |
self.llm_manager = LLMManager()
|
| 16 |
self.similarity_calculator = SimilarityCalculator()
|
| 17 |
self.data_manager = DataManager()
|
| 18 |
self.scorer = Scorer()
|
| 19 |
self.statistics_calculator = StatisticsCalculator()
|
| 20 |
self.achievement_system = AchievementSystem()
|
|
|
|
|
|
|
|
|
|
|
|
|
| 21 |
|
| 22 |
# Initialize UI components
|
| 23 |
self.template_renderer = TemplateRenderer()
|
| 24 |
self.page_handlers = PageHandlers(self)
|
| 25 |
self.interface_builder = InterfaceBuilder(self, self.page_handlers)
|
|
|
|
|
|
|
|
|
|
| 26 |
|
| 27 |
def load_data(self):
|
| 28 |
self.data_manager.load_prompts_data()
|
|
|
|
| 32 |
self.similarity_calculator.load_model()
|
| 33 |
|
| 34 |
def get_random_prompt(self):
|
| 35 |
+
"""Get a random prompt from the dataset"""
|
| 36 |
+
return self.data_manager.get_random_prompt()
|
| 37 |
|
| 38 |
def validate_user_input(self, user_input):
|
| 39 |
+
"""Validate user input using LLM manager"""
|
| 40 |
return self.llm_manager.validate_user_input(user_input)
|
| 41 |
|
| 42 |
+
def process_submission(self, user_input, current_prompt, session_id):
|
| 43 |
+
"""Process user submission and return results with updated state"""
|
| 44 |
# Validation
|
| 45 |
if not user_input.strip():
|
| 46 |
return "Please enter some text to continue the response.", None, None, None, None, None, None
|
|
|
|
| 48 |
if not self.validate_user_input(user_input):
|
| 49 |
return "Please keep your input to 5 tokens or less.", None, None, None, None, None, None
|
| 50 |
|
| 51 |
+
if not current_prompt:
|
| 52 |
return "Error: No prompt loaded. Please refresh the page.", None, None, None, None, None, None
|
| 53 |
|
| 54 |
# Generate response
|
| 55 |
try:
|
| 56 |
generated_response = self.llm_manager.generate_response_from_user_input(
|
| 57 |
+
current_prompt["prompt"],
|
| 58 |
+
current_prompt["llm_partial_response"],
|
| 59 |
user_input
|
| 60 |
)
|
| 61 |
except Exception as e:
|
| 62 |
return f"Error generating response: {str(e)}", None, None, None, None, None, None
|
| 63 |
|
| 64 |
# Calculate similarity score
|
| 65 |
+
original_full = current_prompt["llm_full_response_original"]
|
| 66 |
cosine_distance = self.similarity_calculator.compute_cosine_distance(original_full, generated_response)
|
| 67 |
|
| 68 |
# Save interaction with token count
|
| 69 |
num_user_tokens = self.llm_manager.count_tokens(user_input)
|
| 70 |
+
self.data_manager.save_interaction_to_hf(
|
| 71 |
+
current_prompt, user_input, generated_response,
|
| 72 |
+
cosine_distance, session_id, num_user_tokens
|
| 73 |
)
|
| 74 |
|
| 75 |
# Calculate additional metrics for results display
|
| 76 |
+
all_results = self.data_manager.get_results()
|
| 77 |
prompt_results = self.data_manager.filter_results_by_partial_response(
|
| 78 |
+
all_results, current_prompt["prompt"], current_prompt["llm_partial_response"]
|
| 79 |
)
|
| 80 |
|
| 81 |
# Calculate rank and percentile
|
data/prompts.jsonl
CHANGED
|
The diff for this file is too large to render.
See raw diff
|
|
|
data/results.jsonl
DELETED
|
@@ -1,3 +0,0 @@
|
|
| 1 |
-
version https://git-lfs.github.com/spec/v1
|
| 2 |
-
oid sha256:b2f25a144bab0f085cf223889a98a9215d578b4069a2a41d9cf545c87e4a9976
|
| 3 |
-
size 219450738
|
|
|
|
|
|
|
|
|
|
|
|
src/models/data_manager.py
CHANGED
|
@@ -4,14 +4,31 @@ import json
|
|
| 4 |
import os
|
| 5 |
import random
|
| 6 |
import datetime
|
|
|
|
|
|
|
|
|
|
|
|
|
| 7 |
|
| 8 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 9 |
class DataManager:
|
| 10 |
"""Manages loading and saving of prompts and results data"""
|
| 11 |
|
| 12 |
def __init__(self):
|
| 13 |
self.prompts_data = []
|
| 14 |
-
|
|
|
|
| 15 |
def load_prompts_data(self, filepath="data/prompts.jsonl"):
|
| 16 |
"""Load prompts data from JSONL file"""
|
| 17 |
with open(filepath, "r") as f:
|
|
@@ -23,6 +40,18 @@ class DataManager:
|
|
| 23 |
raise RuntimeError("No prompts data loaded. Call load_prompts_data() first.")
|
| 24 |
return random.choice(self.prompts_data)
|
| 25 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 26 |
def load_results_data(self, filepath="data/results.jsonl"):
|
| 27 |
"""Load all results data from results.jsonl file."""
|
| 28 |
results = []
|
|
@@ -35,6 +64,15 @@ class DataManager:
|
|
| 35 |
pass # Return empty list if file doesn't exist
|
| 36 |
return results
|
| 37 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 38 |
def save_interaction(self, prompt_data, user_continuation, generated_response,
|
| 39 |
cosine_distance, session_id, num_user_tokens, filepath="data/results.jsonl"):
|
| 40 |
"""Save a user interaction to the results file"""
|
|
@@ -55,6 +93,29 @@ class DataManager:
|
|
| 55 |
with open(filepath, "a") as f:
|
| 56 |
f.write(json.dumps(interaction) + "\n")
|
| 57 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 58 |
def filter_results_by_partial_response(self, results, prompt, partial_response):
|
| 59 |
"""Filter results to only include entries for the current prompt."""
|
| 60 |
return [r for r in results if r["prompt"] == prompt and r["llm_partial_response"] == partial_response]
|
|
@@ -65,7 +126,7 @@ class DataManager:
|
|
| 65 |
|
| 66 |
def get_gallery_responses(self, min_score=0.3, limit=20):
|
| 67 |
"""Get gallery responses with minimum creativity score"""
|
| 68 |
-
all_results = self.
|
| 69 |
|
| 70 |
# Filter by minimum score and sort by score (descending)
|
| 71 |
filtered_results = [r for r in all_results if r["cosine_distance"] >= min_score]
|
|
@@ -76,7 +137,7 @@ class DataManager:
|
|
| 76 |
|
| 77 |
def get_inspire_me_examples(self, prompt, partial_response, limit=5):
|
| 78 |
"""Get inspiring examples for the current prompt"""
|
| 79 |
-
all_results = self.
|
| 80 |
|
| 81 |
# Filter to current prompt and get good examples (≥0.2 score)
|
| 82 |
examples = [r for r in all_results
|
|
|
|
| 4 |
import os
|
| 5 |
import random
|
| 6 |
import datetime
|
| 7 |
+
import uuid
|
| 8 |
+
from pathlib import Path
|
| 9 |
+
from datasets import load_dataset
|
| 10 |
+
from huggingface_hub import CommitScheduler
|
| 11 |
|
| 12 |
|
| 13 |
+
JSON_DATASET_DIR = Path("results")
|
| 14 |
+
JSON_DATASET_DIR.mkdir(parents=True, exist_ok=True)
|
| 15 |
+
JSON_DATASET_PATH = JSON_DATASET_DIR / f"results_{uuid.uuid4()}.json"
|
| 16 |
+
|
| 17 |
+
scheduler = CommitScheduler(
|
| 18 |
+
repo_id="alon-albalak/collaborative-decoding-results",
|
| 19 |
+
repo_type="dataset",
|
| 20 |
+
folder_path=JSON_DATASET_DIR.as_posix(),
|
| 21 |
+
path_in_repo="data",
|
| 22 |
+
every=10
|
| 23 |
+
)
|
| 24 |
+
|
| 25 |
class DataManager:
|
| 26 |
"""Manages loading and saving of prompts and results data"""
|
| 27 |
|
| 28 |
def __init__(self):
|
| 29 |
self.prompts_data = []
|
| 30 |
+
self.results = None
|
| 31 |
+
|
| 32 |
def load_prompts_data(self, filepath="data/prompts.jsonl"):
|
| 33 |
"""Load prompts data from JSONL file"""
|
| 34 |
with open(filepath, "r") as f:
|
|
|
|
| 40 |
raise RuntimeError("No prompts data loaded. Call load_prompts_data() first.")
|
| 41 |
return random.choice(self.prompts_data)
|
| 42 |
|
| 43 |
+
def get_results(self):
|
| 44 |
+
"""Get all results data, loading if not already loaded."""
|
| 45 |
+
if self.results is None:
|
| 46 |
+
self.results = self.load_results_from_hf()
|
| 47 |
+
return self.results
|
| 48 |
+
|
| 49 |
+
def add_results(self, new_results):
|
| 50 |
+
"""Add new results to the existing results list."""
|
| 51 |
+
if self.results is None:
|
| 52 |
+
raise RuntimeError("Results not loaded. Call get_results() first.")
|
| 53 |
+
self.results.extend(new_results)
|
| 54 |
+
|
| 55 |
def load_results_data(self, filepath="data/results.jsonl"):
|
| 56 |
"""Load all results data from results.jsonl file."""
|
| 57 |
results = []
|
|
|
|
| 64 |
pass # Return empty list if file doesn't exist
|
| 65 |
return results
|
| 66 |
|
| 67 |
+
def load_results_from_hf(self, hf_repo="alon-albalak/collaborative-decoding-results"):
|
| 68 |
+
"""Load results data from Hugging Face dataset repository."""
|
| 69 |
+
try:
|
| 70 |
+
dataset = load_dataset(hf_repo, split="train")
|
| 71 |
+
return dataset.to_list()
|
| 72 |
+
except Exception as e:
|
| 73 |
+
print(f"Error loading dataset from Hugging Face: {e}")
|
| 74 |
+
return []
|
| 75 |
+
|
| 76 |
def save_interaction(self, prompt_data, user_continuation, generated_response,
|
| 77 |
cosine_distance, session_id, num_user_tokens, filepath="data/results.jsonl"):
|
| 78 |
"""Save a user interaction to the results file"""
|
|
|
|
| 93 |
with open(filepath, "a") as f:
|
| 94 |
f.write(json.dumps(interaction) + "\n")
|
| 95 |
|
| 96 |
+
def save_interaction_to_hf(self, prompt_data, user_continuation, generated_response,
|
| 97 |
+
cosine_distance, session_id, num_user_tokens):
|
| 98 |
+
interaction = {
|
| 99 |
+
"prompt": prompt_data["prompt"],
|
| 100 |
+
"model": prompt_data["model"],
|
| 101 |
+
"llm_partial_response": prompt_data["llm_partial_response"],
|
| 102 |
+
"llm_full_response_original": prompt_data["llm_full_response_original"],
|
| 103 |
+
"user_continuation": user_continuation,
|
| 104 |
+
"full_response_from_user": generated_response,
|
| 105 |
+
"cosine_distance": cosine_distance,
|
| 106 |
+
"timestamp": datetime.datetime.now().isoformat(),
|
| 107 |
+
"continuation_source": session_id,
|
| 108 |
+
"num_user_tokens": num_user_tokens,
|
| 109 |
+
"continuation_prompt": "",
|
| 110 |
+
"full_continuation_prompt": ""
|
| 111 |
+
}
|
| 112 |
+
|
| 113 |
+
self.add_results([interaction])
|
| 114 |
+
|
| 115 |
+
with scheduler.lock:
|
| 116 |
+
with open(JSON_DATASET_PATH, "a") as f:
|
| 117 |
+
f.write(json.dumps(interaction) + "\n")
|
| 118 |
+
|
| 119 |
def filter_results_by_partial_response(self, results, prompt, partial_response):
|
| 120 |
"""Filter results to only include entries for the current prompt."""
|
| 121 |
return [r for r in results if r["prompt"] == prompt and r["llm_partial_response"] == partial_response]
|
|
|
|
| 126 |
|
| 127 |
def get_gallery_responses(self, min_score=0.3, limit=20):
|
| 128 |
"""Get gallery responses with minimum creativity score"""
|
| 129 |
+
all_results = self.get_results()
|
| 130 |
|
| 131 |
# Filter by minimum score and sort by score (descending)
|
| 132 |
filtered_results = [r for r in all_results if r["cosine_distance"] >= min_score]
|
|
|
|
| 137 |
|
| 138 |
def get_inspire_me_examples(self, prompt, partial_response, limit=5):
|
| 139 |
"""Get inspiring examples for the current prompt"""
|
| 140 |
+
all_results = self.get_results()
|
| 141 |
|
| 142 |
# Filter to current prompt and get good examples (≥0.2 score)
|
| 143 |
examples = [r for r in all_results
|
src/models/llm_manager.py
CHANGED
|
@@ -5,8 +5,6 @@ import torch
|
|
| 5 |
from transformers import AutoTokenizer, AutoModelForCausalLM
|
| 6 |
|
| 7 |
os.environ["TOKENIZERS_PARALLELISM"] = "false"
|
| 8 |
-
HF_TOKEN = os.getenv("HF_TOKEN")
|
| 9 |
-
|
| 10 |
|
| 11 |
class LLMManager:
|
| 12 |
"""Manages LLM model loading and text generation operations"""
|
|
@@ -27,13 +25,13 @@ class LLMManager:
|
|
| 27 |
|
| 28 |
self.device = device
|
| 29 |
self.dtype = dtype
|
| 30 |
-
|
| 31 |
def load_models(self, model_name="meta-llama/Llama-3.2-1B-Instruct"):
|
| 32 |
"""Load the LLM model and tokenizer"""
|
| 33 |
-
self.tokenizer = AutoTokenizer.from_pretrained(model_name
|
| 34 |
self.model = AutoModelForCausalLM.from_pretrained(model_name, dtype=self.dtype, low_cpu_mem_usage=True)
|
| 35 |
self.model = self.model.to(self.device)
|
| 36 |
-
|
| 37 |
if self.tokenizer.pad_token is None:
|
| 38 |
self.tokenizer.pad_token = self.tokenizer.eos_token
|
| 39 |
|
|
@@ -86,9 +84,6 @@ class LLMManager:
|
|
| 86 |
temperature=1.0,
|
| 87 |
pad_token_id=self.tokenizer.eos_token_id
|
| 88 |
)
|
| 89 |
-
|
| 90 |
-
# Move output back to CPU and decode
|
| 91 |
-
outputs = outputs.cpu()
|
| 92 |
|
| 93 |
full_response = self.tokenizer.decode(outputs[0].cpu(), skip_special_tokens=True)
|
| 94 |
assistant_part = full_response.split("Assistant: ")[-1]
|
|
|
|
| 5 |
from transformers import AutoTokenizer, AutoModelForCausalLM
|
| 6 |
|
| 7 |
os.environ["TOKENIZERS_PARALLELISM"] = "false"
|
|
|
|
|
|
|
| 8 |
|
| 9 |
class LLMManager:
|
| 10 |
"""Manages LLM model loading and text generation operations"""
|
|
|
|
| 25 |
|
| 26 |
self.device = device
|
| 27 |
self.dtype = dtype
|
| 28 |
+
|
| 29 |
def load_models(self, model_name="meta-llama/Llama-3.2-1B-Instruct"):
|
| 30 |
"""Load the LLM model and tokenizer"""
|
| 31 |
+
self.tokenizer = AutoTokenizer.from_pretrained(model_name)
|
| 32 |
self.model = AutoModelForCausalLM.from_pretrained(model_name, dtype=self.dtype, low_cpu_mem_usage=True)
|
| 33 |
self.model = self.model.to(self.device)
|
| 34 |
+
|
| 35 |
if self.tokenizer.pad_token is None:
|
| 36 |
self.tokenizer.pad_token = self.tokenizer.eos_token
|
| 37 |
|
|
|
|
| 84 |
temperature=1.0,
|
| 85 |
pad_token_id=self.tokenizer.eos_token_id
|
| 86 |
)
|
|
|
|
|
|
|
|
|
|
| 87 |
|
| 88 |
full_response = self.tokenizer.decode(outputs[0].cpu(), skip_special_tokens=True)
|
| 89 |
assistant_part = full_response.split("Assistant: ")[-1]
|
src/scoring/scorer.py
CHANGED
|
@@ -1,8 +1,7 @@
|
|
| 1 |
"""Scoring logic and enhanced score display functionality"""
|
| 2 |
|
| 3 |
import random
|
| 4 |
-
from
|
| 5 |
-
|
| 6 |
|
| 7 |
class Scorer:
|
| 8 |
"""Handles scoring calculations and display generation"""
|
|
@@ -49,7 +48,7 @@ class Scorer:
|
|
| 49 |
# Find rank (1-based)
|
| 50 |
rank = None
|
| 51 |
for i, score in enumerate(sorted_scores):
|
| 52 |
-
if
|
| 53 |
rank = i + 1
|
| 54 |
break
|
| 55 |
|
|
@@ -60,7 +59,10 @@ class Scorer:
|
|
| 60 |
if len(sorted_scores) <= 1:
|
| 61 |
percentile = 50.0
|
| 62 |
else:
|
| 63 |
-
percentile
|
|
|
|
|
|
|
|
|
|
| 64 |
|
| 65 |
return rank, percentile
|
| 66 |
|
|
@@ -115,7 +117,7 @@ class Scorer:
|
|
| 115 |
html_content += f"""
|
| 116 |
<div class="score-metric">
|
| 117 |
<div class="metric-value">#{rank}</div>
|
| 118 |
-
<div class="metric-label">Rank out of {same_category_attempts}</div>
|
| 119 |
</div>
|
| 120 |
<div class="score-metric">
|
| 121 |
<div class="metric-value">{percentile:.1f}%</div>
|
|
@@ -140,7 +142,6 @@ class Scorer:
|
|
| 140 |
"""
|
| 141 |
|
| 142 |
# Add achievement titles
|
| 143 |
-
from .achievements import AchievementSystem
|
| 144 |
achievement_system = AchievementSystem()
|
| 145 |
achievements = achievement_system.determine_achievement_titles(cosine_distance, user_tokens)
|
| 146 |
|
|
|
|
| 1 |
"""Scoring logic and enhanced score display functionality"""
|
| 2 |
|
| 3 |
import random
|
| 4 |
+
from .achievements import AchievementSystem
|
|
|
|
| 5 |
|
| 6 |
class Scorer:
|
| 7 |
"""Handles scoring calculations and display generation"""
|
|
|
|
| 48 |
# Find rank (1-based)
|
| 49 |
rank = None
|
| 50 |
for i, score in enumerate(sorted_scores):
|
| 51 |
+
if user_score >= score:
|
| 52 |
rank = i + 1
|
| 53 |
break
|
| 54 |
|
|
|
|
| 59 |
if len(sorted_scores) <= 1:
|
| 60 |
percentile = 50.0
|
| 61 |
else:
|
| 62 |
+
# Compute raw percentile: proportion of users the current user is better than.
|
| 63 |
+
raw_percentile = (len(sorted_scores) - rank) / len(sorted_scores) * 100.0
|
| 64 |
+
# Ensure percentile is always within 0-100 even if rank is out of expected bounds
|
| 65 |
+
percentile = max(0.0, min(100.0, raw_percentile))
|
| 66 |
|
| 67 |
return rank, percentile
|
| 68 |
|
|
|
|
| 117 |
html_content += f"""
|
| 118 |
<div class="score-metric">
|
| 119 |
<div class="metric-value">#{rank}</div>
|
| 120 |
+
<div class="metric-label">Rank out of {same_category_attempts+1}</div>
|
| 121 |
</div>
|
| 122 |
<div class="score-metric">
|
| 123 |
<div class="metric-value">{percentile:.1f}%</div>
|
|
|
|
| 142 |
"""
|
| 143 |
|
| 144 |
# Add achievement titles
|
|
|
|
| 145 |
achievement_system = AchievementSystem()
|
| 146 |
achievements = achievement_system.determine_achievement_titles(cosine_distance, user_tokens)
|
| 147 |
|
src/scoring/statistics.py
CHANGED
|
@@ -86,7 +86,7 @@ class StatisticsCalculator:
|
|
| 86 |
|
| 87 |
def calculate_session_ranking_stats(self, session_results, data_manager, scorer):
|
| 88 |
"""Calculate comprehensive ranking statistics for the session."""
|
| 89 |
-
all_results = data_manager.
|
| 90 |
ranking_stats = {
|
| 91 |
"best_rank": None,
|
| 92 |
"best_percentile": None,
|
|
|
|
| 86 |
|
| 87 |
def calculate_session_ranking_stats(self, session_results, data_manager, scorer):
|
| 88 |
"""Calculate comprehensive ranking statistics for the session."""
|
| 89 |
+
all_results = data_manager.get_results()
|
| 90 |
ranking_stats = {
|
| 91 |
"best_rank": None,
|
| 92 |
"best_percentile": None,
|
src/session/session_manager.py
CHANGED
|
@@ -1,14 +1,13 @@
|
|
| 1 |
"""Session management and progress tracking functionality"""
|
| 2 |
|
| 3 |
import uuid
|
| 4 |
-
from typing import Dict, List, Optional
|
| 5 |
|
| 6 |
|
| 7 |
class SessionManager:
|
| 8 |
"""Manages user session state and progress tracking"""
|
| 9 |
|
| 10 |
-
def __init__(self, data_manager=None, achievement_system=None):
|
| 11 |
-
self.session_id = str(uuid.uuid4())
|
| 12 |
self.data_manager = data_manager
|
| 13 |
self.achievement_system = achievement_system
|
| 14 |
|
|
@@ -17,7 +16,7 @@ class SessionManager:
|
|
| 17 |
if not self.data_manager:
|
| 18 |
return self._get_empty_session_stats()
|
| 19 |
|
| 20 |
-
all_results = self.data_manager.
|
| 21 |
session_results = self.data_manager.filter_results_by_session(all_results, self.session_id)
|
| 22 |
|
| 23 |
if not session_results:
|
|
|
|
| 1 |
"""Session management and progress tracking functionality"""
|
| 2 |
|
| 3 |
import uuid
|
|
|
|
| 4 |
|
| 5 |
|
| 6 |
class SessionManager:
|
| 7 |
"""Manages user session state and progress tracking"""
|
| 8 |
|
| 9 |
+
def __init__(self, session_id=None, data_manager=None, achievement_system=None):
|
| 10 |
+
self.session_id = session_id or str(uuid.uuid4())
|
| 11 |
self.data_manager = data_manager
|
| 12 |
self.achievement_system = achievement_system
|
| 13 |
|
|
|
|
| 16 |
if not self.data_manager:
|
| 17 |
return self._get_empty_session_stats()
|
| 18 |
|
| 19 |
+
all_results = self.data_manager.get_results()
|
| 20 |
session_results = self.data_manager.filter_results_by_session(all_results, self.session_id)
|
| 21 |
|
| 22 |
if not session_results:
|
src/ui/interface_builder.py
CHANGED
|
@@ -12,12 +12,17 @@ class InterfaceBuilder:
|
|
| 12 |
self.page_handlers = page_handlers
|
| 13 |
|
| 14 |
def create_interface(self):
|
| 15 |
-
with gr.Blocks(title="Help the LLM be Creative!", css_paths=CSS_PATHS
|
| 16 |
|
| 17 |
# Navigation state management
|
| 18 |
current_page = gr.State("welcome")
|
| 19 |
has_results = gr.State(False)
|
| 20 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 21 |
# Navigation bar
|
| 22 |
nav_container = gr.Column(elem_classes=["nav-container"])
|
| 23 |
with nav_container:
|
|
@@ -68,7 +73,7 @@ class InterfaceBuilder:
|
|
| 68 |
)
|
| 69 |
|
| 70 |
tutorial_partial_response_display = gr.Textbox(
|
| 71 |
-
label="🤖 Here's
|
| 72 |
lines=5,
|
| 73 |
interactive=False,
|
| 74 |
elem_classes=["assistant-box"],
|
|
@@ -80,7 +85,7 @@ class InterfaceBuilder:
|
|
| 80 |
with gr.Row():
|
| 81 |
with gr.Column(scale=4):
|
| 82 |
tutorial_user_input = gr.Textbox(
|
| 83 |
-
label="✨
|
| 84 |
placeholder="Type a few words to inspire me...",
|
| 85 |
lines=2,
|
| 86 |
elem_classes=["user-box"],
|
|
@@ -150,22 +155,22 @@ class InterfaceBuilder:
|
|
| 150 |
creative_page = gr.Column(visible=False)
|
| 151 |
with creative_page:
|
| 152 |
prompt_display = gr.Textbox(
|
| 153 |
-
label="🎯 Here's what I was asked to
|
| 154 |
lines=3,
|
| 155 |
interactive=False,
|
| 156 |
elem_classes=["prompt-box"]
|
| 157 |
)
|
| 158 |
|
| 159 |
partial_response_display = gr.Textbox(
|
| 160 |
-
label="🤖 Here's
|
| 161 |
lines=5,
|
| 162 |
interactive=False,
|
| 163 |
elem_classes=["assistant-box"]
|
| 164 |
)
|
| 165 |
|
| 166 |
user_input = gr.Textbox(
|
| 167 |
-
label="✨
|
| 168 |
-
placeholder="Type a few words to
|
| 169 |
lines=1, # changed to single line so that "enter" submits the request
|
| 170 |
elem_classes=["user-box"]
|
| 171 |
)
|
|
@@ -341,7 +346,9 @@ class InterfaceBuilder:
|
|
| 341 |
tutorial_step_explanation, tutorial_prompt_display, tutorial_partial_response_display,
|
| 342 |
tutorial_input_section, tutorial_results_section, tutorial_user_input, tutorial_token_counter,
|
| 343 |
tutorial_score_display, tutorial_original_response, tutorial_creative_response,
|
| 344 |
-
tutorial_prev_btn, tutorial_next_btn, tutorial_play_btn
|
|
|
|
|
|
|
| 345 |
)
|
| 346 |
|
| 347 |
# Demo starts with landing page visible
|
|
@@ -362,7 +369,8 @@ class InterfaceBuilder:
|
|
| 362 |
tutorial_step_explanation, tutorial_prompt_display, tutorial_partial_response_display,
|
| 363 |
tutorial_input_section, tutorial_results_section, tutorial_user_input, tutorial_token_counter,
|
| 364 |
tutorial_score_display, tutorial_original_response, tutorial_creative_response,
|
| 365 |
-
tutorial_prev_btn_ref, tutorial_next_btn_ref, tutorial_play_btn_ref
|
|
|
|
| 366 |
"""Wire up all the event handlers for the interface"""
|
| 367 |
|
| 368 |
# Wire up landing page buttons
|
|
@@ -379,7 +387,8 @@ class InterfaceBuilder:
|
|
| 379 |
|
| 380 |
skip_to_game_btn.click(
|
| 381 |
self.page_handlers.start_game,
|
| 382 |
-
|
|
|
|
| 383 |
)
|
| 384 |
|
| 385 |
# Wire up gallery button (handled at end of function)
|
|
@@ -411,7 +420,8 @@ class InterfaceBuilder:
|
|
| 411 |
|
| 412 |
tutorial_play_btn.click(
|
| 413 |
self.page_handlers.load_creative_with_prompt,
|
| 414 |
-
|
|
|
|
| 415 |
js="() => { window.scrollTo({ top: 0, behavior: 'smooth' }); }"
|
| 416 |
)
|
| 417 |
|
|
@@ -445,7 +455,7 @@ class InterfaceBuilder:
|
|
| 445 |
outputs=[submit_btn, loading_message, error_message, landing_page, gallery_page, creative_page, results_page, cosine_distance_display]
|
| 446 |
).then(
|
| 447 |
self.page_handlers.on_submit_process,
|
| 448 |
-
inputs=[user_input],
|
| 449 |
outputs=[submit_btn, loading_message, error_message, landing_page, gallery_page, creative_page, results_page, cosine_distance_display, results_prompt_display, results_partial_display, results_user_input_display, original_response_display, results_continuation_display, violin_plot_display, current_page, has_results, nav_results, nav_session, nav_welcome, nav_tutorial, nav_creative, nav_gallery]
|
| 450 |
)
|
| 451 |
|
|
@@ -455,7 +465,7 @@ class InterfaceBuilder:
|
|
| 455 |
outputs=[submit_btn, loading_message, error_message, landing_page, gallery_page, creative_page, results_page, cosine_distance_display]
|
| 456 |
).then(
|
| 457 |
self.page_handlers.on_submit_process,
|
| 458 |
-
inputs=[user_input],
|
| 459 |
outputs=[submit_btn, loading_message, error_message, landing_page, gallery_page, creative_page, results_page, cosine_distance_display, results_prompt_display, results_partial_display, results_user_input_display, original_response_display, results_continuation_display, violin_plot_display, current_page, has_results, nav_results, nav_session, nav_welcome, nav_tutorial, nav_creative, nav_gallery]
|
| 460 |
)
|
| 461 |
|
|
@@ -469,20 +479,21 @@ class InterfaceBuilder:
|
|
| 469 |
# Try new prompt button - new prompt and switch to creative page
|
| 470 |
try_again_new_btn.click(
|
| 471 |
self.page_handlers.try_new_prompt,
|
| 472 |
-
outputs=[current_page, landing_page, tutorial_page, creative_page, gallery_page, results_page, session_page, nav_welcome, nav_tutorial, nav_creative, nav_gallery, nav_results, nav_session, prompt_display, partial_response_display, submit_btn, user_input, loading_message, error_message, inspire_me_display],
|
| 473 |
js="() => { window.scrollTo({ top: 0, behavior: 'smooth' }); }"
|
| 474 |
)
|
| 475 |
|
| 476 |
# Wire up inspire me button
|
| 477 |
inspire_me_btn.click(
|
| 478 |
self.page_handlers.show_inspire_me_examples,
|
|
|
|
| 479 |
outputs=[inspire_me_display]
|
| 480 |
)
|
| 481 |
|
| 482 |
# Wire up real-time token counter
|
| 483 |
user_input.change(
|
| 484 |
self.page_handlers.update_token_count,
|
| 485 |
-
inputs=[user_input
|
| 486 |
outputs=[token_counter, token_visualization]
|
| 487 |
)
|
| 488 |
|
|
@@ -501,7 +512,8 @@ class InterfaceBuilder:
|
|
| 501 |
|
| 502 |
nav_creative.click(
|
| 503 |
self.page_handlers.load_creative_with_prompt,
|
| 504 |
-
|
|
|
|
| 505 |
js="() => { window.scrollTo({ top: 0, behavior: 'smooth' }); }"
|
| 506 |
)
|
| 507 |
|
|
@@ -520,6 +532,7 @@ class InterfaceBuilder:
|
|
| 520 |
# Update session page when navigating to it
|
| 521 |
nav_session.click(
|
| 522 |
self.page_handlers.navigate_to_session,
|
|
|
|
| 523 |
outputs=[current_page, landing_page, tutorial_page, creative_page, gallery_page, results_page, session_page, nav_welcome, nav_tutorial, nav_creative, nav_gallery, nav_results, nav_session, session_main_stats, session_history_display, session_achievements_display],
|
| 524 |
js="() => { window.scrollTo({ top: 0, behavior: 'smooth' }); }"
|
| 525 |
)
|
|
@@ -530,21 +543,10 @@ class InterfaceBuilder:
|
|
| 530 |
outputs=[current_page, landing_page, tutorial_page, creative_page, gallery_page, results_page, session_page, nav_welcome, nav_tutorial, nav_creative, nav_gallery, nav_results, nav_session],
|
| 531 |
js="() => { window.scrollTo({ top: 0, behavior: 'smooth' }); }"
|
| 532 |
)
|
| 533 |
-
|
| 534 |
-
#
|
| 535 |
-
skip_to_game_btn.click(
|
| 536 |
-
self.page_handlers.load_creative_with_prompt,
|
| 537 |
-
outputs=[current_page, landing_page, tutorial_page, creative_page, gallery_page, results_page, session_page, nav_welcome, nav_tutorial, nav_creative, nav_gallery, nav_results, nav_session, prompt_display, partial_response_display, inspire_me_display],
|
| 538 |
-
js="() => { window.scrollTo({ top: 0, behavior: 'smooth' }); }"
|
| 539 |
-
)
|
| 540 |
-
|
| 541 |
-
tutorial_btn.click(
|
| 542 |
-
self.page_handlers.load_tutorial_with_content,
|
| 543 |
-
outputs=[current_page, landing_page, tutorial_page, creative_page, gallery_page, results_page, session_page, nav_welcome, nav_tutorial, nav_creative, nav_gallery, nav_results, nav_session, tutorial_step_explanation, tutorial_prompt_display, tutorial_partial_response_display, tutorial_input_section, tutorial_results_section, tutorial_prev_btn_ref, tutorial_next_btn_ref, tutorial_play_btn_ref, tutorial_current_step],
|
| 544 |
-
js="() => { window.scrollTo({ top: 0, behavior: 'smooth' }); }"
|
| 545 |
-
)
|
| 546 |
-
|
| 547 |
gallery_btn.click(
|
| 548 |
self.page_handlers.load_gallery_with_content,
|
| 549 |
-
outputs=[current_page, landing_page, tutorial_page, creative_page, gallery_page, results_page, session_page, nav_welcome, nav_tutorial, nav_creative, nav_gallery, nav_results, nav_session, gallery_display]
|
|
|
|
| 550 |
)
|
|
|
|
| 12 |
self.page_handlers = page_handlers
|
| 13 |
|
| 14 |
def create_interface(self):
|
| 15 |
+
with gr.Blocks(title="Help the LLM be Creative!", css_paths=CSS_PATHS) as demo:
|
| 16 |
|
| 17 |
# Navigation state management
|
| 18 |
current_page = gr.State("welcome")
|
| 19 |
has_results = gr.State(False)
|
| 20 |
|
| 21 |
+
# Session and data state management
|
| 22 |
+
current_prompt = gr.State(None)
|
| 23 |
+
session_id = gr.State(None)
|
| 24 |
+
session_data = gr.State({})
|
| 25 |
+
|
| 26 |
# Navigation bar
|
| 27 |
nav_container = gr.Column(elem_classes=["nav-container"])
|
| 28 |
with nav_container:
|
|
|
|
| 73 |
)
|
| 74 |
|
| 75 |
tutorial_partial_response_display = gr.Textbox(
|
| 76 |
+
label="🤖 Here's the boring start of my response... (help me continue creatively!)",
|
| 77 |
lines=5,
|
| 78 |
interactive=False,
|
| 79 |
elem_classes=["assistant-box"],
|
|
|
|
| 85 |
with gr.Row():
|
| 86 |
with gr.Column(scale=4):
|
| 87 |
tutorial_user_input = gr.Textbox(
|
| 88 |
+
label="✨ Continue where my response above leaves off, and then I'll finish the response after you (max 5 tokens)",
|
| 89 |
placeholder="Type a few words to inspire me...",
|
| 90 |
lines=2,
|
| 91 |
elem_classes=["user-box"],
|
|
|
|
| 155 |
creative_page = gr.Column(visible=False)
|
| 156 |
with creative_page:
|
| 157 |
prompt_display = gr.Textbox(
|
| 158 |
+
label="🎯 Here's what I was asked to do:",
|
| 159 |
lines=3,
|
| 160 |
interactive=False,
|
| 161 |
elem_classes=["prompt-box"]
|
| 162 |
)
|
| 163 |
|
| 164 |
partial_response_display = gr.Textbox(
|
| 165 |
+
label="🤖 Here's the boring start of my response... (help me continue creatively!)",
|
| 166 |
lines=5,
|
| 167 |
interactive=False,
|
| 168 |
elem_classes=["assistant-box"]
|
| 169 |
)
|
| 170 |
|
| 171 |
user_input = gr.Textbox(
|
| 172 |
+
label="✨ Continue where my response above leaves off, and then I'll finish the response after you (max 5 tokens)",
|
| 173 |
+
placeholder="Type a few words to continue my response...",
|
| 174 |
lines=1, # changed to single line so that "enter" submits the request
|
| 175 |
elem_classes=["user-box"]
|
| 176 |
)
|
|
|
|
| 346 |
tutorial_step_explanation, tutorial_prompt_display, tutorial_partial_response_display,
|
| 347 |
tutorial_input_section, tutorial_results_section, tutorial_user_input, tutorial_token_counter,
|
| 348 |
tutorial_score_display, tutorial_original_response, tutorial_creative_response,
|
| 349 |
+
tutorial_prev_btn, tutorial_next_btn, tutorial_play_btn,
|
| 350 |
+
# State variables
|
| 351 |
+
current_prompt, session_id, session_data
|
| 352 |
)
|
| 353 |
|
| 354 |
# Demo starts with landing page visible
|
|
|
|
| 369 |
tutorial_step_explanation, tutorial_prompt_display, tutorial_partial_response_display,
|
| 370 |
tutorial_input_section, tutorial_results_section, tutorial_user_input, tutorial_token_counter,
|
| 371 |
tutorial_score_display, tutorial_original_response, tutorial_creative_response,
|
| 372 |
+
tutorial_prev_btn_ref, tutorial_next_btn_ref, tutorial_play_btn_ref,
|
| 373 |
+
current_prompt, session_id, session_data):
|
| 374 |
"""Wire up all the event handlers for the interface"""
|
| 375 |
|
| 376 |
# Wire up landing page buttons
|
|
|
|
| 387 |
|
| 388 |
skip_to_game_btn.click(
|
| 389 |
self.page_handlers.start_game,
|
| 390 |
+
inputs=[current_prompt, session_id],
|
| 391 |
+
outputs=[current_page, landing_page, tutorial_page, creative_page, gallery_page, results_page, session_page, nav_welcome, nav_tutorial, nav_creative, nav_gallery, nav_results, nav_session, prompt_display, partial_response_display, inspire_me_display, current_prompt, session_id]
|
| 392 |
)
|
| 393 |
|
| 394 |
# Wire up gallery button (handled at end of function)
|
|
|
|
| 420 |
|
| 421 |
tutorial_play_btn.click(
|
| 422 |
self.page_handlers.load_creative_with_prompt,
|
| 423 |
+
inputs=[current_prompt, session_id],
|
| 424 |
+
outputs=[current_page, landing_page, tutorial_page, creative_page, gallery_page, results_page, session_page, nav_welcome, nav_tutorial, nav_creative, nav_gallery, nav_results, nav_session, prompt_display, partial_response_display, inspire_me_display, current_prompt, session_id],
|
| 425 |
js="() => { window.scrollTo({ top: 0, behavior: 'smooth' }); }"
|
| 426 |
)
|
| 427 |
|
|
|
|
| 455 |
outputs=[submit_btn, loading_message, error_message, landing_page, gallery_page, creative_page, results_page, cosine_distance_display]
|
| 456 |
).then(
|
| 457 |
self.page_handlers.on_submit_process,
|
| 458 |
+
inputs=[user_input, current_prompt, session_id],
|
| 459 |
outputs=[submit_btn, loading_message, error_message, landing_page, gallery_page, creative_page, results_page, cosine_distance_display, results_prompt_display, results_partial_display, results_user_input_display, original_response_display, results_continuation_display, violin_plot_display, current_page, has_results, nav_results, nav_session, nav_welcome, nav_tutorial, nav_creative, nav_gallery]
|
| 460 |
)
|
| 461 |
|
|
|
|
| 465 |
outputs=[submit_btn, loading_message, error_message, landing_page, gallery_page, creative_page, results_page, cosine_distance_display]
|
| 466 |
).then(
|
| 467 |
self.page_handlers.on_submit_process,
|
| 468 |
+
inputs=[user_input, current_prompt, session_id],
|
| 469 |
outputs=[submit_btn, loading_message, error_message, landing_page, gallery_page, creative_page, results_page, cosine_distance_display, results_prompt_display, results_partial_display, results_user_input_display, original_response_display, results_continuation_display, violin_plot_display, current_page, has_results, nav_results, nav_session, nav_welcome, nav_tutorial, nav_creative, nav_gallery]
|
| 470 |
)
|
| 471 |
|
|
|
|
| 479 |
# Try new prompt button - new prompt and switch to creative page
|
| 480 |
try_again_new_btn.click(
|
| 481 |
self.page_handlers.try_new_prompt,
|
| 482 |
+
outputs=[current_page, landing_page, tutorial_page, creative_page, gallery_page, results_page, session_page, nav_welcome, nav_tutorial, nav_creative, nav_gallery, nav_results, nav_session, prompt_display, partial_response_display, submit_btn, user_input, loading_message, error_message, inspire_me_display, current_prompt],
|
| 483 |
js="() => { window.scrollTo({ top: 0, behavior: 'smooth' }); }"
|
| 484 |
)
|
| 485 |
|
| 486 |
# Wire up inspire me button
|
| 487 |
inspire_me_btn.click(
|
| 488 |
self.page_handlers.show_inspire_me_examples,
|
| 489 |
+
inputs=[current_prompt],
|
| 490 |
outputs=[inspire_me_display]
|
| 491 |
)
|
| 492 |
|
| 493 |
# Wire up real-time token counter
|
| 494 |
user_input.change(
|
| 495 |
self.page_handlers.update_token_count,
|
| 496 |
+
inputs=[user_input],
|
| 497 |
outputs=[token_counter, token_visualization]
|
| 498 |
)
|
| 499 |
|
|
|
|
| 512 |
|
| 513 |
nav_creative.click(
|
| 514 |
self.page_handlers.load_creative_with_prompt,
|
| 515 |
+
inputs=[current_prompt, session_id],
|
| 516 |
+
outputs=[current_page, landing_page, tutorial_page, creative_page, gallery_page, results_page, session_page, nav_welcome, nav_tutorial, nav_creative, nav_gallery, nav_results, nav_session, prompt_display, partial_response_display, inspire_me_display, current_prompt, session_id],
|
| 517 |
js="() => { window.scrollTo({ top: 0, behavior: 'smooth' }); }"
|
| 518 |
)
|
| 519 |
|
|
|
|
| 532 |
# Update session page when navigating to it
|
| 533 |
nav_session.click(
|
| 534 |
self.page_handlers.navigate_to_session,
|
| 535 |
+
inputs=[session_id],
|
| 536 |
outputs=[current_page, landing_page, tutorial_page, creative_page, gallery_page, results_page, session_page, nav_welcome, nav_tutorial, nav_creative, nav_gallery, nav_results, nav_session, session_main_stats, session_history_display, session_achievements_display],
|
| 537 |
js="() => { window.scrollTo({ top: 0, behavior: 'smooth' }); }"
|
| 538 |
)
|
|
|
|
| 543 |
outputs=[current_page, landing_page, tutorial_page, creative_page, gallery_page, results_page, session_page, nav_welcome, nav_tutorial, nav_creative, nav_gallery, nav_results, nav_session],
|
| 544 |
js="() => { window.scrollTo({ top: 0, behavior: 'smooth' }); }"
|
| 545 |
)
|
| 546 |
+
|
| 547 |
+
# Wire up gallery button from landing page
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 548 |
gallery_btn.click(
|
| 549 |
self.page_handlers.load_gallery_with_content,
|
| 550 |
+
outputs=[current_page, landing_page, tutorial_page, creative_page, gallery_page, results_page, session_page, nav_welcome, nav_tutorial, nav_creative, nav_gallery, nav_results, nav_session, gallery_display],
|
| 551 |
+
js="() => { window.scrollTo({ top: 0, behavior: 'smooth' }); }"
|
| 552 |
)
|
src/ui/page_handlers.py
CHANGED
|
@@ -1,7 +1,9 @@
|
|
| 1 |
"""Page handling and navigation functionality"""
|
|
|
|
| 2 |
|
| 3 |
import gradio as gr
|
| 4 |
from ..config.settings import TUTORIAL_EXAMPLE
|
|
|
|
| 5 |
|
| 6 |
|
| 7 |
class PageHandlers:
|
|
@@ -116,14 +118,14 @@ class PageHandlers:
|
|
| 116 |
|
| 117 |
return gallery_html
|
| 118 |
|
| 119 |
-
def show_inspire_me_examples(self):
|
| 120 |
"""Show new random inspiring examples for current prompt"""
|
| 121 |
-
if not
|
| 122 |
return ""
|
| 123 |
|
| 124 |
examples = self.app.data_manager.get_inspire_me_examples(
|
| 125 |
-
|
| 126 |
-
|
| 127 |
limit=5
|
| 128 |
)
|
| 129 |
|
|
@@ -269,21 +271,31 @@ class PageHandlers:
|
|
| 269 |
prev_step # Update tutorial step
|
| 270 |
)
|
| 271 |
|
| 272 |
-
def start_game(self):
|
| 273 |
-
"""Start the game"""
|
| 274 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 275 |
# Load initial inspire me examples
|
| 276 |
initial_examples = self.app.data_manager.get_inspire_me_examples(
|
| 277 |
-
|
| 278 |
-
|
| 279 |
limit=5
|
| 280 |
)
|
| 281 |
inspire_html = self.generate_inspire_me_html(initial_examples)
|
| 282 |
switch_result = self.switch_to_page("creative", update_nav=False)
|
| 283 |
return switch_result + (
|
| 284 |
-
|
| 285 |
-
|
| 286 |
-
inspire_html
|
|
|
|
|
|
|
| 287 |
)
|
| 288 |
|
| 289 |
def back_to_landing(self):
|
|
@@ -291,7 +303,7 @@ class PageHandlers:
|
|
| 291 |
result = self.switch_to_page("welcome", update_nav=True)
|
| 292 |
return result + ("",) # Add empty gallery_display as the 14th output
|
| 293 |
|
| 294 |
-
def update_token_count(self, text
|
| 295 |
"""Update token counter and visual tokens in real-time"""
|
| 296 |
if not text.strip():
|
| 297 |
return (
|
|
@@ -360,8 +372,8 @@ class PageHandlers:
|
|
| 360 |
gr.update()
|
| 361 |
)
|
| 362 |
|
| 363 |
-
def on_submit_process(self, user_text):
|
| 364 |
-
result = self.app.process_submission(user_text)
|
| 365 |
generated_response, cosine_distance, rank, percentile, mean_score, violin_plot, prompt_results = result
|
| 366 |
|
| 367 |
if "Error:" in generated_response or "Please" in generated_response:
|
|
@@ -410,10 +422,10 @@ class PageHandlers:
|
|
| 410 |
gr.update(visible=False), # creative_page (hide)
|
| 411 |
gr.update(visible=True), # results_page (show)
|
| 412 |
gr.update(visible=True, value=score_text), # cosine_distance_display
|
| 413 |
-
gr.update(value=
|
| 414 |
-
gr.update(value=
|
| 415 |
gr.update(value=user_text), # results_user_input_display
|
| 416 |
-
gr.update(value=
|
| 417 |
gr.update(value=generated_response), # results_continuation_display
|
| 418 |
gr.update(visible=True, value=violin_plot) if violin_plot else gr.update(visible=False), # violin_plot_display
|
| 419 |
"results", # current_page state
|
|
@@ -438,35 +450,43 @@ class PageHandlers:
|
|
| 438 |
)
|
| 439 |
|
| 440 |
def try_new_prompt(self):
|
| 441 |
-
|
| 442 |
initial_examples = self.app.data_manager.get_inspire_me_examples(
|
| 443 |
-
|
| 444 |
-
|
| 445 |
limit=5
|
| 446 |
)
|
| 447 |
inspire_html = self.generate_inspire_me_html(initial_examples)
|
| 448 |
switch_result = self.switch_to_page("creative")
|
| 449 |
return switch_result + (
|
| 450 |
-
|
| 451 |
-
|
| 452 |
gr.update(interactive=True), # submit_btn
|
| 453 |
"", # user_input (clear)
|
| 454 |
gr.update(visible=False), # loading_message
|
| 455 |
gr.update(visible=False), # error_message
|
| 456 |
-
inspire_html
|
|
|
|
| 457 |
)
|
| 458 |
|
| 459 |
-
def load_creative_with_prompt(self):
|
| 460 |
"""Load creative page with a new prompt"""
|
| 461 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 462 |
initial_examples = self.app.data_manager.get_inspire_me_examples(
|
| 463 |
-
|
| 464 |
-
|
| 465 |
limit=5
|
| 466 |
)
|
| 467 |
inspire_html = self.generate_inspire_me_html(initial_examples)
|
| 468 |
switch_result = self.switch_to_page("creative")
|
| 469 |
-
return switch_result + (
|
| 470 |
|
| 471 |
def load_gallery_with_content(self):
|
| 472 |
"""Load gallery page with gallery content"""
|
|
@@ -491,8 +511,16 @@ class PageHandlers:
|
|
| 491 |
1 # Reset tutorial step to 1
|
| 492 |
)
|
| 493 |
|
| 494 |
-
def navigate_to_session(self):
|
| 495 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 496 |
self.app.template_renderer,
|
| 497 |
self.app.statistics_calculator,
|
| 498 |
self.app.scorer
|
|
|
|
| 1 |
"""Page handling and navigation functionality"""
|
| 2 |
+
import uuid
|
| 3 |
|
| 4 |
import gradio as gr
|
| 5 |
from ..config.settings import TUTORIAL_EXAMPLE
|
| 6 |
+
from ..session.session_manager import SessionManager
|
| 7 |
|
| 8 |
|
| 9 |
class PageHandlers:
|
|
|
|
| 118 |
|
| 119 |
return gallery_html
|
| 120 |
|
| 121 |
+
def show_inspire_me_examples(self, current_prompt):
|
| 122 |
"""Show new random inspiring examples for current prompt"""
|
| 123 |
+
if not current_prompt:
|
| 124 |
return ""
|
| 125 |
|
| 126 |
examples = self.app.data_manager.get_inspire_me_examples(
|
| 127 |
+
current_prompt["prompt"],
|
| 128 |
+
current_prompt["llm_partial_response"],
|
| 129 |
limit=5
|
| 130 |
)
|
| 131 |
|
|
|
|
| 271 |
prev_step # Update tutorial step
|
| 272 |
)
|
| 273 |
|
| 274 |
+
def start_game(self, current_prompt, session_id):
|
| 275 |
+
"""Start the game with state management"""
|
| 276 |
+
|
| 277 |
+
# Initialize session if needed
|
| 278 |
+
if session_id is None:
|
| 279 |
+
session_id = str(uuid.uuid4())
|
| 280 |
+
|
| 281 |
+
# Get new prompt if needed
|
| 282 |
+
if current_prompt is None:
|
| 283 |
+
current_prompt = self.app.get_random_prompt()
|
| 284 |
+
|
| 285 |
# Load initial inspire me examples
|
| 286 |
initial_examples = self.app.data_manager.get_inspire_me_examples(
|
| 287 |
+
current_prompt["prompt"],
|
| 288 |
+
current_prompt["llm_partial_response"],
|
| 289 |
limit=5
|
| 290 |
)
|
| 291 |
inspire_html = self.generate_inspire_me_html(initial_examples)
|
| 292 |
switch_result = self.switch_to_page("creative", update_nav=False)
|
| 293 |
return switch_result + (
|
| 294 |
+
current_prompt['prompt'],
|
| 295 |
+
current_prompt['llm_partial_response'],
|
| 296 |
+
inspire_html,
|
| 297 |
+
current_prompt,
|
| 298 |
+
session_id
|
| 299 |
)
|
| 300 |
|
| 301 |
def back_to_landing(self):
|
|
|
|
| 303 |
result = self.switch_to_page("welcome", update_nav=True)
|
| 304 |
return result + ("",) # Add empty gallery_display as the 14th output
|
| 305 |
|
| 306 |
+
def update_token_count(self, text):
|
| 307 |
"""Update token counter and visual tokens in real-time"""
|
| 308 |
if not text.strip():
|
| 309 |
return (
|
|
|
|
| 372 |
gr.update()
|
| 373 |
)
|
| 374 |
|
| 375 |
+
def on_submit_process(self, user_text, current_prompt, session_id):
|
| 376 |
+
result = self.app.process_submission(user_text, current_prompt, session_id)
|
| 377 |
generated_response, cosine_distance, rank, percentile, mean_score, violin_plot, prompt_results = result
|
| 378 |
|
| 379 |
if "Error:" in generated_response or "Please" in generated_response:
|
|
|
|
| 422 |
gr.update(visible=False), # creative_page (hide)
|
| 423 |
gr.update(visible=True), # results_page (show)
|
| 424 |
gr.update(visible=True, value=score_text), # cosine_distance_display
|
| 425 |
+
gr.update(value=current_prompt['prompt']), # results_prompt_display
|
| 426 |
+
gr.update(value=current_prompt['llm_partial_response']), # results_partial_display
|
| 427 |
gr.update(value=user_text), # results_user_input_display
|
| 428 |
+
gr.update(value=current_prompt['llm_full_response_original']), # original_response_display
|
| 429 |
gr.update(value=generated_response), # results_continuation_display
|
| 430 |
gr.update(visible=True, value=violin_plot) if violin_plot else gr.update(visible=False), # violin_plot_display
|
| 431 |
"results", # current_page state
|
|
|
|
| 450 |
)
|
| 451 |
|
| 452 |
def try_new_prompt(self):
|
| 453 |
+
new_prompt = self.app.get_random_prompt()
|
| 454 |
initial_examples = self.app.data_manager.get_inspire_me_examples(
|
| 455 |
+
new_prompt["prompt"],
|
| 456 |
+
new_prompt["llm_partial_response"],
|
| 457 |
limit=5
|
| 458 |
)
|
| 459 |
inspire_html = self.generate_inspire_me_html(initial_examples)
|
| 460 |
switch_result = self.switch_to_page("creative")
|
| 461 |
return switch_result + (
|
| 462 |
+
new_prompt['prompt'], # prompt_display
|
| 463 |
+
new_prompt['llm_partial_response'], # partial_response_display
|
| 464 |
gr.update(interactive=True), # submit_btn
|
| 465 |
"", # user_input (clear)
|
| 466 |
gr.update(visible=False), # loading_message
|
| 467 |
gr.update(visible=False), # error_message
|
| 468 |
+
inspire_html, # inspire_me_display
|
| 469 |
+
new_prompt # current_prompt state update
|
| 470 |
)
|
| 471 |
|
| 472 |
+
def load_creative_with_prompt(self, current_prompt, session_id):
|
| 473 |
"""Load creative page with a new prompt"""
|
| 474 |
+
|
| 475 |
+
# Initialize session if needed
|
| 476 |
+
if session_id is None:
|
| 477 |
+
session_id = str(uuid.uuid4())
|
| 478 |
+
|
| 479 |
+
# Get new prompt (if none provided)
|
| 480 |
+
if current_prompt is None:
|
| 481 |
+
current_prompt = self.app.get_random_prompt()
|
| 482 |
initial_examples = self.app.data_manager.get_inspire_me_examples(
|
| 483 |
+
current_prompt["prompt"],
|
| 484 |
+
current_prompt["llm_partial_response"],
|
| 485 |
limit=5
|
| 486 |
)
|
| 487 |
inspire_html = self.generate_inspire_me_html(initial_examples)
|
| 488 |
switch_result = self.switch_to_page("creative")
|
| 489 |
+
return switch_result + (current_prompt['prompt'], current_prompt['llm_partial_response'], inspire_html, current_prompt, session_id)
|
| 490 |
|
| 491 |
def load_gallery_with_content(self):
|
| 492 |
"""Load gallery page with gallery content"""
|
|
|
|
| 511 |
1 # Reset tutorial step to 1
|
| 512 |
)
|
| 513 |
|
| 514 |
+
def navigate_to_session(self, session_id):
|
| 515 |
+
|
| 516 |
+
# Create session manager instance with session_id
|
| 517 |
+
session_manager = SessionManager(
|
| 518 |
+
session_id=session_id,
|
| 519 |
+
data_manager=self.app.data_manager,
|
| 520 |
+
achievement_system=self.app.achievement_system
|
| 521 |
+
)
|
| 522 |
+
|
| 523 |
+
main_stats, history, achievements = session_manager.generate_session_page_html(
|
| 524 |
self.app.template_renderer,
|
| 525 |
self.app.statistics_calculator,
|
| 526 |
self.app.scorer
|