Add an Explain button that has Claude explain a problem
Test and publish the site / publish (push) Successful in 8m15s
Test and publish the site / test (push) Successful in 5m51s

When stuck, the admin can ask Claude for an intuitive explanation of a
problem. It is committed as explain.md and shown as folded sections, so
the reader opens only as much as they need: the key observation, hints
that get stronger, the approach, a walkthrough with an SVG diagram per
step, complexity, pitfalls and a pseudocode sketch.

- internal/claude: streamed call with a JSON-schema reply, high effort,
  the server-side refusal fallback, fixed error messages and logged
  token usage. CLAUDE_API_KEY and CLAUDE_MODEL (default claude-opus-5-5);
  without a key only this feature is off.
- internal/explain: the prompt, the schema, rendering to markdown, and
  a per-problem job tracker. The request starts a job and the page polls,
  since a call outlasts nginx's 120s timeout.
- internal/statement: fetches statements from LeetCode's GraphQL API and
  USACO's problem pages. Others (Codeforces is behind Cloudflare) are
  pasted.
- problem.md holds the statement, editable from the meta editor and
  shown only to the admin. Diagrams are sanitized with DOMPurify.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
2026-10-19 20:38:15 +01:00
co-authored by Claude Opus 5.5
parent f0e10d2a58
commit 995b44a57a
27 changed files with 2144 additions and 67 deletions
+194
View File
@@ -0,0 +1,194 @@
// Package statement fetches a problem's statement from its judge, as
// markdown, for problem.md. Only the judges this repo mostly uses are known:
// LeetCode (its public GraphQL API) and USACO (the problem page's HTML).
// Anything else is pasted by hand.
package statement
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"strings"
"time"
htmltomarkdown "github.com/JohannesKaufmann/html-to-markdown/v2"
"golang.org/x/net/html"
)
// ErrUnsupported is a link to a judge this package cannot read.
var ErrUnsupported = errors.New("statements can't be fetched from this site; paste it instead")
// maxBody caps a judge's response. A statement page is tens of kilobytes.
const maxBody = 1 << 20
// Fetcher reads statements. The zero value talks to the real judges; tests
// point the bases at an httptest server.
type Fetcher struct {
Client *http.Client
LeetCodeAPI string // default https://leetcode.com/graphql
USACOBase string // default https://usaco.org
}
func (f *Fetcher) client() *http.Client {
if f.Client != nil {
return f.Client
}
return &http.Client{Timeout: 15 * time.Second}
}
// Fetch returns the statement behind a problem link as markdown, headed by
// the problem's title.
func (f *Fetcher) Fetch(ctx context.Context, link string) (string, error) {
u, err := url.Parse(strings.TrimSpace(link))
if err != nil || u.Host == "" {
return "", ErrUnsupported
}
switch strings.TrimPrefix(strings.ToLower(u.Hostname()), "www.") {
case "leetcode.com":
return f.leetcode(ctx, u)
case "usaco.org":
return f.usaco(ctx, u)
}
return "", ErrUnsupported
}
// leetcode asks the GraphQL API the problem page itself uses. Free problems
// answer without a login; a premium one comes back with null content.
func (f *Fetcher) leetcode(ctx context.Context, u *url.URL) (string, error) {
// /problems/<slug>/ and /problems/<slug>/description/ both name it.
parts := strings.Split(strings.Trim(u.Path, "/"), "/")
if len(parts) < 2 || parts[0] != "problems" || parts[1] == "" {
return "", fmt.Errorf("not a LeetCode problem link")
}
body, _ := json.Marshal(map[string]any{
"query": "query($s:String!){question(titleSlug:$s){title content}}",
"variables": map[string]string{"s": parts[1]},
})
api := f.LeetCodeAPI
if api == "" {
api = "https://leetcode.com/graphql"
}
req, err := http.NewRequestWithContext(ctx, http.MethodPost, api, bytes.NewReader(body))
if err != nil {
return "", err
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Referer", "https://leetcode.com")
b, err := f.do(req)
if err != nil {
return "", err
}
var resp struct {
Data struct {
Question *struct {
Title string `json:"title"`
Content *string `json:"content"`
} `json:"question"`
} `json:"data"`
}
if err := json.Unmarshal(b, &resp); err != nil {
return "", fmt.Errorf("LeetCode answered with something other than JSON")
}
q := resp.Data.Question
if q == nil {
return "", fmt.Errorf("LeetCode has no problem %q", parts[1])
}
if q.Content == nil || strings.TrimSpace(*q.Content) == "" {
return "", fmt.Errorf("LeetCode returned no statement (a premium problem?)")
}
return toMarkdown(q.Title, *q.Content)
}
// usaco reads the problem page: the title is its second <h2> (the first is
// the contest) and the statement is div.problem-text.
func (f *Fetcher) usaco(ctx context.Context, u *url.URL) (string, error) {
base := f.USACOBase
if base == "" {
base = "https://usaco.org"
}
req, err := http.NewRequestWithContext(ctx, http.MethodGet, strings.TrimRight(base, "/")+u.RequestURI(), nil)
if err != nil {
return "", err
}
b, err := f.do(req)
if err != nil {
return "", err
}
doc, err := html.Parse(bytes.NewReader(b))
if err != nil {
return "", err
}
var h2s []string
var text *html.Node
for n := range doc.Descendants() {
if n.Type != html.ElementNode {
continue
}
switch {
case n.Data == "h2":
h2s = append(h2s, strings.TrimSpace(textOf(n)))
case text == nil && n.Data == "div" && hasClass(n, "problem-text"):
text = n
}
}
if text == nil {
return "", fmt.Errorf("no statement on that USACO page")
}
title := ""
if len(h2s) > 0 {
title = h2s[len(h2s)-1]
}
var buf bytes.Buffer
if err := html.Render(&buf, text); err != nil {
return "", err
}
return toMarkdown(title, buf.String())
}
func (f *Fetcher) do(req *http.Request) ([]byte, error) {
resp, err := f.client().Do(req)
if err != nil {
return nil, fmt.Errorf("could not reach %s", req.URL.Host)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("%s answered %d", req.URL.Host, resp.StatusCode)
}
return io.ReadAll(io.LimitReader(resp.Body, maxBody))
}
func toMarkdown(title, body string) (string, error) {
md, err := htmltomarkdown.ConvertString(body)
if err != nil {
return "", err
}
md = strings.TrimSpace(md)
if title != "" {
md = "# " + title + "\n\n" + md
}
return md, nil
}
func hasClass(n *html.Node, class string) bool {
for _, a := range n.Attr {
if a.Key == "class" && strings.Contains(" "+a.Val+" ", " "+class+" ") {
return true
}
}
return false
}
func textOf(n *html.Node) string {
var sb strings.Builder
for d := range n.Descendants() {
if d.Type == html.TextNode {
sb.WriteString(d.Data)
}
}
return sb.String()
}
+81
View File
@@ -0,0 +1,81 @@
package statement
import (
"context"
"errors"
"io"
"net/http"
"net/http/httptest"
"os"
"strings"
"testing"
)
// judge serves the saved responses in testdata: LeetCode's GraphQL answer
// for path-with-minimum-effort and USACO's page for cpid=644.
func judge(t *testing.T) *Fetcher {
t.Helper()
lc, _ := os.ReadFile("testdata/leetcode.json")
us, _ := os.ReadFile("testdata/usaco.html")
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch {
case r.URL.Path == "/graphql":
b, _ := io.ReadAll(r.Body)
if !strings.Contains(string(b), `"s":"path-with-minimum-effort"`) {
w.Write([]byte(`{"data":{"question":null}}`))
return
}
w.Write(lc)
case r.URL.Query().Get("cpid") == "644":
w.Write(us)
default:
http.NotFound(w, r)
}
}))
t.Cleanup(srv.Close)
return &Fetcher{LeetCodeAPI: srv.URL + "/graphql", USACOBase: srv.URL}
}
func TestLeetCode(t *testing.T) {
md, err := judge(t).Fetch(context.Background(), "https://leetcode.com/problems/path-with-minimum-effort/description/")
if err != nil {
t.Fatal(err)
}
for _, want := range []string{"# Path With Minimum Effort", "You are a hiker", "`heights`"} {
if !strings.Contains(md, want) {
t.Errorf("markdown is missing %q:\n%s", want, md)
}
}
if strings.Contains(md, "<p>") {
t.Errorf("HTML left in the markdown:\n%s", md)
}
}
func TestLeetCodeUnknownSlug(t *testing.T) {
if _, err := judge(t).Fetch(context.Background(), "https://leetcode.com/problems/no-such-thing/"); err == nil {
t.Fatal("want an error for a problem LeetCode does not have")
}
}
func TestUSACO(t *testing.T) {
md, err := judge(t).Fetch(context.Background(), "https://usaco.org/index.php?page=viewproblem2&cpid=644")
if err != nil {
t.Fatal(err)
}
for _, want := range []string{"# Problem 3. Closing the Farm", "FJ wants to temporarily close", "SAMPLE INPUT"} {
if !strings.Contains(md, want) {
t.Errorf("markdown is missing %q:\n%s", want, md)
}
}
if strings.Contains(md, "navbar") || strings.Contains(md, "Contest has ended") {
t.Errorf("page chrome leaked into the statement:\n%s", md)
}
}
func TestUnsupported(t *testing.T) {
for _, link := range []string{"https://cses.fi/problemset/task/1068", "not a url", ""} {
if _, err := judge(t).Fetch(context.Background(), link); !errors.Is(err, ErrUnsupported) {
t.Errorf("Fetch(%q) = %v, want ErrUnsupported", link, err)
}
}
}
+1
View File
@@ -0,0 +1 @@
{"data":{"question":{"title":"Path With Minimum Effort","content":"<p>You are a hiker preparing for an upcoming hike. You are given <code>heights</code>, a 2D array of size <code>rows x columns</code>, where <code>heights[row][col]</code> represents the height of cell <code>(row, col)</code>. You are situated in the top-left cell, <code>(0, 0)</code>, and you hope to travel to the bottom-right cell, <code>(rows-1, columns-1)</code> (i.e.,&nbsp;<strong>0-indexed</strong>). You can move <strong>up</strong>, <strong>down</strong>, <strong>left</strong>, or <strong>right</strong>, and you wish to find a route that requires the minimum <strong>effort</strong>.</p>\n\n<p>A route&#39;s <strong>effort</strong> is the <strong>maximum absolute difference</strong><strong> </strong>in heights between two consecutive cells of the route.</p>\n\n<p>Return <em>the minimum <strong>effort</strong> required to travel from the top-left cell to the bottom-right cell.</em></p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<p><img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/10/04/ex1.png\" style=\"width: 300px; height: 300px;\" /></p>\n\n<pre>\n<strong>Input:</strong> heights = [[1,2,2],[3,8,2],[5,3,5]]\n<strong>Output:</strong> 2\n<strong>Explanation:</strong> The route of [1,3,5,3,5] has a maximum absolute difference of 2 in consecutive cells.\nThis is better than the route of [1,2,2,2,5], where the maximum absolute difference is 3.\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<p><img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/10/04/ex2.png\" style=\"width: 300px; height: 300px;\" /></p>\n\n<pre>\n<strong>Input:</strong> heights = [[1,2,3],[3,8,4],[5,3,5]]\n<strong>Output:</strong> 1\n<strong>Explanation:</strong> The route of [1,2,3,4,5] has a maximum absolute difference of 1 in consecutive cells, which is better than route [1,3,5,3,5].\n</pre>\n\n<p><strong class=\"example\">Example 3:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/10/04/ex3.png\" style=\"width: 300px; height: 300px;\" />\n<pre>\n<strong>Input:</strong> heights = [[1,2,1,1,1],[1,2,1,2,1],[1,2,1,2,1],[1,2,1,2,1],[1,1,1,2,1]]\n<strong>Output:</strong> 0\n<strong>Explanation:</strong> This route does not require any effort.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>rows == heights.length</code></li>\n\t<li><code>columns == heights[i].length</code></li>\n\t<li><code>1 &lt;= rows, columns &lt;= 100</code></li>\n\t<li><code>1 &lt;= heights[i][j] &lt;= 10<sup>6</sup></code></li>\n</ul>\n"}}}
+249
View File
@@ -0,0 +1,249 @@
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="https://www.w3.org/1999/xhtml">
<head>
<title>USACO</title>
<link rel="stylesheet" type="text/css" href="current/usaco.css?v=2.0">
<script src="current/js/jquery.min.js"></script>
<script src="https://d3js.org/d3.v3.min.js"></script>
<META HTTP-EQUIV="EXPIRES" CONTENT="0">
<META HTTP-EQUIV="CACHE-CONTROL" CONTENT="NO-CACHE">
<META HTTP-EQUIV="PRAGMA" CONTENT="NO-CACHE">
<script type="text/x-mathjax-config">
MathJax.Hub.Config({
"HTML-CSS": {
scale: 85,
preferredFont: "STIX"
},
tex2jax: {
inlineMath: [['$','$'],['\\(','\\)']],
processEscapes: true,
skipTags: ['pre'],
processClass: "mathjax",
ignoreClass: "no-mathjax"
}
});
</script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.1/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script>
</head>
<body class="no-mathjax">
<div align="center">
<div class="shadow1">
<div class="content">
<a href="index.php"><img src="current/images/usaco_logo.png" height="130px" border="0px" /></a>
<div class="navbar" align="left" border="10px">
<ul>
<li><a href="index.php">Overview</a></li>
<li><a href="index.php?page=details">Details / FAQ</a></li>
<li><a href="index.php?page=training">Training</a></li>
<li><a href="index.php?page=history">History</a></li>
<li><a href="index.php?page=resources">Resources</a></li>
</ul>
</div><br/>
<div style="position:relative; float:left; left:10px; top:-50px; width:550px;">
<div class="panel">
<h2> USACO 2016 US Open Contest, Silver </h2>
<h2> Problem 3. Closing the Farm </h2>
</div>
</div>
<div align="right" style="position:relative; float:right; right:30px; top:-40px; width:350px;">
<button style="margin-bottom:6px;" type="button" onClick="window.location='index.php?page=open16results';">Return to Problem List</button><br style="padding-top:6px"/>
Contest has ended.
</div>
<br style="clear:both" />
<div id="last-status" style="padding:10px; position:relative; float:left; left:30px; top:-45px; width:820px; border:1px solid black; background-color:#FFF; "
data-response-code="-1" data-sid="-1">
<img src="current/images/ajax.gif"/> <p style="display:inline;"> <b>Log in to allow submissions in analysis mode</b></p>
<div id="trial-information"></div>
<p style="text-align:left;" class="mono prewrap output-data"></p>
</div>
<br style="clear:both" />
<div align="right" style="position:relative; float:right; right:40px; top:-93px; width:350px; z-index:2; padding:0px;">
<form style="padding-top:60px;" action="">
<select name="lang" style="background-color:#eee;" id="choose-language">
<option value='en' selected='yes'>English (en)</option>
<option value='hy'>Armenian (hy)</option>
<option value='bg'>Bulgarian (bg)</option>
<option value='fr'>French (fr)</option>
<option value='ru'>Russian (ru)</option>
<option value='es'>Spanish (es)</option>
</select>
</form>
</div>
<div align="left" style="position:relative; float:left; left:30px; top:-100px; width:840px; z-index:1;">
<div align="left" class="problem-text" style='width:800px; padding-top:10px;'>
<span id="probtext-text" class="mathjax">Farmer John and his cows are planning to leave town for a long vacation, and so
FJ wants to temporarily close down his farm to save money in the meantime.
<p>The farm consists of $N$ barns connected with $M$ bidirectional paths between
some pairs of barns ($1 \leq N, M \leq 3000$). To shut the farm down, FJ plans
to close one barn at a time. When a barn closes, all paths adjacent to that
barn also close, and can no longer be used.
<p>FJ is interested in knowing at each point in time (initially, and after each
closing) whether his farm is "fully connected" -- meaning that it is possible to
travel from any open barn to any other open barn along an appropriate series of
paths. Since FJ's farm is initially in somewhat in a state of disrepair, it may
not even start out fully connected.
<p><div class='prob-in-spec'><h4>INPUT FORMAT (file closing.in):</h4>
The first line of input contains $N$ and $M$. The next $M$ lines each describe a
path in terms of the pair of barns it connects (barns are conveniently numbered
$1 \ldots N$). The final $N$ lines give a permutation of $1 \ldots N$
describing the order in which the barns will be closed.
</div>
<p><div class='prob-out-spec'><h4>OUTPUT FORMAT (file closing.out):</h4>
The output consists of $N$ lines, each containing "YES" or "NO". The first line
indicates whether the initial farm is fully connected, and line $i+1$ indicates
whether the farm is fully connected after the $i$th closing.
</div>
<p><h4>SAMPLE INPUT:</h4><pre class='in'>
4 3
1 2
2 3
3 4
3
4
1
2
</pre><h4>SAMPLE OUTPUT:</h4> <pre class='out'>
YES
NO
YES
YES
</pre>
<p>
<p>Problem credits: Yang Liu
</span>
</div>
Contest has ended. No further submissions allowed.
</div>
<div align="left" style="position:relative; float:left; left:30px; top:-70px; width:840px;">
</div>
<br style="clear:both" />
<script>
var retries = 100, timeout = 1000;
function postback()
{
var sid = $('#last-status').data('sid'); if (sid == -1) return;
$.post('current/tpcm/status-update.php', { sid: sid }, update_response, 'json');
}
function update_response(s)
{
// only try a limited number of times
if (--retries < 0) return;
// if there is xml data, update the DOM
if (s != null)
{
$('#last-status img').attr("src","current/images/medal_none.png");
if (parseInt(s.cd) <= -8 && s.sc == 'status-working') { $('#last-status img').attr("src","current/images/ajax.gif"); }
// change class and text of the response box
$('#last-status').removeClass().addClass(s.sc);
$('#last-status p').text(s.sr);
// change the response code of the data section
$('#last-status').data('response-code', parseInt(s.cd));
$('#last-status .output-data').hide();
if (s.output != null)
{
$('#last-status .output-data').show().text(s.output);
// if the status is in a "working" state, keep checking
if (parseInt($('#last-status').data('response-code')) <= -8)
{ setTimeout(postback, timeout); timeout *= 1.1; }
return;
}
if (s.jd != null && s.jd.length != 0)
$('#trial-information').html(s.jd);
}
// if the status is in a "working" state, keep checking
if (parseInt($('#last-status').data('response-code')) <= -8)
{ setTimeout(postback, timeout); timeout *= 1.1; }
}
$(document).ready(function(){
$('#last-status .output-data').hide();
$('#last-status img').attr("src","current/images/medal_none.png");
if ($('#last-status').length) postback();
$('.masterTooltip').hover(function(){
// Hover over code
var title = $(this).attr('title');
$(this).data('tipText', title).removeAttr('title');
$('<p class="tooltip"></p>').text(title).appendTo('body').fadeIn('fast');
}, function() {
// Hover out code
$(this).attr('title', $(this).data('tipText'));
$('.tooltip').remove();
}).mousemove(function(e) {
var mousex = e.pageX + 20; //Get X coordinates
var mousey = e.pageY + 10; //Get Y coordinates
$('.tooltip').css({ top: mousey, left: mousex })
});
});
$('#choose-language').change(function(e){
window.location = "index.php?page=viewproblem2&cpid=644&lang=" + $(this).val();
});
</script>
</div>
</div>
</div>
<br style="clear:both" />
<script>(function(){function c(){var b=a.contentDocument||(a.contentWindow&&a.contentWindow.document);if(b){var d=b.createElement('script');d.innerHTML="window.__CF$cv$params={r:'a4d22a230b2cc51c',t:'MTc5MjQzNzg4Mw=='};var a=document.createElement('script');a.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js';document.getElementsByTagName('head')[0].appendChild(a);";b.getElementsByTagName('head')[0].appendChild(d)}}if(document.body){var a=document.createElement('iframe');a.height=1;a.width=1;a.style.position='absolute';a.style.top=0;a.style.left=0;a.style.border='none';a.style.visibility='hidden';document.body.appendChild(a);if('loading'!==document.readyState)c();else if(window.addEventListener)document.addEventListener('DOMContentLoaded',c);else{var e=document.onreadystatechange||function(){};document.onreadystatechange=function(b){e(b);'loading'!==document.readyState&&(document.onreadystatechange=e,c())}}}})();</script></body>
</html>