File size: 10,252 Bytes
db764ae
 
 
 
 
 
 
 
 
 
 
 
 
9f87ec0
db764ae
9f87ec0
db764ae
 
9f87ec0
db764ae
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9f87ec0
 
 
db764ae
 
 
 
 
 
 
9f87ec0
 
 
 
 
 
db764ae
 
 
 
 
 
 
 
9f87ec0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
db764ae
 
 
 
 
9f87ec0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
db764ae
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9f87ec0
db764ae
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9f87ec0
db764ae
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9f87ec0
db764ae
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
import { useState, useEffect, Fragment } from "react";
import type { CorpusStats } from "./types";
import { api, checkConnection } from "./api";
import TrainingPanel from "./components/TrainingPanel";
import EngineSetup from "./components/EngineSetup";
import SemanticSearch from "./components/SemanticSearch";
import TextCompare from "./components/TextCompare";
import KeywordAnalysis from "./components/KeywordAnalysis";
import KeywordMatcher from "./components/KeywordMatcher";
import BatchAnalysis from "./components/BatchAnalysis";
import SimilarWords from "./components/SimilarWords";
import ContextAnalysis from "./components/ContextAnalysis";
import Word2VecPanel from "./components/Word2VecPanel";
import Word2VecTools from "./components/Word2VecTools";
import DatasetPanel from "./components/DatasetPanel";
import MetricCard from "./components/MetricCard";
import "./styles.css";

type NavGroup = "data" | "training" | "analysis";
type TrainingTab = "model" | "w2v";
type AnalysisTab = "context" | "words" | "search" | "compare" | "keyword" | "match" | "batch";

const STEPS: { id: NavGroup; label: string; needsIndex?: boolean }[] = [
  { id: "data", label: "Data & Setup" },
  { id: "training", label: "Training" },
  { id: "analysis", label: "Analysis", needsIndex: true },
];

const TRAINING_TABS: { id: TrainingTab; label: string }[] = [
  { id: "model", label: "Fine-tune Model" },
  { id: "w2v", label: "Word2Vec Baseline" },
];

const ANALYSIS_TABS: { id: AnalysisTab; label: string }[] = [
  { id: "context", label: "Context" },
  { id: "words", label: "Similar Words" },
  { id: "search", label: "Search" },
  { id: "compare", label: "Compare" },
  { id: "keyword", label: "Keywords" },
  { id: "match", label: "Matcher" },
  { id: "batch", label: "Batch" },
];

