コミットを比較
22 コミット
| 作成者 | SHA1 | 日付 | |
|---|---|---|---|
| 53446807c2 | |||
| 5fbb737c70 | |||
| a5d08c99cf | |||
| 2522485f6a | |||
| de5db81e16 | |||
| fd90ef3b15 | |||
| 4caea6213a | |||
| 884a7bc3da | |||
| f936c1e5ce | |||
| 8bf51bbb4a | |||
| 480a06caaf | |||
| 7fe7dbd909 | |||
| 159ad5ed5a | |||
| ae1deaac8c | |||
| be5359eb84 | |||
| a1ea35a7ec | |||
| 49d42d576a | |||
| 77b5c8f262 | |||
| 543f051f8f | |||
| fb2b2a632c | |||
| de21141f5a | |||
| 96df2a4eaa |
@@ -158,13 +158,6 @@ npm run preview
|
||||
- Keep page-level code under `frontend/src/pages` and shared UI/feature code
|
||||
under `frontend/src/components` unless existing patterns point elsewhere.
|
||||
- Match existing Tailwind, component, and import alias conventions.
|
||||
- In TypeScript and TSX, prefer direct comparison operators such as `===` and
|
||||
`!==` over negating a comparison like `!(a === b)`.
|
||||
- In TypeScript and TSX, prefer `++i` or `--i` over `i += 1` or `i -= 1` for
|
||||
simple unit-step counter updates.
|
||||
- For user-facing Japanese text, prefer modern kana usage and natural current
|
||||
phrasing over historical spellings or awkward literal wording.
|
||||
- For user-facing Japanese ellipses, prefer `……` over ASCII `...`.
|
||||
|
||||
### Frontend TSX style
|
||||
|
||||
@@ -186,9 +179,6 @@ npm run preview
|
||||
single physical line.
|
||||
- Always add braces around `if`, `else`, or `for` bodies when the body spans
|
||||
two or more physical lines, even if it is one statement.
|
||||
- Do not use a leading semicolon for expression statements such as
|
||||
`;([...]).forEach(...)`; rewrite the expression to avoid ASI hazards
|
||||
explicitly, for example with `void`.
|
||||
|
||||
Preferred:
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
class GekanatorGamesController < ApplicationController
|
||||
def create
|
||||
return head :unauthorized unless current_user
|
||||
return head :not_found unless current_user&.admin?
|
||||
|
||||
guessed_post_id = params.require(:guessed_post_id)
|
||||
correct_post_id = params[:correct_post_id].presence
|
||||
@@ -14,29 +14,18 @@ class GekanatorGamesController < ApplicationController
|
||||
question_count: answers.length,
|
||||
answers:)
|
||||
|
||||
if game.invalid?
|
||||
if game.save
|
||||
render json: { id: game.id }, status: :created
|
||||
else
|
||||
render json: { errors: game.errors.full_messages }, status: :unprocessable_entity
|
||||
return
|
||||
end
|
||||
|
||||
learned_example_count = 0
|
||||
|
||||
ActiveRecord::Base.transaction do
|
||||
game.save!
|
||||
learned_example_count = learn_answers_from_game!(game)
|
||||
end
|
||||
|
||||
render json: {
|
||||
id: game.id,
|
||||
learned_example_count:
|
||||
}, status: :created
|
||||
rescue ActiveRecord::RecordInvalid => e
|
||||
render json: { errors: e.record.errors.full_messages }, status: :unprocessable_entity
|
||||
end
|
||||
|
||||
def extra_questions
|
||||
game = find_owned_game
|
||||
return if performed?
|
||||
return head :not_found unless current_user&.admin?
|
||||
|
||||
game = GekanatorGame.find_by(id: params[:id])
|
||||
return head :not_found unless game
|
||||
|
||||
questions =
|
||||
GekanatorQuestion
|
||||
@@ -45,12 +34,10 @@ class GekanatorGamesController < ApplicationController
|
||||
.where(kind: 'post_similarity', source: 'user_suggested')
|
||||
.to_a
|
||||
|
||||
selected =
|
||||
prioritized_extra_questions(
|
||||
questions,
|
||||
post_id: game.correct_post_id,
|
||||
user: current_user,
|
||||
limit: 2)
|
||||
selected = weighted_sample_questions(
|
||||
questions,
|
||||
post_id: game.correct_post_id,
|
||||
limit: 2)
|
||||
|
||||
render json: {
|
||||
questions: selected.map { |question| extra_question_json(question) }
|
||||
@@ -58,8 +45,10 @@ class GekanatorGamesController < ApplicationController
|
||||
end
|
||||
|
||||
def extra_question_answers
|
||||
game = find_owned_game
|
||||
return if performed?
|
||||
return head :not_found unless current_user&.admin?
|
||||
|
||||
game = GekanatorGame.find_by(id: params[:id])
|
||||
return head :not_found unless game
|
||||
|
||||
answer_params = params.require(:answers)
|
||||
if !answer_params.is_a?(Array)
|
||||
@@ -111,23 +100,6 @@ class GekanatorGamesController < ApplicationController
|
||||
}
|
||||
end
|
||||
|
||||
def prioritized_extra_questions questions, post_id:, user:, limit:
|
||||
answered_question_ids =
|
||||
GekanatorQuestionExample
|
||||
.where(user:, gekanator_question_id: questions.map(&:id))
|
||||
.distinct
|
||||
.pluck(:gekanator_question_id)
|
||||
unanswered, answered =
|
||||
questions.partition { |question| !answered_question_ids.include?(question.id) }
|
||||
selected = weighted_sample_questions(unanswered, post_id:, limit:)
|
||||
return selected if selected.length >= limit
|
||||
|
||||
selected + weighted_sample_questions(
|
||||
answered.reject { |question| selected.any? { _1.id == question.id } },
|
||||
post_id:,
|
||||
limit: limit - selected.length)
|
||||
end
|
||||
|
||||
def weighted_sample_questions questions, post_id:, limit:
|
||||
remaining = questions.uniq(&:id)
|
||||
selected = []
|
||||
@@ -165,97 +137,4 @@ class GekanatorGamesController < ApplicationController
|
||||
|
||||
question.priority_weight.to_f / (1.0 + sample_count * 0.15)
|
||||
end
|
||||
|
||||
def find_owned_game
|
||||
return head :unauthorized unless current_user
|
||||
|
||||
game = GekanatorGame.find_by(id: params[:id])
|
||||
return head :not_found unless game
|
||||
if !current_user.admin? && game.user_id != current_user.id
|
||||
return head :not_found
|
||||
end
|
||||
|
||||
game
|
||||
end
|
||||
|
||||
def learn_answers_from_game! game
|
||||
correct_post = game.correct_post
|
||||
return 0 if correct_post.blank?
|
||||
|
||||
accepted_questions =
|
||||
GekanatorQuestion
|
||||
.accepted
|
||||
.index_by { |question| public_question_id_for(question) }
|
||||
learned_count = 0
|
||||
|
||||
Array(game.answers).each do |answer|
|
||||
answer_value = answer['answer'].to_s
|
||||
next if answer_value.blank? || answer_value == 'unknown'
|
||||
|
||||
question = accepted_questions[answer['question_id'].to_s]
|
||||
next unless learnable_game_answer_question?(question)
|
||||
|
||||
example =
|
||||
GekanatorQuestionExample.find_or_initialize_by(
|
||||
gekanator_question: question,
|
||||
post: correct_post,
|
||||
user: current_user)
|
||||
example.record_answer!(
|
||||
answer: answer_value,
|
||||
source: 'post_game_answer',
|
||||
gekanator_game: game)
|
||||
example.save!
|
||||
learned_count += 1
|
||||
end
|
||||
|
||||
learned_count
|
||||
end
|
||||
|
||||
def public_question_id_for question
|
||||
condition = normalize_condition(question.condition)
|
||||
|
||||
case condition[:type]
|
||||
when 'tag'
|
||||
"tag:#{condition[:key]}"
|
||||
when 'source'
|
||||
"source:#{condition[:host]}"
|
||||
when 'original-year'
|
||||
"original-year:#{condition[:year]}"
|
||||
when 'original-month'
|
||||
"original-month:#{condition[:month]}"
|
||||
when 'original-month-day'
|
||||
"original-month-day:#{condition[:monthDay] || condition[:month_day]}"
|
||||
when 'title-length-at-least'
|
||||
"title:length-at-least:#{condition[:length]}"
|
||||
when 'title-length-greater-than'
|
||||
"title:length-at-least:#{condition[:length].to_i + 1}"
|
||||
when 'title-has-ascii'
|
||||
'title:ascii'
|
||||
when 'title-contains'
|
||||
"title:contains:#{condition[:text]}"
|
||||
when 'post-similarity'
|
||||
"post-similarity:#{question.id}"
|
||||
else
|
||||
"catalog:#{question.id}"
|
||||
end
|
||||
end
|
||||
|
||||
def normalize_condition condition
|
||||
json = condition.deep_dup.as_json
|
||||
|
||||
if json['type'] == 'original-month-day' && json['monthDay'].blank?
|
||||
json['monthDay'] = json.delete('month_day')
|
||||
end
|
||||
|
||||
json.deep_symbolize_keys
|
||||
end
|
||||
|
||||
def learnable_game_answer_question? question
|
||||
return true if question.kind == 'post_similarity'
|
||||
return false unless question.kind == 'tag'
|
||||
|
||||
condition = normalize_condition(question.condition)
|
||||
key = condition[:key].to_s
|
||||
!key.start_with?('nico:')
|
||||
end
|
||||
end
|
||||
|
||||
@@ -1,8 +1,10 @@
|
||||
class GekanatorPostsController < ApplicationController
|
||||
def index
|
||||
return head :not_found unless current_user&.admin?
|
||||
|
||||
posts =
|
||||
Post
|
||||
.preload(:post_similarities, tags: :tag_name)
|
||||
.preload(tags: :tag_name)
|
||||
.with_attached_thumbnail
|
||||
.order(Arel.sql(
|
||||
'COALESCE(posts.original_created_before - INTERVAL 1 MINUTE, ' \
|
||||
@@ -22,12 +24,6 @@ class GekanatorPostsController < ApplicationController
|
||||
thumbnail_base: post.thumbnail_base,
|
||||
original_created_from: post.original_created_from,
|
||||
original_created_before: post.original_created_before,
|
||||
post_similarity_edges: post.post_similarities.map { |similarity|
|
||||
{
|
||||
target_post_id: similarity.target_post_id,
|
||||
cos: similarity.cos.to_f
|
||||
}
|
||||
},
|
||||
tags: post.tags.map { |tag| tag_json(tag) }
|
||||
}
|
||||
end
|
||||
|
||||
@@ -1,41 +1,9 @@
|
||||
class GekanatorQuestionSuggestionsController < ApplicationController
|
||||
def create
|
||||
return head :unauthorized unless current_user
|
||||
return head :not_found unless current_user&.admin?
|
||||
|
||||
game = GekanatorGame.find_by(id: params.require(:gekanator_game_id))
|
||||
return head :not_found unless game
|
||||
if !current_user.admin? && game.user_id != current_user.id
|
||||
return head :not_found
|
||||
end
|
||||
|
||||
existing_question_id = params[:existing_question_id].presence
|
||||
if existing_question_id
|
||||
question = GekanatorQuestion.accepted.find_by(id: existing_question_id)
|
||||
return head :not_found unless question
|
||||
unless learnable_existing_question?(question)
|
||||
return render_validation_error fields: { existing_question_id: ['質問が不正です.'] }
|
||||
end
|
||||
|
||||
example =
|
||||
GekanatorQuestionExample.find_or_initialize_by(
|
||||
gekanator_question: question,
|
||||
post: game.correct_post,
|
||||
user: current_user)
|
||||
example.record_answer!(
|
||||
answer: params.require(:answer),
|
||||
source: 'post_game_extra',
|
||||
gekanator_game: game)
|
||||
|
||||
if example.save
|
||||
render json: {
|
||||
id: question.id,
|
||||
count: game.question_suggestions.count
|
||||
}, status: :created
|
||||
else
|
||||
render_validation_error example
|
||||
end
|
||||
return
|
||||
end
|
||||
|
||||
suggestion = GekanatorQuestionSuggestion.new(
|
||||
gekanator_game: game,
|
||||
@@ -82,14 +50,4 @@ class GekanatorQuestionSuggestionsController < ApplicationController
|
||||
rescue NotImplementedError
|
||||
head :not_implemented
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def learnable_existing_question? question
|
||||
return true if question.kind == 'post_similarity'
|
||||
return false unless question.kind == 'tag'
|
||||
|
||||
key = question.condition.as_json['key'].to_s
|
||||
!key.start_with?('nico:')
|
||||
end
|
||||
end
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
class GekanatorQuestionsController < ApplicationController
|
||||
def index
|
||||
return head :not_found unless current_user&.admin?
|
||||
|
||||
questions =
|
||||
GekanatorQuestion
|
||||
.accepted
|
||||
@@ -16,7 +18,6 @@ class GekanatorQuestionsController < ApplicationController
|
||||
def question_json question
|
||||
condition = condition_json(question.condition).deep_symbolize_keys
|
||||
json = {
|
||||
record_id: question.id,
|
||||
id: question_id_for(question, condition),
|
||||
text: question_text_for(question, condition),
|
||||
kind: question.kind,
|
||||
@@ -24,7 +25,7 @@ class GekanatorQuestionsController < ApplicationController
|
||||
source: question.source,
|
||||
priority_weight: question.priority_weight
|
||||
}
|
||||
if question.kind == 'post_similarity' || question.kind == 'tag'
|
||||
if question.kind == 'post_similarity'
|
||||
json[:example_answers] = example_answers_json(question)
|
||||
end
|
||||
json
|
||||
@@ -48,8 +49,6 @@ class GekanatorQuestionsController < ApplicationController
|
||||
"title:length-at-least:#{ condition[:length].to_i + 1 }"
|
||||
when 'title-has-ascii'
|
||||
'title:ascii'
|
||||
when 'title-contains'
|
||||
"title:contains:#{ condition[:text] }"
|
||||
when 'post-similarity'
|
||||
"post-similarity:#{ question.id }"
|
||||
else
|
||||
@@ -78,8 +77,6 @@ class GekanatorQuestionsController < ApplicationController
|
||||
case condition[:type]
|
||||
when 'title-length-at-least'
|
||||
"タイトルは #{ condition[:length] } 文字以上?"
|
||||
when 'title-contains'
|
||||
"題名に「#{ condition[:text] }」が含まれる?"
|
||||
else
|
||||
question.text
|
||||
end
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
class GekanatorQuestionExample < ApplicationRecord
|
||||
ANSWERS = GekanatorQuestionSuggestion::ANSWERS
|
||||
NON_UNKNOWN_ANSWERS = ANSWERS - ['unknown']
|
||||
SOURCES = ['initial_suggestion', 'post_game_answer', 'post_game_extra'].freeze
|
||||
SOURCES = ['initial_suggestion', 'post_game_extra'].freeze
|
||||
|
||||
belongs_to :gekanator_question
|
||||
belongs_to :post
|
||||
@@ -35,7 +35,7 @@ class GekanatorQuestionExample < ApplicationRecord
|
||||
self.answer_counts = counts
|
||||
self.sample_count = counts.values.sum
|
||||
self.gekanator_game = gekanator_game if gekanator_game.present?
|
||||
self.source = source
|
||||
self.source = source if new_record?
|
||||
|
||||
apply_aggregated_answer!(preferred_answer: answer)
|
||||
self
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
class GekanatorQuestionSuggestion < ApplicationRecord
|
||||
MAX_QUESTIONS_PER_GAME = 3
|
||||
ANSWERS = ['yes', 'no', 'partial', 'probably_no', 'unknown'].freeze
|
||||
|
||||
belongs_to :gekanator_game
|
||||
@@ -9,4 +10,16 @@ class GekanatorQuestionSuggestion < ApplicationRecord
|
||||
validates :question_text, presence: true, length: { maximum: 1000 }
|
||||
validates :answer, presence: true, inclusion: { in: ANSWERS }
|
||||
validates :processed, inclusion: { in: [true, false] }
|
||||
validate :question_suggestion_limit_per_game, on: :create
|
||||
|
||||
private
|
||||
|
||||
def question_suggestion_limit_per_game
|
||||
return if gekanator_game_id.blank?
|
||||
|
||||
count = GekanatorQuestionSuggestion.where(gekanator_game_id:).count
|
||||
if count >= MAX_QUESTIONS_PER_GAME
|
||||
errors.add(:base, '質問追加数を超えてゐます.')
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
@@ -1,15 +1,5 @@
|
||||
module Gekanator
|
||||
class QuestionSuggestionAiConverter
|
||||
# Temporary heuristic converter for #361.
|
||||
# This creates pending ai_generated questions without external LLM calls;
|
||||
# accepted questions are still distributed only after admin approval.
|
||||
TITLE_LENGTH_RE = /\Aタイトルは\s*(\d+)\s*文字以上[??]\z/
|
||||
ORIGINAL_YEAR_RE = /\Aオリジナルの投稿年は\s*(\d{4})\s*年[??]\z/
|
||||
ORIGINAL_MONTH_RE = /\Aオリジナルの投稿月は\s*(\d{1,2})\s*月[??]\z/
|
||||
ORIGINAL_MONTH_DAY_RE = /\Aオリジナルの投稿日は\s*(\d{1,2})\s*月\s*(\d{1,2})\s*日[??]\z/
|
||||
TITLE_CONTAINS_RE = /\A題名に「(.+?)」が含まれる[??]\z/
|
||||
SOURCE_RE = /\A(.+?)\s+の投稿を思[ひい]浮かべて[ゐい]る[??]\z/
|
||||
|
||||
def self.call(...) = new(...).call
|
||||
|
||||
def initialize suggestion:, user:
|
||||
@@ -18,151 +8,11 @@ module Gekanator
|
||||
end
|
||||
|
||||
def call
|
||||
suggestion.with_lock do
|
||||
existing = existing_generated_question
|
||||
return existing if existing
|
||||
|
||||
run = suggestion.gekanator_ai_runs.create!(
|
||||
model: 'heuristic_converter_v1',
|
||||
status: 'running',
|
||||
input_tokens: 0,
|
||||
output_tokens: 0,
|
||||
estimated_cost_jpy: 0)
|
||||
|
||||
question_attributes = build_question
|
||||
question =
|
||||
question_attributes &&
|
||||
GekanatorQuestion.create!(
|
||||
**question_attributes,
|
||||
source: 'ai_generated',
|
||||
status: 'pending',
|
||||
gekanator_question_suggestion: suggestion,
|
||||
created_by: user)
|
||||
|
||||
run.update!(status: question ? 'succeeded' : 'failed')
|
||||
question
|
||||
end
|
||||
rescue => error
|
||||
run&.update!(status: 'failed') if run&.persisted? && run.status != 'failed'
|
||||
raise error
|
||||
raise NotImplementedError, 'AI question conversion is not implemented yet.'
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
attr_reader :suggestion, :user
|
||||
|
||||
def existing_generated_question
|
||||
suggestion
|
||||
.gekanator_questions
|
||||
.where(source: 'ai_generated')
|
||||
.order(id: :desc)
|
||||
.first
|
||||
end
|
||||
|
||||
def build_question
|
||||
text = normalized_text
|
||||
return nil if text.blank?
|
||||
|
||||
structured_question_for(text) || post_similarity_question_for(text)
|
||||
end
|
||||
|
||||
def normalized_text
|
||||
suggestion.question_text.to_s.gsub(/[[:space:]]+/, ' ').strip
|
||||
end
|
||||
|
||||
def structured_question_for text
|
||||
case text
|
||||
when TITLE_LENGTH_RE
|
||||
length = Regexp.last_match(1).to_i
|
||||
return nil if length <= 0
|
||||
|
||||
{
|
||||
text:,
|
||||
kind: 'title',
|
||||
condition: {
|
||||
type: 'title-length-at-least',
|
||||
length:
|
||||
},
|
||||
priority_weight: 0.95
|
||||
}
|
||||
when /\A題名に英数字が混じって[ゐい]る[??]\z/
|
||||
{
|
||||
text: '題名に英数字が混じってゐる?',
|
||||
kind: 'title',
|
||||
condition: { type: 'title-has-ascii' },
|
||||
priority_weight: 0.95
|
||||
}
|
||||
when ORIGINAL_YEAR_RE
|
||||
year = Regexp.last_match(1).to_i
|
||||
{
|
||||
text:,
|
||||
kind: 'original_date',
|
||||
condition: { type: 'original-year', year: },
|
||||
priority_weight: 0.95
|
||||
}
|
||||
when ORIGINAL_MONTH_RE
|
||||
month = Regexp.last_match(1).to_i
|
||||
return nil unless month.between?(1, 12)
|
||||
|
||||
{
|
||||
text:,
|
||||
kind: 'original_date',
|
||||
condition: { type: 'original-month', month: },
|
||||
priority_weight: 0.95
|
||||
}
|
||||
when ORIGINAL_MONTH_DAY_RE
|
||||
month = Regexp.last_match(1).to_i
|
||||
day = Regexp.last_match(2).to_i
|
||||
return nil unless month.between?(1, 12) && day.between?(1, 31)
|
||||
|
||||
{
|
||||
text:,
|
||||
kind: 'original_date',
|
||||
condition: {
|
||||
type: 'original-month-day',
|
||||
monthDay: "#{ month }-#{ day }"
|
||||
},
|
||||
priority_weight: 0.95
|
||||
}
|
||||
when TITLE_CONTAINS_RE
|
||||
title_text = Regexp.last_match(1).to_s.strip
|
||||
return nil if title_text.blank?
|
||||
|
||||
{
|
||||
text: "題名に「#{ title_text }」が含まれる?",
|
||||
kind: 'title',
|
||||
condition: { type: 'title-contains', text: title_text },
|
||||
priority_weight: 0.95
|
||||
}
|
||||
when SOURCE_RE
|
||||
host = Regexp.last_match(1).to_s.strip
|
||||
return nil if host.blank?
|
||||
|
||||
{
|
||||
text:,
|
||||
kind: 'source',
|
||||
condition: { type: 'source', host: },
|
||||
priority_weight: 0.95
|
||||
}
|
||||
else
|
||||
nil
|
||||
end
|
||||
end
|
||||
|
||||
def post_similarity_question_for text
|
||||
return nil if suggestion.answer == 'unknown'
|
||||
|
||||
{
|
||||
text:,
|
||||
kind: 'post_similarity',
|
||||
condition: {
|
||||
type: 'post-similarity',
|
||||
postId: suggestion.gekanator_game.correct_post_id,
|
||||
answer: suggestion.answer,
|
||||
threshold: 0.65
|
||||
},
|
||||
priority_weight: 1.0
|
||||
}
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
@@ -52,16 +52,16 @@ RSpec.describe 'Gekanator games API', type: :request do
|
||||
expect(response).to have_http_status(:unprocessable_entity)
|
||||
end
|
||||
|
||||
it 'returns unauthorized without a user' do
|
||||
it 'returns not found without an admin user' do
|
||||
post '/gekanator/games', params: {
|
||||
guessed_post_id: guessed_post.id,
|
||||
correct_post_id: guessed_post.id,
|
||||
answers: [] }
|
||||
|
||||
expect(response).to have_http_status(:unauthorized)
|
||||
expect(response).to have_http_status(:not_found)
|
||||
end
|
||||
|
||||
it 'stores a game for a non-admin user' do
|
||||
it 'returns not found for a non-admin user' do
|
||||
sign_in_as user
|
||||
|
||||
post '/gekanator/games', params: {
|
||||
@@ -69,8 +69,7 @@ RSpec.describe 'Gekanator games API', type: :request do
|
||||
correct_post_id: guessed_post.id,
|
||||
answers: [{ question_id: 'tag:1', answer: 'yes' }] }
|
||||
|
||||
expect(response).to have_http_status(:created)
|
||||
expect(GekanatorGame.find(json['id']).user).to eq(user)
|
||||
expect(response).to have_http_status(:not_found)
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
@@ -129,7 +129,7 @@ RSpec.describe 'Gekanator learning API', type: :request do
|
||||
expect(response).to have_http_status(:unprocessable_entity)
|
||||
end
|
||||
|
||||
it 'stores a game result for a non-admin user' do
|
||||
it 'returns not found for a non-admin user' do
|
||||
sign_in_as member
|
||||
|
||||
post '/gekanator/games', params: {
|
||||
@@ -138,18 +138,7 @@ RSpec.describe 'Gekanator learning API', type: :request do
|
||||
answers: []
|
||||
}
|
||||
|
||||
expect(response).to have_http_status(:created)
|
||||
expect(GekanatorGame.find(json['id']).user).to eq(member)
|
||||
end
|
||||
|
||||
it 'returns unauthorized without a user' do
|
||||
post '/gekanator/games', params: {
|
||||
guessed_post_id: guessed_post.id,
|
||||
correct_post_id: correct_post.id,
|
||||
answers: []
|
||||
}
|
||||
|
||||
expect(response).to have_http_status(:unauthorized)
|
||||
expect(response).to have_http_status(:not_found)
|
||||
end
|
||||
end
|
||||
|
||||
@@ -272,57 +261,17 @@ RSpec.describe 'Gekanator learning API', type: :request do
|
||||
expect(response).to have_http_status(:unprocessable_entity)
|
||||
end
|
||||
|
||||
it 'allows a non-admin user to suggest a question for their own game' do
|
||||
member_game = GekanatorGame.create!(
|
||||
user: member,
|
||||
guessed_post: guessed_post,
|
||||
correct_post: correct_post,
|
||||
won: false,
|
||||
question_count: 1,
|
||||
answers: [{ 'question_id' => 'tag:1', 'answer' => 'yes' }]
|
||||
)
|
||||
it 'returns not found for a non-admin user' do
|
||||
sign_in_as member
|
||||
|
||||
expect {
|
||||
post '/gekanator/question_suggestions', params: {
|
||||
gekanator_game_id: member_game.id,
|
||||
question_text: 'member question?',
|
||||
answer: 'yes'
|
||||
}
|
||||
}.to change { GekanatorQuestionSuggestion.count }.by(1)
|
||||
|
||||
expect(response).to have_http_status(:created)
|
||||
expect(GekanatorQuestionSuggestion.last).to have_attributes(
|
||||
gekanator_game_id: member_game.id,
|
||||
user_id: member.id
|
||||
)
|
||||
end
|
||||
|
||||
it 'returns not found for another user game' do
|
||||
sign_in_as member
|
||||
|
||||
expect {
|
||||
post '/gekanator/question_suggestions', params: {
|
||||
gekanator_game_id: game.id,
|
||||
question_text: 'member question?',
|
||||
answer: 'yes'
|
||||
}
|
||||
}.not_to change { GekanatorQuestionSuggestion.count }
|
||||
post '/gekanator/question_suggestions', params: {
|
||||
gekanator_game_id: game.id,
|
||||
question_text: 'member question?',
|
||||
answer: 'yes'
|
||||
}
|
||||
|
||||
expect(response).to have_http_status(:not_found)
|
||||
end
|
||||
|
||||
it 'returns unauthorized without a user' do
|
||||
expect {
|
||||
post '/gekanator/question_suggestions', params: {
|
||||
gekanator_game_id: game.id,
|
||||
question_text: 'member question?',
|
||||
answer: 'yes'
|
||||
}
|
||||
}.not_to change { GekanatorQuestionSuggestion.count }
|
||||
|
||||
expect(response).to have_http_status(:unauthorized)
|
||||
end
|
||||
end
|
||||
|
||||
describe 'GET /gekanator/games/:id/extra_questions' do
|
||||
@@ -428,38 +377,6 @@ RSpec.describe 'Gekanator learning API', type: :request do
|
||||
expect(response).to have_http_status(:ok)
|
||||
expect(json['questions'].map { _1['id'] }).to contain_exactly(accepted.id)
|
||||
end
|
||||
|
||||
it 'allows a non-admin user to fetch extra questions for their own game' do
|
||||
member_game = GekanatorGame.create!(
|
||||
user: member,
|
||||
guessed_post: guessed_post,
|
||||
correct_post: correct_post,
|
||||
won: false,
|
||||
question_count: 1,
|
||||
answers: [{ 'question_id' => 'tag:1', 'answer' => 'yes' }]
|
||||
)
|
||||
accepted = create_post_similarity_question!(text: 'accepted?')
|
||||
sign_in_as member
|
||||
|
||||
get "/gekanator/games/#{member_game.id}/extra_questions"
|
||||
|
||||
expect(response).to have_http_status(:ok)
|
||||
expect(json['questions'].map { _1['id'] }).to include(accepted.id)
|
||||
end
|
||||
|
||||
it 'returns not found for another user game' do
|
||||
sign_in_as member
|
||||
|
||||
get "/gekanator/games/#{game.id}/extra_questions"
|
||||
|
||||
expect(response).to have_http_status(:not_found)
|
||||
end
|
||||
|
||||
it 'returns unauthorized without a user' do
|
||||
get "/gekanator/games/#{game.id}/extra_questions"
|
||||
|
||||
expect(response).to have_http_status(:unauthorized)
|
||||
end
|
||||
end
|
||||
|
||||
describe 'POST /gekanator/games/:id/extra_question_answers' do
|
||||
@@ -586,69 +503,6 @@ RSpec.describe 'Gekanator learning API', type: :request do
|
||||
|
||||
expect(response).to have_http_status(:unprocessable_entity)
|
||||
end
|
||||
|
||||
it 'allows a non-admin user to answer extra questions for their own game' do
|
||||
member_game = GekanatorGame.create!(
|
||||
user: member,
|
||||
guessed_post: guessed_post,
|
||||
correct_post: correct_post,
|
||||
won: false,
|
||||
question_count: 1,
|
||||
answers: [{ 'question_id' => 'tag:1', 'answer' => 'yes' }]
|
||||
)
|
||||
question = create_post_similarity_question!(text: 'extra?')
|
||||
sign_in_as member
|
||||
|
||||
expect {
|
||||
post "/gekanator/games/#{member_game.id}/extra_question_answers", params: {
|
||||
answers: [
|
||||
{
|
||||
question_id: question.id,
|
||||
answer: 'yes'
|
||||
}
|
||||
]
|
||||
}
|
||||
}.to change { GekanatorQuestionExample.count }.by(1)
|
||||
|
||||
expect(response).to have_http_status(:created)
|
||||
expect(GekanatorQuestionExample.last).to have_attributes(
|
||||
user_id: member.id,
|
||||
gekanator_game_id: member_game.id
|
||||
)
|
||||
end
|
||||
|
||||
it 'returns not found for another user game' do
|
||||
question = create_post_similarity_question!(text: 'extra?')
|
||||
sign_in_as member
|
||||
|
||||
expect {
|
||||
post "/gekanator/games/#{game.id}/extra_question_answers", params: {
|
||||
answers: [
|
||||
{
|
||||
question_id: question.id,
|
||||
answer: 'yes'
|
||||
}
|
||||
]
|
||||
}
|
||||
}.not_to change { GekanatorQuestionExample.count }
|
||||
|
||||
expect(response).to have_http_status(:not_found)
|
||||
end
|
||||
|
||||
it 'returns unauthorized without a user' do
|
||||
question = create_post_similarity_question!(text: 'extra?')
|
||||
|
||||
post "/gekanator/games/#{game.id}/extra_question_answers", params: {
|
||||
answers: [
|
||||
{
|
||||
question_id: question.id,
|
||||
answer: 'yes'
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
expect(response).to have_http_status(:unauthorized)
|
||||
end
|
||||
end
|
||||
|
||||
describe 'GET /gekanator/questions' do
|
||||
@@ -754,33 +608,5 @@ RSpec.describe 'Gekanator learning API', type: :request do
|
||||
'length' => 21
|
||||
)
|
||||
end
|
||||
|
||||
it 'returns title-contains questions without authentication' do
|
||||
GekanatorQuestion.create!(
|
||||
text: '題名に「結束バンド」が含まれる?',
|
||||
kind: 'title',
|
||||
source: 'ai_generated',
|
||||
status: 'accepted',
|
||||
priority_weight: 0.95,
|
||||
condition: {
|
||||
type: 'title-contains',
|
||||
text: '結束バンド'
|
||||
},
|
||||
created_by: admin
|
||||
)
|
||||
|
||||
get '/gekanator/questions'
|
||||
|
||||
expect(response).to have_http_status(:ok)
|
||||
question_json = json['questions'].find { _1['id'] == 'title:contains:結束バンド' }
|
||||
expect(question_json).to include(
|
||||
'text' => '題名に「結束バンド」が含まれる?',
|
||||
'kind' => 'title'
|
||||
)
|
||||
expect(question_json['condition']).to include(
|
||||
'type' => 'title-contains',
|
||||
'text' => '結束バンド'
|
||||
)
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
@@ -1,112 +0,0 @@
|
||||
require 'rails_helper'
|
||||
|
||||
RSpec.describe Gekanator::QuestionSuggestionAiConverter do
|
||||
let(:user) { create(:user, :member) }
|
||||
let(:guessed_post) { Post.create!(title: 'guess', url: 'https://example.com/guess') }
|
||||
let(:correct_post) { Post.create!(title: 'correct', url: 'https://example.com/correct') }
|
||||
let(:game) do
|
||||
GekanatorGame.create!(
|
||||
user: user,
|
||||
guessed_post: guessed_post,
|
||||
correct_post: correct_post,
|
||||
won: false,
|
||||
question_count: 1,
|
||||
answers: [{ 'question_id' => 'tag:1', 'answer' => 'yes' }]
|
||||
)
|
||||
end
|
||||
|
||||
def create_suggestion!(question_text:, answer: 'yes')
|
||||
GekanatorQuestionSuggestion.create!(
|
||||
gekanator_game: game,
|
||||
user: user,
|
||||
question_text: question_text,
|
||||
answer: answer
|
||||
)
|
||||
end
|
||||
|
||||
it 'converts title-contains suggestions to pending ai-generated questions' do
|
||||
suggestion = create_suggestion!(question_text: '題名に「結束バンド」が含まれる?')
|
||||
|
||||
expect {
|
||||
described_class.call(suggestion: suggestion, user: user)
|
||||
}.to change { GekanatorQuestion.count }.by(1)
|
||||
.and change { GekanatorAiRun.count }.by(1)
|
||||
|
||||
question = GekanatorQuestion.last
|
||||
expect(question).to have_attributes(
|
||||
text: '題名に「結束バンド」が含まれる?',
|
||||
kind: 'title',
|
||||
source: 'ai_generated',
|
||||
status: 'pending',
|
||||
priority_weight: 0.95,
|
||||
gekanator_question_suggestion_id: suggestion.id,
|
||||
created_by_id: user.id
|
||||
)
|
||||
expect(question.condition).to include(
|
||||
'type' => 'title-contains',
|
||||
'text' => '結束バンド'
|
||||
)
|
||||
expect(GekanatorAiRun.last).to have_attributes(
|
||||
gekanator_question_suggestion_id: suggestion.id,
|
||||
model: 'heuristic_converter_v1',
|
||||
status: 'succeeded'
|
||||
)
|
||||
end
|
||||
|
||||
it 'converts concrete non-unknown suggestions to post-similarity questions' do
|
||||
suggestion = create_suggestion!(
|
||||
question_text: '喜多ちゃんが泣いてる?',
|
||||
answer: 'partial'
|
||||
)
|
||||
|
||||
question = described_class.call(suggestion: suggestion, user: user)
|
||||
|
||||
expect(question).to have_attributes(
|
||||
text: '喜多ちゃんが泣いてる?',
|
||||
kind: 'post_similarity',
|
||||
source: 'ai_generated',
|
||||
status: 'pending',
|
||||
priority_weight: 1.0
|
||||
)
|
||||
expect(question.condition).to include(
|
||||
'type' => 'post-similarity',
|
||||
'postId' => correct_post.id,
|
||||
'answer' => 'partial',
|
||||
'threshold' => 0.65
|
||||
)
|
||||
end
|
||||
|
||||
it 'records a failed run when the suggestion cannot be converted' do
|
||||
suggestion = create_suggestion!(
|
||||
question_text: 'よく分からない質問?',
|
||||
answer: 'unknown'
|
||||
)
|
||||
|
||||
expect {
|
||||
expect(described_class.call(suggestion: suggestion, user: user)).to be_nil
|
||||
}.not_to change { GekanatorQuestion.count }
|
||||
|
||||
expect(GekanatorAiRun.last).to have_attributes(
|
||||
gekanator_question_suggestion_id: suggestion.id,
|
||||
status: 'failed'
|
||||
)
|
||||
end
|
||||
|
||||
it 'returns an existing generated question without creating a duplicate run' do
|
||||
suggestion = create_suggestion!(question_text: 'タイトルは 10 文字以上?')
|
||||
existing = GekanatorQuestion.create!(
|
||||
text: 'タイトルは 10 文字以上?',
|
||||
kind: 'title',
|
||||
source: 'ai_generated',
|
||||
status: 'pending',
|
||||
priority_weight: 0.95,
|
||||
condition: { type: 'title-length-at-least', length: 10 },
|
||||
gekanator_question_suggestion: suggestion,
|
||||
created_by: user
|
||||
)
|
||||
|
||||
expect {
|
||||
expect(described_class.call(suggestion: suggestion, user: user)).to eq(existing)
|
||||
}.not_to change { GekanatorAiRun.count }
|
||||
end
|
||||
end
|
||||
|
変更前 幅: | 高さ: | サイズ: 559 KiB |
|
変更前 幅: | 高さ: | サイズ: 146 KiB |
|
変更前 幅: | 高さ: | サイズ: 1.2 MiB |
|
変更前 幅: | 高さ: | サイズ: 188 KiB |
|
変更前 幅: | 高さ: | サイズ: 201 KiB |
|
変更前 幅: | 高さ: | サイズ: 196 KiB |
|
変更前 幅: | 高さ: | サイズ: 179 KiB |
|
変更前 幅: | 高さ: | サイズ: 559 KiB |
|
変更前 幅: | 高さ: | サイズ: 146 KiB |
|
変更前 幅: | 高さ: | サイズ: 1.2 MiB |
|
変更前 幅: | 高さ: | サイズ: 188 KiB |
|
変更前 幅: | 高さ: | サイズ: 201 KiB |
|
変更前 幅: | 高さ: | サイズ: 196 KiB |
|
変更前 幅: | 高さ: | サイズ: 179 KiB |
@@ -40,7 +40,7 @@ import WikiHistoryPage from '@/pages/wiki/WikiHistoryPage'
|
||||
import WikiNewPage from '@/pages/wiki/WikiNewPage'
|
||||
import WikiSearchPage from '@/pages/wiki/WikiSearchPage'
|
||||
|
||||
import type { Dispatch, FC, SetStateAction } from 'react'
|
||||
import type { Dispatch, FC, ReactNode, SetStateAction } from 'react'
|
||||
|
||||
import type { User } from '@/types'
|
||||
|
||||
@@ -81,7 +81,10 @@ const RouteTransitionWrapper = ({ user, setUser }: {
|
||||
<Route path="/users/settings" element={<SettingPage user={user} setUser={setUser}/>}/>
|
||||
<Route path="/settings" element={<Navigate to="/users/settings" replace/>}/>
|
||||
<Route path="/tos" element={<TOSPage/>}/>
|
||||
<Route path="/gekanator" element={<GekanatorPage user={user}/>}/>
|
||||
<Route path="/gekanator" element={
|
||||
<AdminOnly user={user}>
|
||||
<GekanatorPage/>
|
||||
</AdminOnly>}/>
|
||||
<Route path="/more" element={<MorePage/>}/>
|
||||
<Route path="*" element={<NotFound/>}/>
|
||||
</Routes>
|
||||
@@ -89,6 +92,16 @@ const RouteTransitionWrapper = ({ user, setUser }: {
|
||||
}
|
||||
|
||||
|
||||
const AdminOnly = ({ user, children }: {
|
||||
user: User | null
|
||||
children: ReactNode }) => {
|
||||
if (user?.role !== 'admin')
|
||||
return <NotFound/>
|
||||
|
||||
return <>{children}</>
|
||||
}
|
||||
|
||||
|
||||
const PostDetailRoute = ({ user }: { user: User | null }) => {
|
||||
const location = useLocation ()
|
||||
const key = location.pathname
|
||||
|
||||
@@ -66,8 +66,7 @@ export const menuOutline = ({ tag, wikiId, user, pathName }: {
|
||||
{ name: '履歴', to: `/wiki/changes?id=${ wikiId }`, visible: wikiPageFlg },
|
||||
{ name: '編輯', to: `/wiki/${ wikiId || wikiTitle }/edit`, visible: wikiPageFlg }] },
|
||||
{ name: 'おたのしみ', visible: false, subMenu: [
|
||||
{ name: '上映会 (β)', to: '/theatres/1' },
|
||||
{ name: 'グカネータ (β)', to: '/gekanator' }] },
|
||||
{ name: '上映会 (β)', to: '/theatres/1' }] },
|
||||
{ name: 'ユーザ', to: '/users/settings', visible: false, subMenu: [
|
||||
{ name: '一覧', to: '/users', visible: false },
|
||||
{ name: 'お前', to: `/users/${ user?.id }`, visible: false },
|
||||
|
||||
@@ -4,7 +4,6 @@ import { apiPost } from '@/lib/api'
|
||||
import {
|
||||
buildGekanatorQuestions,
|
||||
expectedAnswerForQuestion,
|
||||
questionIdForCondition,
|
||||
restoreGekanatorQuestion,
|
||||
saveGekanatorExtraQuestionAnswers,
|
||||
saveGekanatorGame,
|
||||
@@ -165,27 +164,6 @@ describe('expectedAnswerForQuestion', () => {
|
||||
|
||||
expect(expectedAnswerForQuestion(question, post({ id: 1, title: 'short' }))).toBe('no')
|
||||
})
|
||||
|
||||
it('returns yes for matching title-contains questions', () => {
|
||||
const question: StoredGekanatorQuestion = {
|
||||
id: 'title:contains:結束バンド',
|
||||
text: '題名に「結束バンド」が含まれる?',
|
||||
kind: 'title',
|
||||
condition: {
|
||||
type: 'title-contains',
|
||||
text: '結束バンド',
|
||||
},
|
||||
}
|
||||
|
||||
expect(expectedAnswerForQuestion(
|
||||
question,
|
||||
post({ title: '結束バンドのライブ' }),
|
||||
)).toBe('yes')
|
||||
expect(expectedAnswerForQuestion(
|
||||
question,
|
||||
post({ title: '後藤ひとりの休日' }),
|
||||
)).toBe('no')
|
||||
})
|
||||
})
|
||||
|
||||
describe('restoreGekanatorQuestion', () => {
|
||||
@@ -270,21 +248,6 @@ describe('restoreGekanatorQuestion', () => {
|
||||
expect(question.test(post({ title: 'x'.repeat(20) }))).toBe(false)
|
||||
expect(question.test(post({ title: 'x'.repeat(21) }))).toBe(true)
|
||||
})
|
||||
|
||||
it('restores title-contains questions with a title matcher', () => {
|
||||
const question = restoreGekanatorQuestion({
|
||||
id: 'title:contains:結束バンド',
|
||||
text: '題名に「結束バンド」が含まれる?',
|
||||
kind: 'title',
|
||||
condition: {
|
||||
type: 'title-contains',
|
||||
text: '結束バンド',
|
||||
},
|
||||
})
|
||||
|
||||
expect(question.test(post({ title: '結束バンドのライブ' }))).toBe(true)
|
||||
expect(question.test(post({ title: '後藤ひとりの休日' }))).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
describe('buildGekanatorQuestions', () => {
|
||||
@@ -301,59 +264,6 @@ describe('buildGekanatorQuestions', () => {
|
||||
expect(titleQuestion?.text).toMatch(/^タイトルは \d+ 文字以上\?$/)
|
||||
expect(titleQuestion?.id).toMatch(/^title:length-at-least:\d+$/)
|
||||
})
|
||||
|
||||
it('builds title-contains questions from repeated title words', () => {
|
||||
const questions = buildGekanatorQuestions([
|
||||
post({ id: 1, title: '結束バンド ライブ' }),
|
||||
post({ id: 2, title: '結束バンド 新曲' }),
|
||||
post({ id: 3, title: '後藤ひとり 練習' }),
|
||||
post({ id: 4, title: '伊地知虹夏 練習' }),
|
||||
])
|
||||
|
||||
const titleContainsQuestion = questions.find(question =>
|
||||
question.condition.type === 'title-contains'
|
||||
&& question.condition.text === '結束バンド')
|
||||
|
||||
expect(titleContainsQuestion).toMatchObject({
|
||||
id: 'title:contains:結束バンド',
|
||||
text: '題名に「結束バンド」が含まれる?',
|
||||
kind: 'title',
|
||||
source: 'default',
|
||||
priorityWeight: .96,
|
||||
})
|
||||
expect(titleContainsQuestion?.test(post({ title: '結束バンドのライブ' }))).toBe(true)
|
||||
expect(titleContainsQuestion?.test(post({ title: '廣井きくりのライブ' }))).toBe(false)
|
||||
})
|
||||
|
||||
it('honors question caps and title-contains toggles', () => {
|
||||
const posts = [
|
||||
post({ id: 1, title: '結束バンド ライブ' }),
|
||||
post({ id: 2, title: '結束バンド 新曲' }),
|
||||
post({ id: 3, title: '後藤ひとり 練習' }),
|
||||
post({ id: 4, title: '伊地知虹夏 練習' }),
|
||||
]
|
||||
|
||||
const capped = buildGekanatorQuestions(posts, {
|
||||
titleContainsCap: 1,
|
||||
totalQuestionCap: 1,
|
||||
})
|
||||
const withoutTitleContains = buildGekanatorQuestions(posts, {
|
||||
includeTitleContains: false,
|
||||
})
|
||||
|
||||
expect(capped).toHaveLength(1)
|
||||
expect(withoutTitleContains.some(question =>
|
||||
question.condition.type === 'title-contains')).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
describe('questionIdForCondition', () => {
|
||||
it('builds stable ids for title-contains questions', () => {
|
||||
expect(questionIdForCondition({
|
||||
type: 'title-contains',
|
||||
text: '結束バンド',
|
||||
})).toBe('title:contains:結束バンド')
|
||||
})
|
||||
})
|
||||
|
||||
describe('Gekanator API writers', () => {
|
||||
|
||||
@@ -13,7 +13,6 @@ export type GekanatorAnswerLog = {
|
||||
questionId: string
|
||||
questionText: string
|
||||
questionCondition?: GekanatorQuestionCondition
|
||||
questionMode?: 'normal' | 'winning_run'
|
||||
answer: GekanatorAnswerValue
|
||||
originalAnswer: GekanatorAnswerValue }
|
||||
|
||||
@@ -30,8 +29,6 @@ export type GekanatorQuestionSource =
|
||||
| 'ai_generated'
|
||||
| 'admin_curated'
|
||||
|
||||
export type GekanatorPerformanceMode = 'normal'
|
||||
|
||||
export type GekanatorQuestionCondition =
|
||||
| { type: 'tag'; key: string }
|
||||
| { type: 'source'; host: string }
|
||||
@@ -41,7 +38,6 @@ export type GekanatorQuestionCondition =
|
||||
| { type: 'title-length-at-least'; length: number }
|
||||
| { type: 'title-length-greater-than'; length: number }
|
||||
| { type: 'title-has-ascii' }
|
||||
| { type: 'title-contains'; text: string }
|
||||
| {
|
||||
type: 'post-similarity'
|
||||
postId: number
|
||||
@@ -62,7 +58,6 @@ export type GekanatorExtraQuestion = {
|
||||
priorityWeight: number }
|
||||
|
||||
export type StoredGekanatorQuestion = {
|
||||
recordId?: number
|
||||
id: string
|
||||
text: string
|
||||
kind: GekanatorQuestionKind
|
||||
@@ -72,7 +67,6 @@ export type StoredGekanatorQuestion = {
|
||||
exampleAnswers?: Record<`${ number }`, GekanatorAnswerValue> }
|
||||
|
||||
export type GekanatorQuestion = {
|
||||
recordId?: number
|
||||
id: string
|
||||
text: string
|
||||
kind: GekanatorQuestionKind
|
||||
@@ -82,13 +76,6 @@ export type GekanatorQuestion = {
|
||||
exampleAnswers?: Record<`${ number }`, GekanatorAnswerValue>
|
||||
test: (post: Post) => boolean }
|
||||
|
||||
export type BuildGekanatorQuestionsOptions = {
|
||||
includeTitleContains?: boolean
|
||||
tagQuestionCap?: number
|
||||
titleContainsCap?: number
|
||||
totalQuestionCap?: number
|
||||
}
|
||||
|
||||
|
||||
export const normalizeTitleLengthCondition = (
|
||||
condition: GekanatorQuestionCondition,
|
||||
@@ -140,8 +127,6 @@ export const questionIdForCondition = (
|
||||
return `title:length-at-least:${ titleLengthMinimumForCondition (condition) }`
|
||||
case 'title-has-ascii':
|
||||
return 'title:ascii'
|
||||
case 'title-contains':
|
||||
return `title:contains:${ condition.text }`
|
||||
}
|
||||
}
|
||||
|
||||
@@ -150,7 +135,7 @@ const directExampleAnswerFor = (
|
||||
question: StoredGekanatorQuestion,
|
||||
post: Post,
|
||||
): GekanatorAnswerValue | null => {
|
||||
if (question.kind !== 'post_similarity' && question.kind !== 'tag')
|
||||
if (question.kind !== 'post_similarity')
|
||||
return null
|
||||
|
||||
const direct = question.exampleAnswers?.[String (post.id) as `${ number }`]
|
||||
@@ -307,8 +292,6 @@ const questionMatches = (
|
||||
return (post.title?.length ?? 0) > question.condition.length
|
||||
case 'title-has-ascii':
|
||||
return /[A-Za-z0-9]/.test (post.title ?? '')
|
||||
case 'title-contains':
|
||||
return (post.title ?? '').includes (question.condition.text)
|
||||
case 'post-similarity':
|
||||
return false
|
||||
}
|
||||
@@ -336,7 +319,6 @@ export const expectedAnswerForQuestion = (
|
||||
case 'title-length-at-least':
|
||||
case 'title-length-greater-than':
|
||||
case 'title-has-ascii':
|
||||
case 'title-contains':
|
||||
return questionMatches (post, question) ? 'yes' : 'no'
|
||||
case 'post-similarity':
|
||||
return null
|
||||
@@ -350,7 +332,6 @@ export const restoreGekanatorQuestion = (
|
||||
const normalizedCondition = normalizeTitleLengthCondition (question.condition)
|
||||
const normalizedQuestion = {
|
||||
...question,
|
||||
recordId: question.recordId,
|
||||
id: normalizedCondition.type === 'title-length-at-least'
|
||||
? `title:length-at-least:${ normalizedCondition.length }`
|
||||
: question.id,
|
||||
@@ -370,7 +351,6 @@ export const storeGekanatorQuestion = (
|
||||
id: question.condition.type === 'title-length-greater-than'
|
||||
? `title:length-at-least:${ question.condition.length + 1 }`
|
||||
: question.id,
|
||||
recordId: question.recordId,
|
||||
text: question.text,
|
||||
kind: question.kind,
|
||||
condition: normalizeTitleLengthCondition (question.condition),
|
||||
@@ -402,16 +382,7 @@ export const fetchGekanatorExtraQuestions = async (
|
||||
}
|
||||
|
||||
|
||||
export const buildGekanatorQuestions = (
|
||||
posts: Post[],
|
||||
options: BuildGekanatorQuestionsOptions = { },
|
||||
): GekanatorQuestion[] => {
|
||||
const {
|
||||
includeTitleContains = true,
|
||||
tagQuestionCap = 192,
|
||||
titleContainsCap = 24,
|
||||
totalQuestionCap = Number.POSITIVE_INFINITY,
|
||||
} = options
|
||||
export const buildGekanatorQuestions = (posts: Post[]): GekanatorQuestion[] => {
|
||||
const tagCounts = countBy (posts.flatMap (post =>
|
||||
post.tags
|
||||
.filter (tag =>
|
||||
@@ -433,31 +404,17 @@ export const buildGekanatorQuestions = (
|
||||
.map (originalMonthDayOf)
|
||||
.filter ((monthDay): monthDay is string => monthDay !== null))
|
||||
const titleLengthMedian = median (posts.map (post => post.title?.length ?? 0))
|
||||
const titleWordCounts =
|
||||
includeTitleContains
|
||||
? countBy (
|
||||
posts.flatMap (post =>
|
||||
Array.from (
|
||||
new Set (
|
||||
(post.title ?? '')
|
||||
.match (
|
||||
/[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}A-Za-z0-9]{2,}/gu)
|
||||
?? []))))
|
||||
: new Map<string, number> ()
|
||||
|
||||
const usefulEntries = <T extends string | number> (
|
||||
counts: Map<T, number>,
|
||||
cap: number,
|
||||
) =>
|
||||
const usefulEntries = <T extends string | number> (counts: Map<T, number>) =>
|
||||
[...counts.entries ()]
|
||||
.filter (([, count]) => count > 0 && count < posts.length)
|
||||
.sort ((a, b) => Math.abs (posts.length / 2 - a[1])
|
||||
- Math.abs (posts.length / 2 - b[1]))
|
||||
.slice (0, cap)
|
||||
.slice (0, 80)
|
||||
|
||||
const tagQuestions = usefulEntries (tagCounts, Math.max (tagQuestionCap, 80))
|
||||
const tagQuestions = usefulEntries (tagCounts)
|
||||
.filter (([, count]) => count >= 2 && count <= Math.max (2, posts.length * .7))
|
||||
.slice (0, tagQuestionCap)
|
||||
.slice (0, 80)
|
||||
.map (([key]) => {
|
||||
const { category, name } = tagFromQuestionKey (String (key))
|
||||
const label = category === 'nico' ? nicoTagLabel (name) : name
|
||||
@@ -472,7 +429,7 @@ export const buildGekanatorQuestions = (
|
||||
test: (post: Post) => questionableTag (post, String (key)) }
|
||||
})
|
||||
|
||||
const sourceQuestions = usefulEntries (hosts, 20)
|
||||
const sourceQuestions = usefulEntries (hosts)
|
||||
.filter (([, count]) => count >= 2 && count <= Math.max (2, posts.length * .7))
|
||||
.slice (0, 20)
|
||||
.map (([host]) => ({
|
||||
@@ -484,7 +441,7 @@ export const buildGekanatorQuestions = (
|
||||
priorityWeight: 1,
|
||||
test: (post: Post) => hostOf (post) === host }))
|
||||
|
||||
const originalYearQuestions = usefulEntries (originalYears, 20)
|
||||
const originalYearQuestions = usefulEntries (originalYears)
|
||||
.filter (([, count]) => count >= 2 && count <= Math.max (2, posts.length * .7))
|
||||
.slice (0, 20)
|
||||
.map (([year]) => ({
|
||||
@@ -496,7 +453,7 @@ export const buildGekanatorQuestions = (
|
||||
priorityWeight: 1,
|
||||
test: (post: Post) => originalYearOf (post) === year }))
|
||||
|
||||
const originalMonthQuestions = usefulEntries (originalMonths, 20)
|
||||
const originalMonthQuestions = usefulEntries (originalMonths)
|
||||
.filter (([, count]) => count >= 2 && count <= Math.max (2, posts.length * .7))
|
||||
.slice (0, 20)
|
||||
.map (([month]) => ({
|
||||
@@ -508,7 +465,7 @@ export const buildGekanatorQuestions = (
|
||||
priorityWeight: 1,
|
||||
test: (post: Post) => originalMonthOf (post) === month }))
|
||||
|
||||
const originalMonthDayQuestions = usefulEntries (originalMonthDays, 20)
|
||||
const originalMonthDayQuestions = usefulEntries (originalMonthDays)
|
||||
.filter (([, count]) => count >= 2 && count <= Math.max (2, posts.length * .7))
|
||||
.slice (0, 20)
|
||||
.map (([monthDay]) => {
|
||||
@@ -548,23 +505,6 @@ export const buildGekanatorQuestions = (
|
||||
const no = posts.length - yes
|
||||
return yes >= 2 && no >= 2 && yes <= posts.length * .7 && no <= posts.length * .7
|
||||
})
|
||||
const titleContainsQuestions =
|
||||
includeTitleContains
|
||||
? usefulEntries (titleWordCounts, titleContainsCap)
|
||||
.filter (([word, count]) =>
|
||||
String (word).length <= 24
|
||||
&& count >= 2
|
||||
&& count <= Math.max (2, posts.length * .7))
|
||||
.slice (0, titleContainsCap)
|
||||
.map (([word]) => ({
|
||||
id: `title:contains:${ word }`,
|
||||
text: `題名に「${ word }」が含まれる?`,
|
||||
kind: 'title' as const,
|
||||
condition: { type: 'title-contains' as const, text: String (word) },
|
||||
source: 'default' as const,
|
||||
priorityWeight: .96,
|
||||
test: (post: Post) => (post.title ?? '').includes (String (word)) }))
|
||||
: []
|
||||
|
||||
return [
|
||||
...sourceQuestions,
|
||||
@@ -572,8 +512,7 @@ export const buildGekanatorQuestions = (
|
||||
...originalMonthQuestions,
|
||||
...originalMonthDayQuestions,
|
||||
...titleQuestions,
|
||||
...titleContainsQuestions,
|
||||
...tagQuestions].slice (0, totalQuestionCap)
|
||||
...tagQuestions]
|
||||
}
|
||||
|
||||
|
||||
@@ -585,7 +524,7 @@ export const saveGekanatorGame = async ({
|
||||
guessedPostId: number
|
||||
correctPostId: number
|
||||
answers: GekanatorAnswerLog[]
|
||||
}): Promise<{ id: number; learnedExampleCount: number }> =>
|
||||
}): Promise<{ id: number }> =>
|
||||
await apiPost ('/gekanator/games', {
|
||||
guessed_post_id: guessedPostId,
|
||||
correct_post_id: correctPostId,
|
||||
@@ -599,18 +538,15 @@ export const saveGekanatorGame = async ({
|
||||
|
||||
export const saveGekanatorQuestionSuggestion = async ({
|
||||
gekanatorGameId,
|
||||
existingQuestionId,
|
||||
questionText,
|
||||
answer,
|
||||
}: {
|
||||
gekanatorGameId: number
|
||||
existingQuestionId?: number
|
||||
questionText?: string
|
||||
questionText: string
|
||||
answer: GekanatorAnswerValue
|
||||
}): Promise<{ id: number; count: number }> =>
|
||||
await apiPost ('/gekanator/question_suggestions', {
|
||||
gekanator_game_id: gekanatorGameId,
|
||||
existing_question_id: existingQuestionId,
|
||||
question_text: questionText,
|
||||
answer })
|
||||
|
||||
|
||||
@@ -145,30 +145,7 @@ describe('recoverCandidatePosts', () => {
|
||||
|
||||
expect(recovered?.recoveryStepCount).toBe (1)
|
||||
expect([...(recovered?.recoveredCandidatePosts.keys () ?? [])])
|
||||
.toEqual ([8, 7, 6, 5, 4])
|
||||
.toEqual ([8, 7, 6, 5, 4, 3, 2])
|
||||
expect(recovered?.recoveredCandidatePosts.get (7)).toBe (2)
|
||||
})
|
||||
|
||||
it('does not add posts when recovered and eligible candidates already hit the target', () => {
|
||||
const posts = Array.from ({ length: 10 }, (_value, index) => post (index + 1))
|
||||
const scores = new Map (posts.map (candidate => [candidate.id, candidate.id]))
|
||||
|
||||
const recovered = recoverCandidatePosts ({
|
||||
posts,
|
||||
scores,
|
||||
rejectedPostIds: new Set (),
|
||||
recoveredCandidatePosts: new Map ([
|
||||
[1, 1],
|
||||
[2, 1],
|
||||
[3, 1],
|
||||
]),
|
||||
eligiblePostIds: new Set ([4, 5, 6]),
|
||||
answerCountAtRecovery: 2,
|
||||
recoveryStepCount: 0,
|
||||
})
|
||||
|
||||
expect(recovered?.recoveryStepCount).toBe (1)
|
||||
expect([...(recovered?.recoveredCandidatePosts.keys () ?? [])])
|
||||
.toEqual ([1, 2, 3])
|
||||
})
|
||||
})
|
||||
|
||||
@@ -13,16 +13,6 @@ export type RecoveredCandidatePost = {
|
||||
answerCountAtRecovery: number }
|
||||
|
||||
|
||||
const questionIsFactLikeForHardFiltering = (
|
||||
question: GekanatorQuestion,
|
||||
): boolean =>
|
||||
!(question.kind === 'post_similarity'
|
||||
|| (
|
||||
question.kind === 'tag'
|
||||
&& question.condition.type === 'tag'
|
||||
&& !(question.condition.key.startsWith ('nico:'))))
|
||||
|
||||
|
||||
export const candidatePostsFor = ({
|
||||
posts,
|
||||
questions,
|
||||
@@ -56,8 +46,6 @@ export const candidatePostsFor = ({
|
||||
const question = questionById.get (answer.questionId)
|
||||
if (!(question))
|
||||
return true
|
||||
if (!(questionIsFactLikeForHardFiltering (question)))
|
||||
return true
|
||||
|
||||
switch (answer.answer)
|
||||
{
|
||||
@@ -83,9 +71,6 @@ export const hardFilteredPostsForAnswer = ({
|
||||
question: GekanatorQuestion
|
||||
answer: GekanatorAnswerValue
|
||||
}): Post[] => {
|
||||
if (!(questionIsFactLikeForHardFiltering (question)))
|
||||
return posts
|
||||
|
||||
if (answer === 'unknown')
|
||||
return posts
|
||||
|
||||
@@ -115,7 +100,7 @@ export const allConcreteAnswerOptionsExhausted = (
|
||||
}
|
||||
|
||||
|
||||
const nextRecoveryTargetSize = (recoveryStepCount: number): number =>
|
||||
const nextRecoveryBatchSize = (recoveryStepCount: number): number =>
|
||||
6 * (2 ** recoveryStepCount)
|
||||
|
||||
|
||||
@@ -140,16 +125,6 @@ export const recoverCandidatePosts = ({
|
||||
recoveryStepCount: number
|
||||
} | null => {
|
||||
const recovered = new Map (recoveredCandidatePosts)
|
||||
const targetSize = nextRecoveryTargetSize (recoveryStepCount)
|
||||
const countedPostIds = new Set ([
|
||||
...eligiblePostIds,
|
||||
...recovered.keys ()])
|
||||
const addCount = targetSize - countedPostIds.size
|
||||
if (addCount <= 0)
|
||||
return {
|
||||
recoveredCandidatePosts: recovered,
|
||||
recoveryStepCount: recoveryStepCount + 1 }
|
||||
|
||||
const candidates = posts
|
||||
.filter (post =>
|
||||
!(rejectedPostIds.has (post.id))
|
||||
@@ -158,7 +133,7 @@ export const recoverCandidatePosts = ({
|
||||
.sort ((a, b) =>
|
||||
(scores.get (b.id) ?? Number.NEGATIVE_INFINITY)
|
||||
- (scores.get (a.id) ?? Number.NEGATIVE_INFINITY))
|
||||
.slice (0, addCount)
|
||||
.slice (0, nextRecoveryBatchSize (recoveryStepCount))
|
||||
|
||||
if (candidates.length === 0)
|
||||
return null
|
||||
|
||||
@@ -139,10 +139,6 @@ export type Post = {
|
||||
title: string | null
|
||||
thumbnail: string | null
|
||||
thumbnailBase: string | null
|
||||
postSimilarityEdges?: {
|
||||
targetPostId: number
|
||||
cos: number
|
||||
}[]
|
||||
tags: Tag[]
|
||||
parentPosts?: Post[]
|
||||
childPosts?: Post[]
|
||||
|
||||