export default function App() {
  const [group, setGroup] = useState<NavGroup>("data");
  const [trainingTab, setTrainingTab] = useState<TrainingTab>("model");
  const [analysisTab, setAnalysisTab] = useState<AnalysisTab>("context");
  const [stats, setStats] = useState<CorpusStats | null>(null);
  const [showManualSetup, setShowManualSetup] = useState(false);
  const [serverError, setServerError] = useState<string | null>(null);
  const [w2vReady, setW2vReady] = useState(false);
  const [w2vInfo, setW2vInfo] = useState<{ vocab_size: number; sentences: number; vector_size: number } | null>(null);
  const [resetLoading, setResetLoading] = useState(false);
  const ready = stats !== null && stats.index_built;

  useEffect(() => {
    checkConnection().then((err) => {
      setServerError(err);
      if (!err) {
        api.getStats().then(setStats).catch(() => {});
        api.w2vStatus().then(res => {
          if (res.ready) {
            setW2vReady(true);
            setW2vInfo({ vocab_size: res.vocab_size!, sentences: res.sentences!, vector_size: res.vector_size! });
          }
        }).catch(() => {});
      }
    });
    const interval = setInterval(() => {
      checkConnection().then(setServerError);
    }, 15000);
    return () => clearInterval(interval);
  }, []);

  function handleW2vReady(ready: boolean, info?: { vocab_size: number; sentences: number; vector_size: number }) {
    setW2vReady(ready);
    setW2vInfo(ready && info ? info : null);
  }

  async function handleReset() {
    setResetLoading(true);
    try {
      await api.w2vReset();
      setW2vReady(false);
      setW2vInfo(null);
    } catch {
      // ignore
    } finally {
      setResetLoading(false);
    }
  }

  function handleStepClick(id: NavGroup, needsIndex?: boolean) {
    if (needsIndex && !ready) return;
    setGroup(id);
  }

  // ── W2V trained: stats bar + analysis tabs, no stepper ──
  if (w2vReady && w2vInfo) {
    return (
      <div className="app">
        <header className="app-header">
          <h1>Contextual Similarity Engine</h1>
          {stats && (
            <div className="header-stats">
              <span className="badge">{stats.model_name}</span>
              <span className="badge">{stats.total_documents} docs</span>
              <span className="badge">{stats.total_chunks} chunks</span>
            </div>
          )}
        </header>

        {serverError && (
          <div className="server-error-banner">
            <strong>Server unavailable:</strong> {serverError}
          </div>
        )}

        {/* W2V stats bar */}
        <div className="content">
          <div className="panel">
            <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", flexWrap: "wrap", gap: 12 }}>
              <h2 style={{ margin: 0 }}>Word2Vec Baseline</h2>
              <button className="btn btn-secondary" onClick={handleReset} disabled={resetLoading}
                style={{ fontSize: "0.85em" }}>
                {resetLoading ? "Resetting..." : "Reset & Retrain"}
              </button>
            </div>
            <div className="metric-grid" style={{ marginTop: 12 }}>
              <MetricCard value={w2vInfo.vocab_size} label="Vocabulary" />
              <MetricCard value={w2vInfo.sentences} label="Sentences" />
              <MetricCard value={w2vInfo.vector_size} label="Dimensions" />
            </div>
          </div>

          {/* W2V-specific tools: Similar Words, Compare, Semantic Search */}
          <Word2VecTools />
        </div>

        {/* Transformer Analysis sub-tabs */}
        <nav className="subtabs">
          {ANALYSIS_TABS.map((t) => (
            <button
              key={t.id}
              className={`subtab ${analysisTab === t.id ? "subtab-active" : ""}`}
              onClick={() => setAnalysisTab(t.id)}
            >
              {t.label}
            </button>
          ))}
        </nav>

        {/* Analysis content */}
        <main className="content">
          {analysisTab === "context" && <ContextAnalysis />}
          {analysisTab === "words" && <SimilarWords />}
          {analysisTab === "search" && <SemanticSearch />}
          {analysisTab === "compare" && <TextCompare />}
          {analysisTab === "keyword" && <KeywordAnalysis />}
          {analysisTab === "match" && <KeywordMatcher />}
          {analysisTab === "batch" && <BatchAnalysis />}
        </main>
      </div>
    );
  }

  // ── Normal stepper flow ──
  return (
    <div className="app">
      <header className="app-header">
        <h1>Contextual Similarity Engine</h1>
        {stats && (
          <div className="header-stats">
            <span className="badge">{stats.model_name}</span>
            <span className="badge">{stats.total_documents} docs</span>
            <span className="badge">{stats.total_chunks} chunks</span>
            <span className={`badge ${stats.index_built ? "badge-ok" : "badge-warn"}`}>
              {stats.index_built ? "Index ready" : "Index not built"}
            </span>
          </div>
        )}
      </header>

      {serverError && (
        <div className="server-error-banner">
          <strong>Server unavailable:</strong> {serverError}
        </div>
      )}

      {/* Progress Stepper */}
      <nav className="stepper">
        {STEPS.map((step, i) => {
          const disabled = step.needsIndex && !ready;
          const active = group === step.id;
          const done = step.id === "data" && ready;
          return (
            <Fragment key={step.id}>
              {i > 0 && (
                <div className={`stepper-line ${!disabled ? "stepper-line-active" : ""}`} />
              )}
              <div className="stepper-item">
                <button
                  className={`stepper-circle ${active ? "stepper-active" : ""} ${done && !active ? "stepper-done" : ""}`}
                  onClick={() => handleStepClick(step.id, step.needsIndex)}
                  disabled={disabled}
                >
                  {done && !active ? "\u2713" : i + 1}
                </button>
                <span className={`stepper-label ${active ? "stepper-label-active" : ""}`}>
                  {step.label}
                </span>
              </div>
            </Fragment>
          );
        })}
      </nav>

      {/* Sub-tabs */}
      {group === "training" && (
        <nav className="subtabs">
          {TRAINING_TABS.map((t) => (
            <button
              key={t.id}
              className={`subtab ${trainingTab === t.id ? "subtab-active" : ""}`}
              onClick={() => setTrainingTab(t.id)}
            >
              {t.label}
            </button>
          ))}
        </nav>
      )}

      {group === "analysis" && (
        <nav className="subtabs">
          {ANALYSIS_TABS.map((t) => (
            <button
              key={t.id}
              className={`subtab ${analysisTab === t.id ? "subtab-active" : ""}`}
              onClick={() => setAnalysisTab(t.id)}
            >
              {t.label}
            </button>
          ))}
        </nav>
      )}

      {/* Content */}
      <main className="content">
        {group === "data" && (
          <>
            <DatasetPanel onStatsUpdate={setStats} />
            <button
              className="collapsible-toggle"
              onClick={() => setShowManualSetup(!showManualSetup)}
            >
              <span className="collapsible-arrow">{showManualSetup ? "\u25be" : "\u25b8"}</span>
              Or add documents manually
            </button>
            {showManualSetup && <EngineSetup onStatsUpdate={setStats} />}
          </>
        )}

        {group === "training" && trainingTab === "model" && <TrainingPanel />}
        {group === "training" && trainingTab === "w2v" && <Word2VecPanel onReady={handleW2vReady} />}

        {group === "analysis" && analysisTab === "context" && <ContextAnalysis />}
        {group === "analysis" && analysisTab === "words" && <SimilarWords />}
        {group === "analysis" && analysisTab === "search" && <SemanticSearch />}
        {group === "analysis" && analysisTab === "compare" && <TextCompare />}
        {group === "analysis" && analysisTab === "keyword" && <KeywordAnalysis />}
        {group === "analysis" && analysisTab === "match" && <KeywordMatcher />}
        {group === "analysis" && analysisTab === "batch" && <BatchAnalysis />}
      </main>
    </div>
  );
}