quanliang commited on
Commit
41d9864
·
1 Parent(s): c5c35e3

1. Added PlotExtract; 2. Made the design the same as the PlotExtract

Browse files
README.md CHANGED
@@ -4,9 +4,12 @@ emoji: 📊
4
  colorFrom: indigo
5
  colorTo: indigo
6
  sdk: docker
 
7
  pinned: false
8
  license: mit
9
  short_description: Turn research papers into structured knowledges and ideas
10
  ---
11
 
12
  Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
4
  colorFrom: indigo
5
  colorTo: indigo
6
  sdk: docker
7
+ app_port: 7860
8
  pinned: false
9
  license: mit
10
  short_description: Turn research papers into structured knowledges and ideas
11
  ---
12
 
13
  Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
14
+
15
+ The welcome screen includes MatSciBot workflows plus PlotExtract at `/plotextract`.
index.html CHANGED
@@ -2,7 +2,14 @@
2
  <html lang="en">
3
  <head>
4
  <meta charset="UTF-8" />
 
5
  <title>Chatbot</title>
 
 
 
 
 
 
6
  <script>
7
  (function () {
8
  const params = new URLSearchParams(window.location.search);
@@ -172,6 +179,30 @@
172
  flex-grow: 1;
173
  }
174
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
175
  form label {
176
  display: flex;
177
  flex-direction: column;
@@ -795,17 +826,71 @@
795
  box-shadow: 0 10px 24px var(--accent-shadow);
796
  }
797
 
798
- /* Landing page has a distinct neutral background */
799
  html[data-mode=""] body {
800
  background:
801
- radial-gradient(circle at 0% 0%, rgba(251, 146, 60, 0.14), transparent 35%),
802
- radial-gradient(circle at 100% 0%, rgba(59, 130, 246, 0.12), transparent 38%),
803
- linear-gradient(180deg, #f6f2eb 0%, #eceff7 100%);
 
 
 
804
  }
805
 
806
  html[data-mode=""] .mode-selection {
807
- background: linear-gradient(180deg, #ffffff 0%, #f7f8fc 100%);
808
- border-color: #d7ddeb;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
809
  }
810
 
811
  html[data-mode=""] .mode-card::before {
@@ -819,9 +904,33 @@
819
  border-top-right-radius: var(--radius-md);
820
  }
821
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
822
  html[data-mode=""] .mode-card[data-mode="QA"] {
823
- border-color: #c8dafc;
824
- background: linear-gradient(180deg, #f4f8ff 0%, #eaf1ff 100%);
825
  }
826
 
827
  html[data-mode=""] .mode-card[data-mode="QA"]::before {
@@ -829,8 +938,8 @@
829
  }
830
 
831
  html[data-mode=""] .mode-card[data-mode="System Chart Extraction"] {
832
- border-color: #bedfd4;
833
- background: linear-gradient(180deg, #edf9f5 0%, #e4f5ef 100%);
834
  }
835
 
836
  html[data-mode=""] .mode-card[data-mode="System Chart Extraction"]::before {
@@ -838,14 +947,23 @@
838
  }
839
 
840
  html[data-mode=""] .mode-card[data-mode="Hypotheses Generation"] {
841
- border-color: #d9caf6;
842
- background: linear-gradient(180deg, #f5f0ff 0%, #efe7ff 100%);
843
  }
844
 
845
  html[data-mode=""] .mode-card[data-mode="Hypotheses Generation"]::before {
846
  background: linear-gradient(90deg, #7c3aed, #ec4899);
847
  }
848
 
 
 
 
 
 
 
 
 
 
849
  html[data-mode=""] .mode-card[data-mode="QA"]:hover {
850
  box-shadow: 0 12px 24px rgba(37, 99, 235, 0.24);
851
  }
@@ -858,6 +976,10 @@
858
  box-shadow: 0 12px 24px rgba(124, 58, 237, 0.24);
859
  }
860
 
 
 
 
 
861
  .section-title {
862
  margin-top: 1.8rem;
863
  margin-bottom: 0.8rem;
@@ -1278,16 +1400,678 @@
1278
  border-radius: 16px;
1279
  }
1280
 
 
 
 
 
1281
  .mode-cards {
1282
  grid-template-columns: 1fr;
1283
  }
1284
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1285
  </style>
1286
  </head>
1287
  <body>
1288
  <div id="modeSelection" class="mode-selection">
1289
- <h2>Mode Selection</h2>
1290
- <p>Choose the workflow you want to start with.</p>
1291
  <div class="mode-cards">
1292
  <button type="button" class="mode-card" data-mode="QA">
1293
  <h3>QA</h3>
@@ -1301,6 +2085,10 @@
1301
  <h3>Hypotheses Generation</h3>
1302
  <p>Generate materials design hypotheses from system charts.</p>
1303
  </button>
 
 
 
 
1304
  </div>
1305
  </div>
1306
  <div id="app">
@@ -1321,21 +2109,17 @@
1321
  <div class="section-title">1) Set API Key</div>
1322
  <form id="apiKeyForm">
1323
  <div class="form-inputs">
 
 
 
 
 
1324
  <label>
1325
  Model:
1326
- <select name="model" id="modelSelect">
1327
- <!-- Options will be populated dynamically -->
1328
- <option value="gpt-5-nano">gpt-5-nano</option>
1329
- <option value="gpt-5-mini">gpt-5-mini</option>
1330
- <option value="gpt-5.2">gpt-5.2</option>
1331
- <option value="gemini-3-flash-preview">gemini-3-flash-preview</option>
1332
- <option value="gemini-3-pro-preview">gemini-3-pro-preview</option>
1333
- <option value="gemini-2.5-flash-lite">gemini-2.5-flash-lite</option>
1334
  </select>
1335
- </label>
1336
- <label id="apiKeyLabel">
1337
- API Key:
1338
- <input type="password" id="apiKeyInput" name="api_key_input" placeholder="Enter your API key">
1339
  </label>
1340
  <details id="advancedParameters">
1341
  <summary>Advanced parameter selection</summary>
@@ -1394,28 +2178,30 @@
1394
  <button type="submit" id="modelSubmitButton">Submit</button>
1395
  </form>
1396
 
1397
- <hr>
1398
 
1399
  <!-- File Upload Form -->
1400
- <div class="section-title">2) Upload Files</div>
1401
- <p style="font-size: 0.9rem; color: #666; margin-bottom: 0.5rem;">If the number of files is greater than 1000, please upload a zip file instead.</p>
1402
- <form id="uploadForm">
1403
- <label>
1404
- Database:
1405
- <input type="text" name="category" value="my-database">
1406
- </label>
1407
-
1408
- <label>
1409
- Select File(s) (.pdf, .txt, .zip, etc.):
1410
- <input type="file" name="files" multiple accept=".pdf,.txt,.text,.png,.jpg,.jpeg,.gif,.bmp,.tiff,.webp,.zip,application/zip">
1411
- </label>
1412
- <button type="submit">Upload</button>
1413
- </form>
1414
 
1415
- <hr>
 
 
 
 
 
 
 
 
1416
 
1417
  <!-- Ask Question Form -->
1418
- <div class="section-title">3) Ask Questions</div>
1419
  <form id="askForm">
1420
  <div class="form-inputs">
1421
  <div id="databaseContainer">
@@ -1631,6 +2417,11 @@
1631
 
1632
  cards.forEach(card => {
1633
  card.addEventListener('click', () => {
 
 
 
 
 
1634
  const mode = card.getAttribute('data-mode');
1635
  const params = new URLSearchParams(window.location.search);
1636
  params.set('mode', mode);
@@ -1696,7 +2487,33 @@
1696
  };
1697
 
1698
  function getModelAdvancedConfig(modelName) {
1699
- return MODEL_ADVANCED_CONFIG[modelName] || { visible: [], defaults: {}, options: {} };
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1700
  }
1701
 
1702
  function setSelectOptions(selectElement, options, defaultValue) {
@@ -1792,41 +2609,147 @@
1792
  configureAdvancedControlsForModel(selectedModel);
1793
  }
1794
 
1795
- document.addEventListener('DOMContentLoaded', async () => {
1796
  initializeAdvancedParameterControls();
1797
- await loadAvailableModels();
1798
  });
1799
 
1800
  // ========================
1801
- // Load available models when page loads
1802
  // ========================
1803
- async function loadAvailableModels() {
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1804
  try {
1805
- const res = await fetch('/available_models');
 
 
1806
  const data = await res.json();
1807
- const modelSelect = document.getElementById('modelSelect');
1808
- const modelsToShow = Array.isArray(data.models) ? data.models : [];
 
 
 
 
 
 
 
 
1809
 
1810
  modelSelect.innerHTML = '';
1811
- modelsToShow.forEach(model => {
1812
- const option = document.createElement('option');
1813
- option.value = model;
1814
- option.textContent = model;
1815
- modelSelect.appendChild(option);
1816
- });
1817
-
1818
- if (modelsToShow.includes('gpt-5.2')) {
1819
- modelSelect.value = 'gpt-5.2';
1820
- } else if (modelsToShow.length > 0) {
1821
- modelSelect.value = modelsToShow[0];
1822
  }
1823
-
1824
- modelSelect.addEventListener('change', () => {
1825
- configureAdvancedControlsForModel(modelSelect.value);
1826
- });
1827
  configureAdvancedControlsForModel(modelSelect.value);
1828
- } catch (error) {
1829
- console.error('Error loading models:', error);
 
 
 
 
 
 
 
 
 
 
1830
  }
1831
  }
1832
 
@@ -3672,4 +4595,4 @@
3672
  initAdminPanel();
3673
  </script>
3674
  </body>
3675
- </html>
 
2
  <html lang="en">
3
  <head>
4
  <meta charset="UTF-8" />
5
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
6
  <title>Chatbot</title>
7
+ <link rel="preconnect" href="https://fonts.googleapis.com" />
8
+ <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
9
+ <link
10
+ href="https://fonts.googleapis.com/css2?family=Electrolize&family=JetBrains+Mono:wght@400;600&family=Space+Grotesk:wght@400;500;600;700&display=swap"
11
+ rel="stylesheet"
12
+ />
13
  <script>
14
  (function () {
15
  const params = new URLSearchParams(window.location.search);
 
179
  flex-grow: 1;
180
  }
181
 
182
+ .provider-badge {
183
+ align-self: flex-end;
184
+ font-size: 0.8rem;
185
+ color: #555;
186
+ padding: 0.3rem 0.6rem;
187
+ border: 1px solid #d7ddeb;
188
+ border-radius: 999px;
189
+ background: #f6f7fb;
190
+ margin-bottom: 0.2rem;
191
+ }
192
+
193
+ .provider-badge[data-provider="openai"] { color: #047857; border-color: #a7f3d0; background: #ecfdf5; }
194
+ .provider-badge[data-provider="anthropic"] { color: #b45309; border-color: #fcd34d; background: #fffbeb; }
195
+ .provider-badge[data-provider="gemini"] { color: #1d4ed8; border-color: #bfdbfe; background: #eff6ff; }
196
+ .provider-badge[data-provider="error"] { color: #b91c1c; border-color: #fecaca; background: #fef2f2; }
197
+
198
+ .model-status {
199
+ font-size: 0.78rem;
200
+ color: #666;
201
+ margin-top: 0.25rem;
202
+ }
203
+ .model-status[data-tone="error"] { color: #b91c1c; }
204
+ .model-status[data-tone="success"] { color: #047857; }
205
+
206
  form label {
207
  display: flex;
208
  flex-direction: column;
 
826
  box-shadow: 0 10px 24px var(--accent-shadow);
827
  }
828
 
829
+ /* Landing page uses the PlotExtract-style dark tool surface */
830
  html[data-mode=""] body {
831
  background:
832
+ radial-gradient(circle at top left, rgba(124, 58, 237, 0.2), transparent 46%),
833
+ radial-gradient(circle at 20% 80%, rgba(6, 182, 212, 0.16), transparent 42%),
834
+ radial-gradient(circle at 100% 15%, rgba(249, 115, 22, 0.1), transparent 32%),
835
+ linear-gradient(160deg, #0b0d12 0%, #0c121f 62%, #0a0f1a 100%);
836
+ align-items: center;
837
+ color: #f8fafc;
838
  }
839
 
840
  html[data-mode=""] .mode-selection {
841
+ max-width: 1120px;
842
+ padding: 3rem;
843
+ text-align: left;
844
+ background:
845
+ linear-gradient(145deg, rgba(124, 58, 237, 0.11), rgba(15, 23, 42, 0.92)),
846
+ rgba(17, 20, 30, 0.94);
847
+ border: 1px solid rgba(120, 134, 170, 0.28);
848
+ border-radius: 18px;
849
+ box-shadow: 0 20px 60px rgba(0, 0, 0, 0.45);
850
+ backdrop-filter: blur(12px);
851
+ overflow: hidden;
852
+ position: relative;
853
+ }
854
+
855
+ html[data-mode=""] .mode-selection::after {
856
+ content: '';
857
+ position: absolute;
858
+ width: 420px;
859
+ height: 420px;
860
+ right: -140px;
861
+ top: -180px;
862
+ border-radius: 999px;
863
+ background: radial-gradient(circle, rgba(124, 58, 237, 0.32), transparent 70%);
864
+ filter: blur(4px);
865
+ pointer-events: none;
866
+ }
867
+
868
+ html[data-mode=""] .mode-selection h2 {
869
+ color: #f8fafc;
870
+ font-family: "Electrolize", "Space Grotesk", "Segoe UI", sans-serif;
871
+ font-size: 3.4rem;
872
+ line-height: 1.05;
873
+ margin-bottom: 0.8rem;
874
+ max-width: 760px;
875
+ position: relative;
876
+ z-index: 1;
877
+ }
878
+
879
+ html[data-mode=""] .mode-selection > p {
880
+ color: #b0b8c5;
881
+ font-size: 1rem;
882
+ line-height: 1.65;
883
+ margin-bottom: 2rem;
884
+ max-width: 660px;
885
+ position: relative;
886
+ z-index: 1;
887
+ }
888
+
889
+ html[data-mode=""] .mode-cards {
890
+ grid-template-columns: repeat(4, minmax(0, 1fr));
891
+ gap: 1rem;
892
+ position: relative;
893
+ z-index: 1;
894
  }
895
 
896
  html[data-mode=""] .mode-card::before {
 
904
  border-top-right-radius: var(--radius-md);
905
  }
906
 
907
+ html[data-mode=""] .mode-card {
908
+ min-height: 178px;
909
+ padding: 1.35rem 1.15rem;
910
+ border-radius: 8px;
911
+ background: rgba(15, 23, 42, 0.68);
912
+ border-color: rgba(120, 134, 170, 0.28);
913
+ box-shadow: 0 18px 36px rgba(0, 0, 0, 0.28);
914
+ color: #f8fafc;
915
+ }
916
+
917
+ html[data-mode=""] .mode-card h3 {
918
+ color: #f8fafc;
919
+ font-family: "Space Grotesk", "Segoe UI", sans-serif;
920
+ font-size: 1.1rem;
921
+ margin-top: 0.25rem;
922
+ margin-bottom: 0.65rem;
923
+ }
924
+
925
+ html[data-mode=""] .mode-card p {
926
+ color: #b0b8c5;
927
+ line-height: 1.55;
928
+ font-size: 0.9rem;
929
+ }
930
+
931
  html[data-mode=""] .mode-card[data-mode="QA"] {
932
+ border-color: rgba(37, 99, 235, 0.42);
933
+ background: linear-gradient(160deg, rgba(37, 99, 235, 0.18), rgba(15, 23, 42, 0.72));
934
  }
935
 
936
  html[data-mode=""] .mode-card[data-mode="QA"]::before {
 
938
  }
939
 
940
  html[data-mode=""] .mode-card[data-mode="System Chart Extraction"] {
941
+ border-color: rgba(16, 185, 129, 0.36);
942
+ background: linear-gradient(160deg, rgba(15, 118, 110, 0.2), rgba(15, 23, 42, 0.72));
943
  }
944
 
945
  html[data-mode=""] .mode-card[data-mode="System Chart Extraction"]::before {
 
947
  }
948
 
949
  html[data-mode=""] .mode-card[data-mode="Hypotheses Generation"] {
950
+ border-color: rgba(124, 58, 237, 0.42);
951
+ background: linear-gradient(160deg, rgba(124, 58, 237, 0.2), rgba(15, 23, 42, 0.72));
952
  }
953
 
954
  html[data-mode=""] .mode-card[data-mode="Hypotheses Generation"]::before {
955
  background: linear-gradient(90deg, #7c3aed, #ec4899);
956
  }
957
 
958
+ html[data-mode=""] .mode-card[data-href="/plotextract"] {
959
+ border-color: rgba(6, 182, 212, 0.4);
960
+ background: linear-gradient(160deg, rgba(6, 182, 212, 0.16), rgba(15, 23, 42, 0.72));
961
+ }
962
+
963
+ html[data-mode=""] .mode-card[data-href="/plotextract"]::before {
964
+ background: linear-gradient(90deg, #7c3aed, #06b6d4, #f97316);
965
+ }
966
+
967
  html[data-mode=""] .mode-card[data-mode="QA"]:hover {
968
  box-shadow: 0 12px 24px rgba(37, 99, 235, 0.24);
969
  }
 
976
  box-shadow: 0 12px 24px rgba(124, 58, 237, 0.24);
977
  }
978
 
979
+ html[data-mode=""] .mode-card[data-href="/plotextract"]:hover {
980
+ box-shadow: 0 12px 24px rgba(124, 58, 237, 0.22);
981
+ }
982
+
983
  .section-title {
984
  margin-top: 1.8rem;
985
  margin-bottom: 0.8rem;
 
1400
  border-radius: 16px;
1401
  }
1402
 
1403
+ html[data-mode=""] .mode-selection h2 {
1404
+ font-size: 2.15rem;
1405
+ }
1406
+
1407
  .mode-cards {
1408
  grid-template-columns: 1fr;
1409
  }
1410
  }
1411
+
1412
+ /* ============================================================
1413
+ Dark theme overlay — aligns QA / System Chart / Hypotheses
1414
+ modes with the PlotExtract aesthetic. Each mode keeps its
1415
+ accent hue (QA: blue, Chart: teal, Hypotheses: purple) on a
1416
+ shared dark surface.
1417
+ ============================================================ */
1418
+
1419
+ /* Shared dark base — applied only inside the three app modes,
1420
+ leaving the landing-page styling untouched. */
1421
+ html[data-mode="QA"],
1422
+ html[data-mode="System Chart Extraction"],
1423
+ html[data-mode="Hypotheses Generation"] {
1424
+ --bg: #0b0d12;
1425
+ --surface: rgba(17, 20, 30, 0.92);
1426
+ --surface-soft: rgba(15, 23, 42, 0.7);
1427
+ --surface-strong: #121826;
1428
+ --text: #f8fafc;
1429
+ --muted: #b0b8c5;
1430
+ --border: rgba(120, 134, 170, 0.28);
1431
+ --border-strong: rgba(148, 163, 184, 0.4);
1432
+ --shadow-sm: 0 4px 16px rgba(0, 0, 0, 0.45);
1433
+ --shadow-md: 0 20px 60px rgba(0, 0, 0, 0.45);
1434
+ --radius-sm: 10px;
1435
+ --radius-md: 14px;
1436
+ --radius-lg: 18px;
1437
+ --font-display: "Electrolize", "Space Grotesk", "Segoe UI", sans-serif;
1438
+ --font-body: "Space Grotesk", "Segoe UI", sans-serif;
1439
+ --font-mono: "JetBrains Mono", "SFMono-Regular", monospace;
1440
+ }
1441
+
1442
+ /* QA — blue accent on dark */
1443
+ html[data-mode="QA"] {
1444
+ --primary: #3b82f6;
1445
+ --primary-dark: #2563eb;
1446
+ --primary-soft: rgba(59, 130, 246, 0.18);
1447
+ --secondary-soft: rgba(56, 189, 248, 0.16);
1448
+ --accent-2: #06b6d4;
1449
+ --bg-glow-primary: rgba(59, 130, 246, 0.18);
1450
+ --bg-glow-secondary: rgba(6, 182, 212, 0.16);
1451
+ --accent-shadow: rgba(59, 130, 246, 0.32);
1452
+ --focus-ring: rgba(59, 130, 246, 0.4);
1453
+ --chat-user-top: rgba(16, 185, 129, 0.42);
1454
+ --chat-user-bottom: rgba(15, 118, 110, 0.42);
1455
+ --chat-user-border: rgba(16, 185, 129, 0.55);
1456
+ --chat-ai-top: rgba(59, 130, 246, 0.4);
1457
+ --chat-ai-bottom: rgba(37, 99, 235, 0.4);
1458
+ --chat-ai-border: rgba(59, 130, 246, 0.55);
1459
+ --progress-gradient: linear-gradient(120deg, #3b82f6, #06b6d4);
1460
+ --scrollbar-thumb: rgba(59, 130, 246, 0.5);
1461
+ --scrollbar-track: rgba(15, 23, 42, 0.6);
1462
+ }
1463
+
1464
+ /* System Chart Extraction — teal accent on dark */
1465
+ html[data-mode="System Chart Extraction"] {
1466
+ --primary: #14b8a6;
1467
+ --primary-dark: #0f766e;
1468
+ --primary-soft: rgba(20, 184, 166, 0.18);
1469
+ --secondary-soft: rgba(16, 185, 129, 0.16);
1470
+ --accent-2: #10b981;
1471
+ --bg-glow-primary: rgba(20, 184, 166, 0.2);
1472
+ --bg-glow-secondary: rgba(16, 185, 129, 0.16);
1473
+ --accent-shadow: rgba(20, 184, 166, 0.32);
1474
+ --focus-ring: rgba(20, 184, 166, 0.4);
1475
+ --chat-user-top: rgba(16, 185, 129, 0.42);
1476
+ --chat-user-bottom: rgba(15, 118, 110, 0.42);
1477
+ --chat-user-border: rgba(16, 185, 129, 0.55);
1478
+ --chat-ai-top: rgba(20, 184, 166, 0.4);
1479
+ --chat-ai-bottom: rgba(15, 118, 110, 0.4);
1480
+ --chat-ai-border: rgba(20, 184, 166, 0.55);
1481
+ --progress-gradient: linear-gradient(120deg, #14b8a6, #10b981);
1482
+ --scrollbar-thumb: rgba(20, 184, 166, 0.5);
1483
+ --scrollbar-track: rgba(15, 23, 42, 0.6);
1484
+ }
1485
+
1486
+ /* Hypotheses Generation — purple accent on dark */
1487
+ html[data-mode="Hypotheses Generation"] {
1488
+ --primary: #a855f7;
1489
+ --primary-dark: #7c3aed;
1490
+ --primary-soft: rgba(168, 85, 247, 0.18);
1491
+ --secondary-soft: rgba(236, 72, 153, 0.16);
1492
+ --accent-2: #ec4899;
1493
+ --bg-glow-primary: rgba(168, 85, 247, 0.2);
1494
+ --bg-glow-secondary: rgba(236, 72, 153, 0.16);
1495
+ --accent-shadow: rgba(168, 85, 247, 0.32);
1496
+ --focus-ring: rgba(168, 85, 247, 0.4);
1497
+ --chat-user-top: rgba(168, 85, 247, 0.42);
1498
+ --chat-user-bottom: rgba(124, 58, 237, 0.42);
1499
+ --chat-user-border: rgba(168, 85, 247, 0.55);
1500
+ --chat-ai-top: rgba(236, 72, 153, 0.4);
1501
+ --chat-ai-bottom: rgba(168, 85, 247, 0.4);
1502
+ --chat-ai-border: rgba(168, 85, 247, 0.55);
1503
+ --progress-gradient: linear-gradient(120deg, #a855f7, #ec4899);
1504
+ --scrollbar-thumb: rgba(168, 85, 247, 0.5);
1505
+ --scrollbar-track: rgba(15, 23, 42, 0.6);
1506
+ }
1507
+
1508
+ html[data-mode="QA"] body,
1509
+ html[data-mode="System Chart Extraction"] body,
1510
+ html[data-mode="Hypotheses Generation"] body {
1511
+ background:
1512
+ radial-gradient(circle at top right, var(--bg-glow-primary), transparent 42%),
1513
+ radial-gradient(circle at 20% 80%, var(--bg-glow-secondary), transparent 45%),
1514
+ linear-gradient(160deg, #0b0d12 0%, #0c121f 60%, #0a0f1a 100%);
1515
+ color: var(--text);
1516
+ font-family: var(--font-body);
1517
+ }
1518
+
1519
+ html[data-mode="QA"] *,
1520
+ html[data-mode="System Chart Extraction"] *,
1521
+ html[data-mode="Hypotheses Generation"] * {
1522
+ font-family: inherit;
1523
+ }
1524
+
1525
+ /* App shell */
1526
+ html[data-mode="QA"] #app,
1527
+ html[data-mode="System Chart Extraction"] #app,
1528
+ html[data-mode="Hypotheses Generation"] #app {
1529
+ background: linear-gradient(145deg, var(--primary-soft), rgba(15, 23, 42, 0.92));
1530
+ border: 1px solid var(--border);
1531
+ box-shadow: var(--shadow-md);
1532
+ backdrop-filter: blur(12px);
1533
+ color: var(--text);
1534
+ }
1535
+
1536
+ html[data-mode="QA"] .app-header h1,
1537
+ html[data-mode="System Chart Extraction"] .app-header h1,
1538
+ html[data-mode="Hypotheses Generation"] .app-header h1 {
1539
+ color: var(--text);
1540
+ font-family: var(--font-display);
1541
+ letter-spacing: 0.02em;
1542
+ }
1543
+
1544
+ html[data-mode="QA"] .app-header p,
1545
+ html[data-mode="System Chart Extraction"] .app-header p,
1546
+ html[data-mode="Hypotheses Generation"] .app-header p {
1547
+ color: var(--muted);
1548
+ }
1549
+
1550
+ html[data-mode="QA"] .section-title,
1551
+ html[data-mode="System Chart Extraction"] .section-title,
1552
+ html[data-mode="Hypotheses Generation"] .section-title {
1553
+ color: var(--text);
1554
+ font-family: var(--font-display);
1555
+ }
1556
+
1557
+ html[data-mode="QA"] hr,
1558
+ html[data-mode="System Chart Extraction"] hr,
1559
+ html[data-mode="Hypotheses Generation"] hr {
1560
+ border: none;
1561
+ border-top: 1px solid var(--border);
1562
+ margin: 1.25rem 0;
1563
+ }
1564
+
1565
+ html[data-mode="QA"] form label,
1566
+ html[data-mode="System Chart Extraction"] form label,
1567
+ html[data-mode="Hypotheses Generation"] form label {
1568
+ color: var(--text);
1569
+ }
1570
+
1571
+ /* Inputs, selects, textareas */
1572
+ html[data-mode="QA"] form input[type="text"],
1573
+ html[data-mode="QA"] form input[type="password"],
1574
+ html[data-mode="QA"] form input[type="number"],
1575
+ html[data-mode="QA"] form select,
1576
+ html[data-mode="QA"] form textarea,
1577
+ html[data-mode="System Chart Extraction"] form input[type="text"],
1578
+ html[data-mode="System Chart Extraction"] form input[type="password"],
1579
+ html[data-mode="System Chart Extraction"] form input[type="number"],
1580
+ html[data-mode="System Chart Extraction"] form select,
1581
+ html[data-mode="System Chart Extraction"] form textarea,
1582
+ html[data-mode="Hypotheses Generation"] form input[type="text"],
1583
+ html[data-mode="Hypotheses Generation"] form input[type="password"],
1584
+ html[data-mode="Hypotheses Generation"] form input[type="number"],
1585
+ html[data-mode="Hypotheses Generation"] form select,
1586
+ html[data-mode="Hypotheses Generation"] form textarea {
1587
+ background-color: var(--surface-soft) !important;
1588
+ color: var(--text) !important;
1589
+ border: 1px solid var(--border) !important;
1590
+ border-radius: var(--radius-sm);
1591
+ }
1592
+
1593
+ html[data-mode="QA"] form input[type="file"],
1594
+ html[data-mode="System Chart Extraction"] form input[type="file"],
1595
+ html[data-mode="Hypotheses Generation"] form input[type="file"] {
1596
+ color: var(--muted);
1597
+ }
1598
+
1599
+ html[data-mode="QA"] form input:focus,
1600
+ html[data-mode="QA"] form select:focus,
1601
+ html[data-mode="QA"] form textarea:focus,
1602
+ html[data-mode="System Chart Extraction"] form input:focus,
1603
+ html[data-mode="System Chart Extraction"] form select:focus,
1604
+ html[data-mode="System Chart Extraction"] form textarea:focus,
1605
+ html[data-mode="Hypotheses Generation"] form input:focus,
1606
+ html[data-mode="Hypotheses Generation"] form select:focus,
1607
+ html[data-mode="Hypotheses Generation"] form textarea:focus {
1608
+ outline: none;
1609
+ border-color: var(--primary) !important;
1610
+ box-shadow: 0 0 0 3px var(--focus-ring);
1611
+ }
1612
+
1613
+ /* Buttons */
1614
+ html[data-mode="QA"] form button[type="submit"],
1615
+ html[data-mode="QA"] button.primary,
1616
+ html[data-mode="System Chart Extraction"] form button[type="submit"],
1617
+ html[data-mode="System Chart Extraction"] button.primary,
1618
+ html[data-mode="Hypotheses Generation"] form button[type="submit"],
1619
+ html[data-mode="Hypotheses Generation"] button.primary {
1620
+ background: linear-gradient(120deg, var(--primary), var(--accent-2)) !important;
1621
+ color: #fff !important;
1622
+ border: none !important;
1623
+ padding: 0.6rem 1.4rem;
1624
+ border-radius: var(--radius-sm);
1625
+ font-weight: 600;
1626
+ cursor: pointer;
1627
+ box-shadow: 0 8px 24px var(--accent-shadow);
1628
+ transition: transform 0.15s ease, box-shadow 0.15s ease;
1629
+ }
1630
+
1631
+ html[data-mode="QA"] form button[type="submit"]:hover:not(:disabled),
1632
+ html[data-mode="System Chart Extraction"] form button[type="submit"]:hover:not(:disabled),
1633
+ html[data-mode="Hypotheses Generation"] form button[type="submit"]:hover:not(:disabled) {
1634
+ transform: translateY(-1px);
1635
+ box-shadow: 0 12px 30px var(--accent-shadow);
1636
+ }
1637
+
1638
+ html[data-mode="QA"] form button[type="submit"]:disabled,
1639
+ html[data-mode="System Chart Extraction"] form button[type="submit"]:disabled,
1640
+ html[data-mode="Hypotheses Generation"] form button[type="submit"]:disabled {
1641
+ opacity: 0.55;
1642
+ cursor: not-allowed;
1643
+ }
1644
+
1645
+ /* Provider badge + model status (used in API key form) */
1646
+ html[data-mode="QA"] .provider-badge,
1647
+ html[data-mode="System Chart Extraction"] .provider-badge,
1648
+ html[data-mode="Hypotheses Generation"] .provider-badge {
1649
+ background: var(--surface-soft);
1650
+ border-color: var(--border);
1651
+ color: var(--muted);
1652
+ }
1653
+ html[data-mode="QA"] .provider-badge[data-provider="openai"],
1654
+ html[data-mode="System Chart Extraction"] .provider-badge[data-provider="openai"],
1655
+ html[data-mode="Hypotheses Generation"] .provider-badge[data-provider="openai"] {
1656
+ color: #34d399; border-color: rgba(16, 185, 129, 0.4); background: rgba(16, 185, 129, 0.1);
1657
+ }
1658
+ html[data-mode="QA"] .provider-badge[data-provider="anthropic"],
1659
+ html[data-mode="System Chart Extraction"] .provider-badge[data-provider="anthropic"],
1660
+ html[data-mode="Hypotheses Generation"] .provider-badge[data-provider="anthropic"] {
1661
+ color: #fbbf24; border-color: rgba(251, 191, 36, 0.4); background: rgba(251, 191, 36, 0.12);
1662
+ }
1663
+ html[data-mode="QA"] .provider-badge[data-provider="gemini"],
1664
+ html[data-mode="System Chart Extraction"] .provider-badge[data-provider="gemini"],
1665
+ html[data-mode="Hypotheses Generation"] .provider-badge[data-provider="gemini"] {
1666
+ color: #60a5fa; border-color: rgba(96, 165, 250, 0.4); background: rgba(59, 130, 246, 0.12);
1667
+ }
1668
+ html[data-mode="QA"] .provider-badge[data-provider="error"],
1669
+ html[data-mode="System Chart Extraction"] .provider-badge[data-provider="error"],
1670
+ html[data-mode="Hypotheses Generation"] .provider-badge[data-provider="error"] {
1671
+ color: #f87171; border-color: rgba(248, 113, 113, 0.4); background: rgba(248, 113, 113, 0.12);
1672
+ }
1673
+ html[data-mode="QA"] .model-status,
1674
+ html[data-mode="System Chart Extraction"] .model-status,
1675
+ html[data-mode="Hypotheses Generation"] .model-status {
1676
+ color: var(--muted);
1677
+ }
1678
+ html[data-mode="QA"] .model-status[data-tone="error"],
1679
+ html[data-mode="System Chart Extraction"] .model-status[data-tone="error"],
1680
+ html[data-mode="Hypotheses Generation"] .model-status[data-tone="error"] {
1681
+ color: #fca5a5;
1682
+ }
1683
+ html[data-mode="QA"] .model-status[data-tone="success"],
1684
+ html[data-mode="System Chart Extraction"] .model-status[data-tone="success"],
1685
+ html[data-mode="Hypotheses Generation"] .model-status[data-tone="success"] {
1686
+ color: #34d399;
1687
+ }
1688
+
1689
+ /* Advanced parameter rows */
1690
+ html[data-mode="QA"] .advanced-params-content,
1691
+ html[data-mode="System Chart Extraction"] .advanced-params-content,
1692
+ html[data-mode="Hypotheses Generation"] .advanced-params-content {
1693
+ background: var(--surface-soft);
1694
+ border: 1px solid var(--border);
1695
+ border-radius: var(--radius-md);
1696
+ }
1697
+
1698
+ html[data-mode="QA"] .advanced-param-row,
1699
+ html[data-mode="System Chart Extraction"] .advanced-param-row,
1700
+ html[data-mode="Hypotheses Generation"] .advanced-param-row {
1701
+ color: var(--text);
1702
+ }
1703
+
1704
+ html[data-mode="QA"] .advanced-param-value,
1705
+ html[data-mode="System Chart Extraction"] .advanced-param-value,
1706
+ html[data-mode="Hypotheses Generation"] .advanced-param-value {
1707
+ color: var(--muted);
1708
+ }
1709
+
1710
+ html[data-mode="QA"] details summary,
1711
+ html[data-mode="System Chart Extraction"] details summary,
1712
+ html[data-mode="Hypotheses Generation"] details summary {
1713
+ color: var(--text);
1714
+ }
1715
+
1716
+ /* Chat / message areas */
1717
+ html[data-mode="QA"] #chat-area,
1718
+ html[data-mode="System Chart Extraction"] #chat-area,
1719
+ html[data-mode="Hypotheses Generation"] #chat-area {
1720
+ background: var(--surface-soft);
1721
+ border: 1px solid var(--border);
1722
+ border-radius: var(--radius-md);
1723
+ padding: 1rem;
1724
+ color: var(--text);
1725
+ }
1726
+
1727
+ html[data-mode="QA"] .user-bubble,
1728
+ html[data-mode="System Chart Extraction"] .user-bubble,
1729
+ html[data-mode="Hypotheses Generation"] .user-bubble {
1730
+ background: linear-gradient(160deg, var(--chat-user-top), var(--chat-user-bottom));
1731
+ border: 1px solid var(--chat-user-border);
1732
+ color: var(--text);
1733
+ }
1734
+
1735
+ html[data-mode="QA"] .ai-bubble,
1736
+ html[data-mode="System Chart Extraction"] .ai-bubble,
1737
+ html[data-mode="Hypotheses Generation"] .ai-bubble {
1738
+ background: linear-gradient(160deg, var(--chat-ai-top), var(--chat-ai-bottom));
1739
+ border: 1px solid var(--chat-ai-border);
1740
+ color: var(--text);
1741
+ }
1742
+
1743
+ html[data-mode="QA"] .error-bubble,
1744
+ html[data-mode="System Chart Extraction"] .error-bubble,
1745
+ html[data-mode="Hypotheses Generation"] .error-bubble {
1746
+ background: rgba(239, 68, 68, 0.12);
1747
+ border-left: 4px solid #ef4444;
1748
+ color: #fecaca;
1749
+ }
1750
+
1751
+ html[data-mode="QA"] .references-section,
1752
+ html[data-mode="System Chart Extraction"] .references-section,
1753
+ html[data-mode="Hypotheses Generation"] .references-section {
1754
+ background: var(--surface-soft);
1755
+ border: 1px solid var(--border);
1756
+ box-shadow: var(--shadow-sm);
1757
+ color: var(--text);
1758
+ }
1759
+ html[data-mode="QA"] .references-section h3,
1760
+ html[data-mode="System Chart Extraction"] .references-section h3,
1761
+ html[data-mode="Hypotheses Generation"] .references-section h3 {
1762
+ color: var(--text);
1763
+ border-bottom-color: var(--primary);
1764
+ }
1765
+ html[data-mode="QA"] .reference-item,
1766
+ html[data-mode="System Chart Extraction"] .reference-item,
1767
+ html[data-mode="Hypotheses Generation"] .reference-item {
1768
+ color: var(--muted);
1769
+ }
1770
+ html[data-mode="QA"] .reference-item strong,
1771
+ html[data-mode="System Chart Extraction"] .reference-item strong,
1772
+ html[data-mode="Hypotheses Generation"] .reference-item strong {
1773
+ color: var(--text);
1774
+ }
1775
+ html[data-mode="QA"] .category-label,
1776
+ html[data-mode="System Chart Extraction"] .category-label,
1777
+ html[data-mode="Hypotheses Generation"] .category-label {
1778
+ color: var(--primary);
1779
+ }
1780
+
1781
+ /* Conversation / hypothesis-chat panes (wrappers built with inline styles) */
1782
+ html[data-mode="QA"] #hypothesis-text-input,
1783
+ html[data-mode="QA"] #original-paper-content-input,
1784
+ html[data-mode="QA"] #hypothesis-chat-input,
1785
+ html[data-mode="QA"] #hypothesis-chat-messages,
1786
+ html[data-mode="QA"] #conversation-messages,
1787
+ html[data-mode="QA"] #conversationSelect,
1788
+ html[data-mode="QA"] #followUpQuestion,
1789
+ html[data-mode="System Chart Extraction"] #hypothesis-text-input,
1790
+ html[data-mode="System Chart Extraction"] #original-paper-content-input,
1791
+ html[data-mode="System Chart Extraction"] #hypothesis-chat-input,
1792
+ html[data-mode="System Chart Extraction"] #hypothesis-chat-messages,
1793
+ html[data-mode="System Chart Extraction"] #conversation-messages,
1794
+ html[data-mode="System Chart Extraction"] #conversationSelect,
1795
+ html[data-mode="System Chart Extraction"] #followUpQuestion,
1796
+ html[data-mode="Hypotheses Generation"] #hypothesis-text-input,
1797
+ html[data-mode="Hypotheses Generation"] #original-paper-content-input,
1798
+ html[data-mode="Hypotheses Generation"] #hypothesis-chat-input,
1799
+ html[data-mode="Hypotheses Generation"] #hypothesis-chat-messages,
1800
+ html[data-mode="Hypotheses Generation"] #conversation-messages,
1801
+ html[data-mode="Hypotheses Generation"] #conversationSelect,
1802
+ html[data-mode="Hypotheses Generation"] #followUpQuestion {
1803
+ background-color: var(--surface-soft) !important;
1804
+ border: 1px solid var(--border) !important;
1805
+ color: var(--text) !important;
1806
+ }
1807
+
1808
+ html[data-mode="QA"] #hypothesis-text-input::placeholder,
1809
+ html[data-mode="QA"] #original-paper-content-input::placeholder,
1810
+ html[data-mode="QA"] #hypothesis-chat-input::placeholder,
1811
+ html[data-mode="QA"] #followUpQuestion::placeholder,
1812
+ html[data-mode="System Chart Extraction"] #hypothesis-text-input::placeholder,
1813
+ html[data-mode="System Chart Extraction"] #original-paper-content-input::placeholder,
1814
+ html[data-mode="System Chart Extraction"] #hypothesis-chat-input::placeholder,
1815
+ html[data-mode="System Chart Extraction"] #followUpQuestion::placeholder,
1816
+ html[data-mode="Hypotheses Generation"] #hypothesis-text-input::placeholder,
1817
+ html[data-mode="Hypotheses Generation"] #original-paper-content-input::placeholder,
1818
+ html[data-mode="Hypotheses Generation"] #hypothesis-chat-input::placeholder,
1819
+ html[data-mode="Hypotheses Generation"] #followUpQuestion::placeholder {
1820
+ color: var(--muted);
1821
+ }
1822
+
1823
+ /* Buttons embedded inline (Start hypothesis chat, Send, Load conversation, Submit follow-up) */
1824
+ html[data-mode="QA"] #start-hypothesis-conversation-btn,
1825
+ html[data-mode="QA"] #send-hypothesis-message-btn,
1826
+ html[data-mode="QA"] #loadConversationBtn,
1827
+ html[data-mode="System Chart Extraction"] #start-hypothesis-conversation-btn,
1828
+ html[data-mode="System Chart Extraction"] #send-hypothesis-message-btn,
1829
+ html[data-mode="System Chart Extraction"] #loadConversationBtn,
1830
+ html[data-mode="Hypotheses Generation"] #start-hypothesis-conversation-btn,
1831
+ html[data-mode="Hypotheses Generation"] #send-hypothesis-message-btn,
1832
+ html[data-mode="Hypotheses Generation"] #loadConversationBtn {
1833
+ background: linear-gradient(120deg, var(--primary), var(--accent-2)) !important;
1834
+ color: #fff !important;
1835
+ border: none !important;
1836
+ box-shadow: 0 8px 24px var(--accent-shadow);
1837
+ }
1838
+
1839
+ /* Section panels with hardcoded f8f9fa backgrounds */
1840
+ html[data-mode="QA"] #hypothesesContainer > div,
1841
+ html[data-mode="QA"] #conversation-section > div,
1842
+ html[data-mode="QA"] #hypotheses-conversation-section > div,
1843
+ html[data-mode="System Chart Extraction"] #hypothesesContainer > div,
1844
+ html[data-mode="System Chart Extraction"] #conversation-section > div,
1845
+ html[data-mode="System Chart Extraction"] #hypotheses-conversation-section > div,
1846
+ html[data-mode="Hypotheses Generation"] #hypothesesContainer > div,
1847
+ html[data-mode="Hypotheses Generation"] #conversation-section > div,
1848
+ html[data-mode="Hypotheses Generation"] #hypotheses-conversation-section > div {
1849
+ background: var(--surface) !important;
1850
+ border: 1px solid var(--border) !important;
1851
+ box-shadow: var(--shadow-sm);
1852
+ }
1853
+
1854
+ html[data-mode="QA"] #visualizationContainer,
1855
+ html[data-mode="System Chart Extraction"] #visualizationContainer,
1856
+ html[data-mode="Hypotheses Generation"] #visualizationContainer {
1857
+ background: var(--surface) !important;
1858
+ border: 1px solid var(--border) !important;
1859
+ box-shadow: var(--shadow-sm);
1860
+ }
1861
+
1862
+ html[data-mode="QA"] #visualizationContainer label,
1863
+ html[data-mode="System Chart Extraction"] #visualizationContainer label,
1864
+ html[data-mode="Hypotheses Generation"] #visualizationContainer label {
1865
+ color: var(--text) !important;
1866
+ }
1867
+
1868
+ /* h4 inside the hypothesis/conversation panes */
1869
+ html[data-mode="QA"] #hypotheses-conversation-section h4,
1870
+ html[data-mode="QA"] #conversation-section h4,
1871
+ html[data-mode="System Chart Extraction"] #hypotheses-conversation-section h4,
1872
+ html[data-mode="System Chart Extraction"] #conversation-section h4,
1873
+ html[data-mode="Hypotheses Generation"] #hypotheses-conversation-section h4,
1874
+ html[data-mode="Hypotheses Generation"] #conversation-section h4 {
1875
+ color: var(--text) !important;
1876
+ }
1877
+
1878
+ html[data-mode="QA"] #hypotheses-conversation-section small,
1879
+ html[data-mode="QA"] #conversation-section small,
1880
+ html[data-mode="QA"] #hypotheses-conversation-section p,
1881
+ html[data-mode="QA"] #conversation-section p,
1882
+ html[data-mode="System Chart Extraction"] #hypotheses-conversation-section small,
1883
+ html[data-mode="System Chart Extraction"] #conversation-section small,
1884
+ html[data-mode="System Chart Extraction"] #hypotheses-conversation-section p,
1885
+ html[data-mode="System Chart Extraction"] #conversation-section p,
1886
+ html[data-mode="Hypotheses Generation"] #hypotheses-conversation-section small,
1887
+ html[data-mode="Hypotheses Generation"] #conversation-section small,
1888
+ html[data-mode="Hypotheses Generation"] #hypotheses-conversation-section p,
1889
+ html[data-mode="Hypotheses Generation"] #conversation-section p {
1890
+ color: var(--muted) !important;
1891
+ }
1892
+
1893
+ /* Banner / model-selection-banner */
1894
+ html[data-mode="QA"] .model-selection-banner,
1895
+ html[data-mode="System Chart Extraction"] .model-selection-banner,
1896
+ html[data-mode="Hypotheses Generation"] .model-selection-banner {
1897
+ background: var(--surface-soft);
1898
+ border: 1px solid var(--border);
1899
+ color: var(--text);
1900
+ }
1901
+
1902
+ /* Code blocks / pre */
1903
+ html[data-mode="QA"] pre,
1904
+ html[data-mode="QA"] code,
1905
+ html[data-mode="System Chart Extraction"] pre,
1906
+ html[data-mode="System Chart Extraction"] code,
1907
+ html[data-mode="Hypotheses Generation"] pre,
1908
+ html[data-mode="Hypotheses Generation"] code {
1909
+ background: rgba(2, 6, 23, 0.7);
1910
+ color: #e2e8f0;
1911
+ font-family: var(--font-mono);
1912
+ }
1913
+
1914
+ /* Scrollbars (WebKit) */
1915
+ html[data-mode="QA"] ::-webkit-scrollbar,
1916
+ html[data-mode="System Chart Extraction"] ::-webkit-scrollbar,
1917
+ html[data-mode="Hypotheses Generation"] ::-webkit-scrollbar {
1918
+ width: 10px;
1919
+ height: 10px;
1920
+ }
1921
+ html[data-mode="QA"] ::-webkit-scrollbar-track,
1922
+ html[data-mode="System Chart Extraction"] ::-webkit-scrollbar-track,
1923
+ html[data-mode="Hypotheses Generation"] ::-webkit-scrollbar-track {
1924
+ background: var(--scrollbar-track);
1925
+ }
1926
+ html[data-mode="QA"] ::-webkit-scrollbar-thumb,
1927
+ html[data-mode="System Chart Extraction"] ::-webkit-scrollbar-thumb,
1928
+ html[data-mode="Hypotheses Generation"] ::-webkit-scrollbar-thumb {
1929
+ background: var(--scrollbar-thumb);
1930
+ border-radius: 999px;
1931
+ }
1932
+
1933
+ /* Helper rules for elements that the JS injects with hardcoded styles */
1934
+ html[data-mode="QA"] .error-message,
1935
+ html[data-mode="System Chart Extraction"] .error-message,
1936
+ html[data-mode="Hypotheses Generation"] .error-message {
1937
+ background: rgba(239, 68, 68, 0.12) !important;
1938
+ color: #fca5a5 !important;
1939
+ border: 1px solid rgba(239, 68, 68, 0.4) !important;
1940
+ }
1941
+
1942
+ html[data-mode="QA"] hr,
1943
+ html[data-mode="System Chart Extraction"] hr,
1944
+ html[data-mode="Hypotheses Generation"] hr {
1945
+ border-color: var(--border);
1946
+ }
1947
+
1948
+ /* The danger zone separator */
1949
+ html[data-mode="QA"] #adminDangerZone,
1950
+ html[data-mode="System Chart Extraction"] #adminDangerZone,
1951
+ html[data-mode="Hypotheses Generation"] #adminDangerZone {
1952
+ border-top-color: var(--border) !important;
1953
+ }
1954
+
1955
+ /* Wrapper divs that hardcode `background-color: #f8f9fa` inline (no ID/class) */
1956
+ html[data-mode="QA"] div[style*="#f8f9fa"],
1957
+ html[data-mode="System Chart Extraction"] div[style*="#f8f9fa"],
1958
+ html[data-mode="Hypotheses Generation"] div[style*="#f8f9fa"] {
1959
+ background-color: var(--surface) !important;
1960
+ border-color: var(--border) !important;
1961
+ color: var(--text);
1962
+ }
1963
+
1964
+ html[data-mode="QA"] div[style*="#f8f9fa"] small,
1965
+ html[data-mode="QA"] div[style*="#f8f9fa"] p,
1966
+ html[data-mode="System Chart Extraction"] div[style*="#f8f9fa"] small,
1967
+ html[data-mode="System Chart Extraction"] div[style*="#f8f9fa"] p,
1968
+ html[data-mode="Hypotheses Generation"] div[style*="#f8f9fa"] small,
1969
+ html[data-mode="Hypotheses Generation"] div[style*="#f8f9fa"] p {
1970
+ color: var(--muted) !important;
1971
+ }
1972
+
1973
+ /* Loose hint <small> tags scattered with inline color: #666 */
1974
+ html[data-mode="QA"] small[style*="color: #666"],
1975
+ html[data-mode="QA"] p[style*="color: #666"],
1976
+ html[data-mode="System Chart Extraction"] small[style*="color: #666"],
1977
+ html[data-mode="System Chart Extraction"] p[style*="color: #666"],
1978
+ html[data-mode="Hypotheses Generation"] small[style*="color: #666"],
1979
+ html[data-mode="Hypotheses Generation"] p[style*="color: #666"] {
1980
+ color: var(--muted) !important;
1981
+ }
1982
+
1983
+ /* JS-emitted inline buttons / status divs (e.g., `background: #f8f9fa; border-left: 4px solid #4285F4`) */
1984
+ html[data-mode="QA"] div[style*="background: #f8f9fa"],
1985
+ html[data-mode="System Chart Extraction"] div[style*="background: #f8f9fa"],
1986
+ html[data-mode="Hypotheses Generation"] div[style*="background: #f8f9fa"] {
1987
+ background: var(--surface-soft) !important;
1988
+ color: var(--text) !important;
1989
+ border-left-color: var(--primary) !important;
1990
+ }
1991
+
1992
+ /* JS-emitted message bubbles inside conversation/hypothesis chat panes
1993
+ (loadConversationHistory + sendHypothesisMessage create divs with hardcoded
1994
+ light backgrounds — override so text stays readable in dark mode) */
1995
+ html[data-mode="QA"] #conversation-messages > div,
1996
+ html[data-mode="QA"] #hypothesis-chat-messages > div,
1997
+ html[data-mode="System Chart Extraction"] #conversation-messages > div,
1998
+ html[data-mode="System Chart Extraction"] #hypothesis-chat-messages > div,
1999
+ html[data-mode="Hypotheses Generation"] #conversation-messages > div,
2000
+ html[data-mode="Hypotheses Generation"] #hypothesis-chat-messages > div {
2001
+ background: var(--surface) !important;
2002
+ color: var(--text) !important;
2003
+ }
2004
+
2005
+ /* Progress container inside loading bubbles (system chart extraction "Started"
2006
+ progress bar) — base rule has a white gradient that bleeds through the
2007
+ transparent override; force a dark background in app modes. */
2008
+ html[data-mode="QA"] .progress-container,
2009
+ html[data-mode="System Chart Extraction"] .progress-container,
2010
+ html[data-mode="Hypotheses Generation"] .progress-container {
2011
+ background: var(--surface) !important;
2012
+ border: 1px solid var(--border) !important;
2013
+ color: var(--text) !important;
2014
+ }
2015
+ html[data-mode="QA"] .loading-bubble .progress-container,
2016
+ html[data-mode="System Chart Extraction"] .loading-bubble .progress-container,
2017
+ html[data-mode="Hypotheses Generation"] .loading-bubble .progress-container {
2018
+ background: transparent !important;
2019
+ border: none !important;
2020
+ }
2021
+ html[data-mode="QA"] .progress-status,
2022
+ html[data-mode="QA"] .progress-details,
2023
+ html[data-mode="QA"] .progress-message,
2024
+ html[data-mode="QA"] .progress-percentage,
2025
+ html[data-mode="System Chart Extraction"] .progress-status,
2026
+ html[data-mode="System Chart Extraction"] .progress-details,
2027
+ html[data-mode="System Chart Extraction"] .progress-message,
2028
+ html[data-mode="System Chart Extraction"] .progress-percentage,
2029
+ html[data-mode="Hypotheses Generation"] .progress-status,
2030
+ html[data-mode="Hypotheses Generation"] .progress-details,
2031
+ html[data-mode="Hypotheses Generation"] .progress-message,
2032
+ html[data-mode="Hypotheses Generation"] .progress-percentage {
2033
+ color: var(--text) !important;
2034
+ }
2035
+
2036
+ /* Dim helper text inside completion bubbles uses inline color: #666 — over
2037
+ the now-opaque teal/blue/purple bubble fill, --muted (#b0b8c5) is too
2038
+ low-contrast to read, so force full --text inside .ai-bubble specifically. */
2039
+ html[data-mode="QA"] .ai-bubble p[style*="color: #666"],
2040
+ html[data-mode="System Chart Extraction"] .ai-bubble p[style*="color: #666"],
2041
+ html[data-mode="Hypotheses Generation"] .ai-bubble p[style*="color: #666"] {
2042
+ color: var(--text) !important;
2043
+ }
2044
+
2045
+ /* "Download Results (ZIP)" button inside completion bubbles — has no styling,
2046
+ falls back to browser default. Give it the same accent treatment as primary
2047
+ buttons in app modes. */
2048
+ html[data-mode="QA"] .ai-bubble .download-btn,
2049
+ html[data-mode="System Chart Extraction"] .ai-bubble .download-btn,
2050
+ html[data-mode="Hypotheses Generation"] .ai-bubble .download-btn {
2051
+ background: linear-gradient(120deg, var(--primary), var(--accent-2)) !important;
2052
+ color: #fff !important;
2053
+ border: none !important;
2054
+ padding: 0.5rem 1rem;
2055
+ border-radius: var(--radius-sm);
2056
+ font-weight: 600;
2057
+ cursor: pointer;
2058
+ box-shadow: 0 6px 18px var(--accent-shadow);
2059
+ }
2060
+
2061
+ /* Hide Upload Files section and renumber Ask Questions in Hypotheses Generation mode */
2062
+ html[data-mode="Hypotheses Generation"] #uploadSection {
2063
+ display: none !important;
2064
+ }
2065
+ .step-number-hypotheses { display: none; }
2066
+ html[data-mode="Hypotheses Generation"] .step-number-default { display: none; }
2067
+ html[data-mode="Hypotheses Generation"] .step-number-hypotheses { display: inline; }
2068
+
2069
  </style>
2070
  </head>
2071
  <body>
2072
  <div id="modeSelection" class="mode-selection">
2073
+ <h2>Choose your research workflow</h2>
2074
+ <p>Move between document QA, system chart extraction, hypotheses generation, and plot data extraction from one Space.</p>
2075
  <div class="mode-cards">
2076
  <button type="button" class="mode-card" data-mode="QA">
2077
  <h3>QA</h3>
 
2085
  <h3>Hypotheses Generation</h3>
2086
  <p>Generate materials design hypotheses from system charts.</p>
2087
  </button>
2088
+ <button type="button" class="mode-card" data-href="/plotextract">
2089
+ <h3>PlotExtract</h3>
2090
+ <p>Extract CSV data from plot images with Anthropic or OpenAI models.</p>
2091
+ </button>
2092
  </div>
2093
  </div>
2094
  <div id="app">
 
2109
  <div class="section-title">1) Set API Key</div>
2110
  <form id="apiKeyForm">
2111
  <div class="form-inputs">
2112
+ <label id="apiKeyLabel">
2113
+ API Key:
2114
+ <input type="password" id="apiKeyInput" name="api_key_input" placeholder="sk-... (OpenAI), sk-ant-... (Anthropic), or AIza... (Gemini)" autocomplete="off">
2115
+ </label>
2116
+ <div id="providerBadge" class="provider-badge" data-provider="">Provider: —</div>
2117
  <label>
2118
  Model:
2119
+ <select name="model" id="modelSelect" disabled>
2120
+ <option value="">Enter API key to load models</option>
 
 
 
 
 
 
2121
  </select>
2122
+ <span id="modelStatus" class="model-status"></span>
 
 
 
2123
  </label>
2124
  <details id="advancedParameters">
2125
  <summary>Advanced parameter selection</summary>
 
2178
  <button type="submit" id="modelSubmitButton">Submit</button>
2179
  </form>
2180
 
2181
+ <hr id="uploadSectionDivider">
2182
 
2183
  <!-- File Upload Form -->
2184
+ <div id="uploadSection">
2185
+ <div class="section-title">2) Upload Files</div>
2186
+ <p style="font-size: 0.9rem; color: #666; margin-bottom: 0.5rem;">If the number of files is greater than 1000, please upload a zip file instead.</p>
2187
+ <form id="uploadForm">
2188
+ <label>
2189
+ Database:
2190
+ <input type="text" name="category" value="my-database">
2191
+ </label>
 
 
 
 
 
 
2192
 
2193
+ <label>
2194
+ Select File(s) (.pdf, .txt, .zip, etc.):
2195
+ <input type="file" name="files" multiple accept=".pdf,.txt,.text,.png,.jpg,.jpeg,.gif,.bmp,.tiff,.webp,.zip,application/zip">
2196
+ </label>
2197
+ <button type="submit">Upload</button>
2198
+ </form>
2199
+
2200
+ <hr>
2201
+ </div>
2202
 
2203
  <!-- Ask Question Form -->
2204
+ <div class="section-title"><span class="step-number-default">3)</span><span class="step-number-hypotheses">2)</span> Ask Questions</div>
2205
  <form id="askForm">
2206
  <div class="form-inputs">
2207
  <div id="databaseContainer">
 
2417
 
2418
  cards.forEach(card => {
2419
  card.addEventListener('click', () => {
2420
+ const href = card.getAttribute('data-href');
2421
+ if (href) {
2422
+ window.open(href, '_blank');
2423
+ return;
2424
+ }
2425
  const mode = card.getAttribute('data-mode');
2426
  const params = new URLSearchParams(window.location.search);
2427
  params.set('mode', mode);
 
2487
  };
2488
 
2489
  function getModelAdvancedConfig(modelName) {
2490
+ if (MODEL_ADVANCED_CONFIG[modelName]) return MODEL_ADVANCED_CONFIG[modelName];
2491
+ const m = (modelName || '').toLowerCase();
2492
+ // Pattern fallback so dynamically-fetched models still surface a sensible advanced-params UI.
2493
+ if (m.includes('gpt-5')) {
2494
+ return {
2495
+ visible: ["reasoning_effort", "verbosity"],
2496
+ defaults: { reasoning_effort: "medium", verbosity: "medium" },
2497
+ options: { reasoning_effort: ["minimal", "low", "medium", "high"], verbosity: ["low", "medium", "high"] }
2498
+ };
2499
+ }
2500
+ if (m.includes('gpt')) {
2501
+ return { visible: ["temperature", "top_p"], defaults: { temperature: 1.0, top_p: 1.0 }, options: {} };
2502
+ }
2503
+ if (m.includes('gemini') && m.includes('pro')) {
2504
+ return {
2505
+ visible: ["temperature", "top_p", "thinking_level"],
2506
+ defaults: { temperature: 1.0, top_p: 0.95, thinking_level: "high" },
2507
+ options: { thinking_level: ["low", "high"] }
2508
+ };
2509
+ }
2510
+ if (m.includes('gemini')) {
2511
+ return { visible: ["temperature", "top_p"], defaults: { temperature: 1.0, top_p: 0.95 }, options: {} };
2512
+ }
2513
+ if (m.includes('claude')) {
2514
+ return { visible: ["temperature", "top_p"], defaults: { temperature: 1.0, top_p: 1.0 }, options: {} };
2515
+ }
2516
+ return { visible: [], defaults: {}, options: {} };
2517
  }
2518
 
2519
  function setSelectOptions(selectElement, options, defaultValue) {
 
2609
  configureAdvancedControlsForModel(selectedModel);
2610
  }
2611
 
2612
+ document.addEventListener('DOMContentLoaded', () => {
2613
  initializeAdvancedParameterControls();
2614
+ setupApiKeyAutoLoad();
2615
  });
2616
 
2617
  // ========================
2618
+ // Provider detection + dynamic model loading
2619
  // ========================
2620
+ function detectProviderFromKey(key) {
2621
+ const k = (key || '').trim();
2622
+ if (!k) return '';
2623
+ if (k.startsWith('sk-ant-')) return 'anthropic';
2624
+ if (k.startsWith('AIza')) return 'gemini';
2625
+ if (k.startsWith('sk-')) return 'openai';
2626
+ return '';
2627
+ }
2628
+
2629
+ function setProviderBadge(provider, label) {
2630
+ const badge = document.getElementById('providerBadge');
2631
+ if (!badge) return;
2632
+ badge.dataset.provider = provider || '';
2633
+ badge.textContent = label ? `Provider: ${label}` : 'Provider: —';
2634
+ }
2635
+
2636
+ function setModelStatus(text, tone = '') {
2637
+ const el = document.getElementById('modelStatus');
2638
+ if (!el) return;
2639
+ el.textContent = text || '';
2640
+ if (tone) {
2641
+ el.dataset.tone = tone;
2642
+ } else {
2643
+ delete el.dataset.tone;
2644
+ }
2645
+ }
2646
+
2647
+ function setModelDropdownPlaceholder(text) {
2648
+ const modelSelect = document.getElementById('modelSelect');
2649
+ if (!modelSelect) return;
2650
+ modelSelect.innerHTML = '';
2651
+ const opt = document.createElement('option');
2652
+ opt.value = '';
2653
+ opt.textContent = text;
2654
+ modelSelect.appendChild(opt);
2655
+ modelSelect.value = '';
2656
+ modelSelect.disabled = true;
2657
+ }
2658
+
2659
+ let _modelsLoadedForKey = '';
2660
+ let _modelsLoading = false;
2661
+
2662
+ function setupApiKeyAutoLoad() {
2663
+ const apiKeyInput = document.getElementById('apiKeyInput');
2664
+ const modelSelect = document.getElementById('modelSelect');
2665
+ if (!apiKeyInput || !modelSelect) return;
2666
+
2667
+ modelSelect.addEventListener('change', () => {
2668
+ configureAdvancedControlsForModel(modelSelect.value);
2669
+ });
2670
+
2671
+ apiKeyInput.addEventListener('input', () => {
2672
+ const provider = detectProviderFromKey(apiKeyInput.value);
2673
+ if (provider) {
2674
+ setProviderBadge(provider, provider === 'openai' ? 'OpenAI' : provider === 'anthropic' ? 'Anthropic' : 'Gemini');
2675
+ } else {
2676
+ setProviderBadge('', null);
2677
+ }
2678
+ if (apiKeyInput.value.trim() !== _modelsLoadedForKey) {
2679
+ _modelsLoadedForKey = '';
2680
+ setModelDropdownPlaceholder(apiKeyInput.value.trim() ? 'Tab/click out to load models' : 'Enter API key to load models');
2681
+ setModelStatus('');
2682
+ }
2683
+ });
2684
+
2685
+ apiKeyInput.addEventListener('blur', () => {
2686
+ loadModelsForKey();
2687
+ });
2688
+ }
2689
+
2690
+ async function loadModelsForKey({ silent = false } = {}) {
2691
+ const apiKeyInput = document.getElementById('apiKeyInput');
2692
+ const modelSelect = document.getElementById('modelSelect');
2693
+ const key = (apiKeyInput?.value || '').trim();
2694
+ if (!key) {
2695
+ setModelDropdownPlaceholder('Enter API key to load models');
2696
+ setModelStatus('');
2697
+ _modelsLoadedForKey = '';
2698
+ return false;
2699
+ }
2700
+ if (_modelsLoadedForKey === key) return true;
2701
+ if (_modelsLoading) return false;
2702
+
2703
+ const provider = detectProviderFromKey(key);
2704
+ if (!provider) {
2705
+ setProviderBadge('error', 'unknown');
2706
+ setModelDropdownPlaceholder('Unsupported key format');
2707
+ setModelStatus('Use an OpenAI (sk-...), Anthropic (sk-ant-...), or Gemini (AIza...) key.', 'error');
2708
+ return false;
2709
+ }
2710
+
2711
+ _modelsLoading = true;
2712
+ setModelDropdownPlaceholder('Loading models...');
2713
+ if (!silent) setModelStatus('Loading models...');
2714
+
2715
  try {
2716
+ const formData = new FormData();
2717
+ formData.append('api_key_input', key);
2718
+ const res = await fetch('/list_models', { method: 'POST', body: formData });
2719
  const data = await res.json();
2720
+ if (!res.ok) {
2721
+ const detail = data.details ? ` (${data.details})` : '';
2722
+ throw new Error(`${data.message || 'Failed to load models.'}${detail}`);
2723
+ }
2724
+ const models = Array.isArray(data.models) ? data.models : [];
2725
+ if (!models.length) {
2726
+ setModelDropdownPlaceholder('No models available');
2727
+ setModelStatus('No models available for this key.', 'error');
2728
+ return false;
2729
+ }
2730
 
2731
  modelSelect.innerHTML = '';
2732
+ for (const m of models) {
2733
+ const opt = document.createElement('option');
2734
+ opt.value = m.id;
2735
+ opt.textContent = m.display_name && m.display_name !== m.id ? `${m.display_name} (${m.id})` : m.id;
2736
+ modelSelect.appendChild(opt);
 
 
 
 
 
 
2737
  }
2738
+ modelSelect.disabled = false;
2739
+ modelSelect.value = data.default_model || models[0].id;
 
 
2740
  configureAdvancedControlsForModel(modelSelect.value);
2741
+
2742
+ _modelsLoadedForKey = key;
2743
+ setProviderBadge(data.provider, data.provider_label);
2744
+ setModelStatus(`Loaded ${models.length} ${data.provider_label} model${models.length === 1 ? '' : 's'}.`, 'success');
2745
+ return true;
2746
+ } catch (err) {
2747
+ setModelDropdownPlaceholder('Could not load models');
2748
+ setModelStatus(err.message || 'Failed to load models.', 'error');
2749
+ _modelsLoadedForKey = '';
2750
+ return false;
2751
+ } finally {
2752
+ _modelsLoading = false;
2753
  }
2754
  }
2755
 
 
4595
  initAdminPanel();
4596
  </script>
4597
  </body>
4598
+ </html>
main.py CHANGED
@@ -18,6 +18,7 @@ from rapidfuzz import fuzz
18
  from fastapi import FastAPI, UploadFile, File, Form, BackgroundTasks
19
  from fastapi.responses import JSONResponse, FileResponse
20
  from fastapi.middleware.cors import CORSMiddleware
 
21
  from zipfile import ZipFile
22
 
23
  # Setup logging
@@ -43,6 +44,24 @@ except ImportError:
43
  ChatGoogleGenerativeAI = None
44
  GoogleGenerativeAIEmbeddings = None
45
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
46
  from pdf_text_processing import (
47
  extract_text_from_pdf,
48
  extract_and_split,
@@ -55,6 +74,7 @@ from system_chart_service import SystemChartService
55
  from hypotheses_service import HypothesesService
56
  from prompts import create_hypotheses_generation_prompt
57
  from conversation_storage import save_conversation, get_conversations, update_conversation
 
58
 
59
  # Metadata management functions
60
  def load_metadata(database: str) -> Dict[str, Dict[str, Any]]:
@@ -356,6 +376,8 @@ app.add_middleware(
356
  allow_headers=["*"]
357
  )
358
 
 
 
359
  # A registry of hash -> filename for each "database" category
360
  FILE_REGISTRY = {}
361
 
@@ -669,6 +691,169 @@ def get_model_provider(model: str) -> Optional[str]:
669
  return "gemini"
670
  return None
671
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
672
  MODEL_ADVANCED_PARAMETERS: Dict[str, Dict[str, Any]] = {
673
  "gpt-5-nano": {
674
  "reasoning_effort": {"choices": ["minimal", "low", "medium", "high"]},
@@ -700,7 +885,38 @@ MODEL_ADVANCED_PARAMETERS: Dict[str, Dict[str, Any]] = {
700
 
701
 
702
  def get_model_advanced_parameter_rules(model: str) -> Dict[str, Any]:
703
- return MODEL_ADVANCED_PARAMETERS.get(model, {})
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
704
 
705
 
706
  def parse_optional_float(value: Optional[str], field_name: str) -> Tuple[Optional[float], Optional[str]]:
@@ -781,10 +997,15 @@ async def set_api_key(
781
  status_code=400
782
  )
783
  api_key = api_key_input.strip()
784
- model_provider = get_model_provider(model)
785
  if not model_provider:
786
  return JSONResponse(
787
- content={"message": f"Invalid proprietary model: {model}"},
 
 
 
 
 
788
  status_code=400
789
  )
790
  model_advanced_rules = get_model_advanced_parameter_rules(model)
@@ -925,9 +1146,11 @@ async def set_api_key(
925
  content={"message": "Gemini models require langchain-google-genai. Please install it to continue."},
926
  status_code=500
927
  )
 
 
928
  embedding_model = GoogleGenerativeAIEmbeddings(
929
  google_api_key=api_key,
930
- model="models/embedding-001"
931
  )
932
  embedding_model = ensure_async_embeddings(embedding_model)
933
  gemini_common_kwargs: Dict[str, Any] = {
@@ -958,9 +1181,34 @@ async def set_api_key(
958
  **gemini_chart_kwargs
959
  )
960
  provider_label = "Gemini"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
961
  else:
962
  return JSONResponse(
963
- content={"message": f"Unsupported model provider for {model}."},
964
  status_code=400
965
  )
966
 
@@ -980,6 +1228,42 @@ async def get_available_models():
980
  "models": AVAILABLE_MODELS
981
  })
982
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
983
  # -------------------- Upload -------------------- #
984
  async def save_file(file: UploadFile, database: str) -> Tuple[str, str]:
985
  """
@@ -3131,4 +3415,4 @@ if __name__ == "__main__":
3131
 
3132
  print("Starting server...")
3133
 
3134
- uvicorn.run(app, host="127.0.0.1", port=8000)
 
18
  from fastapi import FastAPI, UploadFile, File, Form, BackgroundTasks
19
  from fastapi.responses import JSONResponse, FileResponse
20
  from fastapi.middleware.cors import CORSMiddleware
21
+ from starlette.middleware.wsgi import WSGIMiddleware
22
  from zipfile import ZipFile
23
 
24
  # Setup logging
 
44
  ChatGoogleGenerativeAI = None
45
  GoogleGenerativeAIEmbeddings = None
46
 
47
+ import requests as _requests
48
+
49
+ # 1c) Imports for Anthropic (Claude)
50
+ try:
51
+ from langchain_anthropic import ChatAnthropic
52
+ except ImportError:
53
+ ChatAnthropic = None
54
+
55
+ try:
56
+ import anthropic as anthropic_sdk
57
+ except ImportError:
58
+ anthropic_sdk = None
59
+
60
+ try:
61
+ from openai import OpenAI as OpenAIClient
62
+ except ImportError:
63
+ OpenAIClient = None
64
+
65
  from pdf_text_processing import (
66
  extract_text_from_pdf,
67
  extract_and_split,
 
74
  from hypotheses_service import HypothesesService
75
  from prompts import create_hypotheses_generation_prompt
76
  from conversation_storage import save_conversation, get_conversations, update_conversation
77
+ from plotextract.app import app as plotextract_app
78
 
79
  # Metadata management functions
80
  def load_metadata(database: str) -> Dict[str, Dict[str, Any]]:
 
376
  allow_headers=["*"]
377
  )
378
 
379
+ app.mount("/plotextract", WSGIMiddleware(plotextract_app))
380
+
381
  # A registry of hash -> filename for each "database" category
382
  FILE_REGISTRY = {}
383
 
 
691
  return "gemini"
692
  return None
693
 
694
+
695
+ def detect_provider_from_key(api_key: str) -> Optional[str]:
696
+ """Infer provider from an API key prefix.
697
+
698
+ sk-ant-... → Anthropic, AIza... → Gemini, sk-... → OpenAI.
699
+ """
700
+ key = (api_key or "").strip()
701
+ if not key:
702
+ return None
703
+ if key.startswith("sk-ant-"):
704
+ return "anthropic"
705
+ if key.startswith("AIza"):
706
+ return "gemini"
707
+ if key.startswith("sk-"):
708
+ return "openai"
709
+ return None
710
+
711
+
712
+ def provider_display_name(provider: str) -> str:
713
+ return {"openai": "OpenAI", "anthropic": "Anthropic", "gemini": "Gemini"}.get(provider, provider or "Unknown")
714
+
715
+
716
+ def list_openai_chat_models(api_key: str) -> List[Dict[str, str]]:
717
+ if OpenAIClient is None:
718
+ raise RuntimeError("openai SDK is not installed.")
719
+ client = OpenAIClient(api_key=api_key)
720
+ page = client.models.list()
721
+ out: List[Dict[str, str]] = []
722
+ seen = set()
723
+ for item in getattr(page, "data", []) or []:
724
+ model_id = getattr(item, "id", None) or (item.get("id") if isinstance(item, dict) else None)
725
+ if not model_id or model_id in seen:
726
+ continue
727
+ if "gpt" not in model_id.lower():
728
+ continue
729
+ seen.add(model_id)
730
+ out.append({"id": model_id, "display_name": model_id})
731
+ return out
732
+
733
+
734
+ def list_anthropic_models(api_key: str) -> List[Dict[str, str]]:
735
+ if anthropic_sdk is None:
736
+ raise RuntimeError("anthropic SDK is not installed.")
737
+ client = anthropic_sdk.Anthropic(api_key=api_key)
738
+ page = client.models.list(limit=1000)
739
+ out: List[Dict[str, str]] = []
740
+ seen = set()
741
+ for item in getattr(page, "data", []) or []:
742
+ model_id = getattr(item, "id", None) or (item.get("id") if isinstance(item, dict) else None)
743
+ if not model_id or model_id in seen:
744
+ continue
745
+ seen.add(model_id)
746
+ display = getattr(item, "display_name", None) or model_id
747
+ out.append({"id": model_id, "display_name": str(display)})
748
+ return out
749
+
750
+
751
+ def _fetch_gemini_model_list(api_key: str) -> List[Dict[str, Any]]:
752
+ url = "https://generativelanguage.googleapis.com/v1beta/models"
753
+ response = _requests.get(url, params={"key": api_key}, timeout=15)
754
+ if response.status_code != 200:
755
+ try:
756
+ err = response.json().get("error", {}).get("message") or response.text
757
+ except Exception:
758
+ err = response.text
759
+ raise RuntimeError(f"Gemini API returned {response.status_code}: {err}")
760
+ payload = response.json() or {}
761
+ return payload.get("models", []) or []
762
+
763
+
764
+ def list_gemini_models(api_key: str) -> List[Dict[str, str]]:
765
+ """List Gemini chat models via the public REST API to avoid pinning conflicts
766
+ between google-generativeai and langchain-google-genai.
767
+ """
768
+ out: List[Dict[str, str]] = []
769
+ seen = set()
770
+ for item in _fetch_gemini_model_list(api_key):
771
+ methods = item.get("supportedGenerationMethods") or []
772
+ if "generateContent" not in methods:
773
+ continue
774
+ raw_id = item.get("name", "")
775
+ model_id = raw_id.split("/", 1)[-1] if raw_id else ""
776
+ if not model_id or model_id in seen:
777
+ continue
778
+ seen.add(model_id)
779
+ display = item.get("displayName") or model_id
780
+ out.append({"id": model_id, "display_name": str(display)})
781
+ return out
782
+
783
+
784
+ def pick_gemini_embedding_model(api_key: str) -> str:
785
+ """Find a Gemini embedding model this key actually has access to.
786
+
787
+ The v1beta endpoint exposes different embedding models depending on the key's
788
+ tier and rollout — `embedding-001` and `text-embedding-004` are sometimes 404.
789
+ We list models, filter to those supporting `embedContent`, and pick the
790
+ newest one we recognise.
791
+ """
792
+ try:
793
+ embedding_models: List[str] = []
794
+ for item in _fetch_gemini_model_list(api_key):
795
+ methods = item.get("supportedGenerationMethods") or []
796
+ if "embedContent" not in methods:
797
+ continue
798
+ name = item.get("name") or ""
799
+ if name:
800
+ embedding_models.append(name)
801
+ for preferred_prefix in (
802
+ "models/gemini-embedding",
803
+ "models/text-embedding",
804
+ "models/embedding",
805
+ ):
806
+ for name in embedding_models:
807
+ if name.startswith(preferred_prefix):
808
+ return name
809
+ if embedding_models:
810
+ return embedding_models[0]
811
+ except Exception as exc:
812
+ logger.warning(f"Failed to pick Gemini embedding model dynamically, falling back: {exc}")
813
+ return "models/gemini-embedding-001"
814
+
815
+
816
+ def fetch_models_for_provider(provider: str, api_key: str) -> List[Dict[str, str]]:
817
+ if provider == "openai":
818
+ return list_openai_chat_models(api_key)
819
+ if provider == "anthropic":
820
+ return list_anthropic_models(api_key)
821
+ if provider == "gemini":
822
+ return list_gemini_models(api_key)
823
+ return []
824
+
825
+
826
+ def _date_key(text: str) -> int:
827
+ value = (text or "").lower()
828
+ compact = re.search(r"(20\d{2})(\d{2})(\d{2})", value)
829
+ if compact:
830
+ return int("".join(compact.groups()))
831
+ dashed = re.search(r"(20\d{2})[-_](\d{2})[-_](\d{2})", value)
832
+ if dashed:
833
+ return int("".join(dashed.groups()))
834
+ return -1
835
+
836
+
837
+ def choose_default_model(models: List[Dict[str, str]], provider: str) -> str:
838
+ if not models:
839
+ return ""
840
+ def priority(m):
841
+ mid = (m.get("id") or "").lower()
842
+ return (1 if "latest" in mid else 0, _date_key(mid), mid)
843
+ if provider == "anthropic":
844
+ sonnets = [m for m in models if "sonnet" in (m.get("id") or "").lower()]
845
+ if sonnets:
846
+ return max(sonnets, key=priority)["id"]
847
+ if provider == "openai":
848
+ gpt5 = [m for m in models if "gpt-5" in (m.get("id") or "").lower()]
849
+ if gpt5:
850
+ return max(gpt5, key=priority)["id"]
851
+ if provider == "gemini":
852
+ pros = [m for m in models if "pro" in (m.get("id") or "").lower()]
853
+ if pros:
854
+ return max(pros, key=priority)["id"]
855
+ return max(models, key=priority)["id"]
856
+
857
  MODEL_ADVANCED_PARAMETERS: Dict[str, Dict[str, Any]] = {
858
  "gpt-5-nano": {
859
  "reasoning_effort": {"choices": ["minimal", "low", "medium", "high"]},
 
885
 
886
 
887
  def get_model_advanced_parameter_rules(model: str) -> Dict[str, Any]:
888
+ if model in MODEL_ADVANCED_PARAMETERS:
889
+ return MODEL_ADVANCED_PARAMETERS[model]
890
+ # Pattern fallback so models fetched live from a provider's API still
891
+ # surface a sensible advanced-params UI.
892
+ m = (model or "").lower()
893
+ if "gpt-5" in m:
894
+ return {
895
+ "reasoning_effort": {"choices": ["minimal", "low", "medium", "high"]},
896
+ "verbosity": {"choices": ["low", "medium", "high"]},
897
+ }
898
+ if "gpt" in m:
899
+ return {
900
+ "temperature": {"min": 0.0, "max": 2.0},
901
+ "top_p": {"min": 0.0, "max": 1.0},
902
+ }
903
+ if "gemini" in m and "pro" in m:
904
+ return {
905
+ "temperature": {"min": 0.0, "max": 2.0},
906
+ "top_p": {"min": 0.0, "max": 1.0},
907
+ "thinking_level": {"choices": ["low", "high"]},
908
+ }
909
+ if "gemini" in m:
910
+ return {
911
+ "temperature": {"min": 0.0, "max": 2.0},
912
+ "top_p": {"min": 0.0, "max": 1.0},
913
+ }
914
+ if "claude" in m:
915
+ return {
916
+ "temperature": {"min": 0.0, "max": 1.0},
917
+ "top_p": {"min": 0.0, "max": 1.0},
918
+ }
919
+ return {}
920
 
921
 
922
  def parse_optional_float(value: Optional[str], field_name: str) -> Tuple[Optional[float], Optional[str]]:
 
997
  status_code=400
998
  )
999
  api_key = api_key_input.strip()
1000
+ model_provider = detect_provider_from_key(api_key)
1001
  if not model_provider:
1002
  return JSONResponse(
1003
+ content={"message": "Unsupported API key format. Use an OpenAI (sk-...), Anthropic (sk-ant-...), or Gemini (AIza...) key."},
1004
+ status_code=400
1005
+ )
1006
+ if not model:
1007
+ return JSONResponse(
1008
+ content={"message": "Please select a model."},
1009
  status_code=400
1010
  )
1011
  model_advanced_rules = get_model_advanced_parameter_rules(model)
 
1146
  content={"message": "Gemini models require langchain-google-genai. Please install it to continue."},
1147
  status_code=500
1148
  )
1149
+ gemini_embedding_model_name = pick_gemini_embedding_model(api_key)
1150
+ logger.info(f"Using Gemini embedding model: {gemini_embedding_model_name}")
1151
  embedding_model = GoogleGenerativeAIEmbeddings(
1152
  google_api_key=api_key,
1153
+ model=gemini_embedding_model_name
1154
  )
1155
  embedding_model = ensure_async_embeddings(embedding_model)
1156
  gemini_common_kwargs: Dict[str, Any] = {
 
1181
  **gemini_chart_kwargs
1182
  )
1183
  provider_label = "Gemini"
1184
+ elif model_provider == "anthropic":
1185
+ if ChatAnthropic is None:
1186
+ return JSONResponse(
1187
+ content={"message": "Anthropic models require langchain-anthropic. Please install it to continue."},
1188
+ status_code=500
1189
+ )
1190
+ # No native Anthropic embedding model — QA retrieval requires OpenAI or Gemini.
1191
+ embedding_model = None
1192
+ anthropic_common_kwargs: Dict[str, Any] = {
1193
+ "anthropic_api_key": api_key,
1194
+ "model": DEFAULT_MODEL_QA,
1195
+ }
1196
+ anthropic_chart_kwargs: Dict[str, Any] = {
1197
+ "anthropic_api_key": api_key,
1198
+ "model": DEFAULT_MODEL_SYSTEM_CHART_EXTRACTION,
1199
+ }
1200
+ if "temperature" in llm_config:
1201
+ anthropic_common_kwargs["temperature"] = llm_config["temperature"]
1202
+ anthropic_chart_kwargs["temperature"] = llm_config["temperature"]
1203
+ if "top_p" in llm_config:
1204
+ anthropic_common_kwargs["top_p"] = llm_config["top_p"]
1205
+ anthropic_chart_kwargs["top_p"] = llm_config["top_p"]
1206
+ llm_QA = ChatAnthropic(**anthropic_common_kwargs)
1207
+ llm_system_chart_extraction = ChatAnthropic(**anthropic_chart_kwargs)
1208
+ provider_label = "Anthropic"
1209
  else:
1210
  return JSONResponse(
1211
+ content={"message": f"Unsupported provider: {model_provider}."},
1212
  status_code=400
1213
  )
1214
 
 
1228
  "models": AVAILABLE_MODELS
1229
  })
1230
 
1231
+
1232
+ @app.post("/list_models")
1233
+ async def list_models_for_key(api_key_input: Optional[str] = Form(None)):
1234
+ """Return the models available for the provider that the supplied API key belongs to.
1235
+
1236
+ Provider is inferred from the key prefix; the dropdown only ever shows models
1237
+ matching the detected provider.
1238
+ """
1239
+ key = (api_key_input or "").strip()
1240
+ if not key:
1241
+ return JSONResponse({"message": "API key is required."}, status_code=400)
1242
+ provider = detect_provider_from_key(key)
1243
+ if not provider:
1244
+ return JSONResponse(
1245
+ {"message": "Unsupported API key format. Use an OpenAI (sk-...), Anthropic (sk-ant-...), or Gemini (AIza...) key."},
1246
+ status_code=400,
1247
+ )
1248
+ try:
1249
+ models = fetch_models_for_provider(provider, key)
1250
+ except Exception as exc:
1251
+ return JSONResponse(
1252
+ {"message": f"Failed to fetch models from {provider_display_name(provider)}.", "details": str(exc)},
1253
+ status_code=400,
1254
+ )
1255
+ if not models:
1256
+ return JSONResponse(
1257
+ {"message": f"No models available for this {provider_display_name(provider)} key."},
1258
+ status_code=400,
1259
+ )
1260
+ return JSONResponse({
1261
+ "provider": provider,
1262
+ "provider_label": provider_display_name(provider),
1263
+ "models": models,
1264
+ "default_model": choose_default_model(models, provider),
1265
+ })
1266
+
1267
  # -------------------- Upload -------------------- #
1268
  async def save_file(file: UploadFile, database: str) -> Tuple[str, str]:
1269
  """
 
3415
 
3416
  print("Starting server...")
3417
 
3418
+ uvicorn.run(app, host="127.0.0.1", port=8000)
plotextract/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+
plotextract/app.py ADDED
@@ -0,0 +1,880 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import base64
2
+ import json
3
+ import os
4
+ import re
5
+ import shutil
6
+ import threading
7
+ import traceback
8
+ import zipfile
9
+ from datetime import datetime, timezone
10
+ from uuid import uuid4
11
+
12
+ from flask import Flask, jsonify, render_template, request, send_from_directory
13
+ from PIL import Image, ImageOps
14
+ import anthropic
15
+ try:
16
+ from openai import OpenAI
17
+ except Exception:
18
+ OpenAI = None
19
+
20
+ APP_ROOT = os.path.dirname(os.path.abspath(__file__))
21
+ OUTPUT_DIR = os.path.join(APP_ROOT, "outputs")
22
+
23
+ app = Flask(__name__, static_folder="static", template_folder="templates")
24
+
25
+ PROMPTS = {
26
+ "extract": """The image depicts a figure from a research paper. Please carefully analyze the figure and extract the horizontal (\"x\") and vertical (\"y\") coordinates of each individual data point from each curve. Pay extremely close attention to the axes:
27
+ - Identify the tick marks and labels on both axes, and use them to determine the numeric values for every point.
28
+ - Read the labels of both axes (the text or symbols denoting what each axis represents).
29
+
30
+ Data Reporting Requirements:
31
+ 1. Separate each curve's data so that every curve has its own two columns of x and y.
32
+ 2. The first row of your output must contain the axis labels (for example, \"x-axis label\" for the x-column and \"y-axis label (Curve X)\" for the y-column). Include the curve label in the y-axis header if it's available.
33
+ 3. Subsequent rows must present the extracted numeric data in comma-separated values (CSV) format, with:
34
+ - No additional words or commentary.
35
+ - Exactly one row per data point in each curve.
36
+ - For multiple curves, produce additional pairs of columns (two columns per curve: one for x-values, one for y-values).
37
+ 4. If, for any reason, you are unable to extract the data, respond with only the word \"None\".
38
+ 5. Make sure that both axis are labeled and there are individual values assigned to each tickmark, and that they increase in a logical monotonius fashion. If they are not it may be impossible to extract the data. In that case respond with only the word \"None\".
39
+
40
+ Key Instructions:
41
+ - Look at each point individually; do not assume a pattern or formula. Each data point must be read precisely from its plotted location.
42
+ - Verify the numerical axis labels carefully so the extracted data is as accurate as possible.
43
+ - Do not include any explanations or text other than the required CSV table.
44
+
45
+ Output Format Example (if you have two curves):
46
+ x-axis label,y-axis label (Curve 1),x-axis label,y-axis label (Curve 2)
47
+ 0.1,0.5,0.1,0.75
48
+ 0.2,0.52,0.2,0.77
49
+ ...
50
+
51
+ (Or \"None\" if you cannot extract the data.)
52
+
53
+ Remember: The sole output should be either the CSV table (with all columns for the curves) or \"None\". Nothing else.
54
+ """,
55
+ "code_fix": "The text above is an error produced by your code, please fix the code so that this error does not appear. Use only matplotlib and numpy (plus the Python standard library). Repeat the whole code and only the code so that your whole response can be directly copied and executed. Do not explain and do not say anything else, respond with just the code. Do not output the markdown code fence.",
56
+ "compare_x": "You are provided with two images of research plots extracted from academic papers. Do these two plots have the same x-axis (horizontal)? Do they have the same ranges, labels, etc.? Answer with a single word, \"yes\" or \"no\" only.",
57
+ "compare_y": "You are provided with two images of research plots extracted from academic papers. Do these two plots have the same y-axis (vertical)? Do they have the same ranges, labels, etc.? Answer with a single word, \"yes\" or \"no\" only.",
58
+ "compare_number": "You are provided with two images of research plots extracted from academic papers. Do these two plots have the same number of points (for point plots)? Do the curves look like they connect the same amount of pointis (for line plots)?. Answer with a single word, \"yes\" or \"no\" only.",
59
+ "compare_trend": "You are provided with two images of research plots extracted from academic papers. Do these sets of points or curves on these two plots represent the same trends? Do they follow the same patterns? Are points distributed in the same way? Answer with a single word, \"yes\" or \"no\" only.",
60
+ }
61
+
62
+
63
+ def detect_provider(api_key):
64
+ key = (api_key or "").strip()
65
+ if key.startswith("sk-ant-"):
66
+ return "anthropic"
67
+ if key.startswith("sk-"):
68
+ return "openai"
69
+ return ""
70
+
71
+
72
+ def init_provider_client(api_key, provider):
73
+ if provider == "anthropic":
74
+ return anthropic.Anthropic(api_key=api_key)
75
+ if provider == "openai":
76
+ if OpenAI is None:
77
+ raise RuntimeError("OpenAI SDK is not installed on the server.")
78
+ return OpenAI(api_key=api_key)
79
+ raise ValueError("Unsupported API key format. Use an Anthropic or OpenAI API key.")
80
+
81
+
82
+ def provider_label(provider):
83
+ if provider == "anthropic":
84
+ return "Anthropic"
85
+ if provider == "openai":
86
+ return "OpenAI"
87
+ return "Unknown"
88
+
89
+
90
+ def app_path(path):
91
+ prefix = (request.script_root or "").rstrip("/")
92
+ return f"{prefix}{path}"
93
+
94
+
95
+ @app.route("/")
96
+ def index():
97
+ return render_template("index.html")
98
+
99
+
100
+ @app.route("/outputs/<path:filename>")
101
+ def outputs(filename):
102
+ return send_from_directory(OUTPUT_DIR, filename)
103
+
104
+
105
+ @app.route("/api/run", methods=["POST"])
106
+ def run_extraction():
107
+ api_key = (request.form.get("api_key") or "").strip()
108
+ model = (request.form.get("model") or "").strip()
109
+ image_file = request.files.get("image")
110
+ provider = detect_provider(api_key)
111
+
112
+ if not api_key:
113
+ return jsonify({"error": "Missing API key."}), 400
114
+ if not provider:
115
+ return jsonify({"error": "Unsupported API key format. Use an Anthropic or OpenAI API key."}), 400
116
+ if not image_file:
117
+ return jsonify({"error": "Missing image upload."}), 400
118
+
119
+ run_id = uuid4().hex[:10]
120
+ run_dir = os.path.join(OUTPUT_DIR, run_id)
121
+ os.makedirs(run_dir, exist_ok=True)
122
+
123
+ ext = os.path.splitext(image_file.filename)[-1].lower()
124
+ if ext not in [".png", ".jpg", ".jpeg", ".zip"]:
125
+ return jsonify({"error": "Please upload a PNG, JPG, or ZIP file."}), 400
126
+
127
+ try:
128
+ client = init_provider_client(api_key, provider)
129
+ except Exception as exc:
130
+ return jsonify({
131
+ "error": f"Failed to initialize {provider_label(provider)} client. Check your API key.",
132
+ "details": str(exc),
133
+ }), 400
134
+
135
+ if not model:
136
+ try:
137
+ models = fetch_all_models(client, provider)
138
+ model = choose_default_model(models, provider)
139
+ except Exception as exc:
140
+ return jsonify({
141
+ "error": f"Failed to fetch available models from {provider_label(provider)}.",
142
+ "details": str(exc),
143
+ }), 500
144
+ if not model:
145
+ return jsonify({"error": "No available models found for this API key."}), 400
146
+
147
+ try:
148
+ if ext == ".zip":
149
+ zip_path = os.path.join(run_dir, "input.zip")
150
+ image_file.save(zip_path)
151
+ result = prepare_zip_run(zip_path, run_dir, run_id)
152
+ if "error" in result:
153
+ return jsonify({"error": result["error"]}), 400
154
+ result["base_path"] = request.script_root or ""
155
+ start_zip_worker(api_key, provider, model, result)
156
+ return jsonify({
157
+ "run_id": run_id,
158
+ "status": "zip_pending",
159
+ "progress_url": app_path(f"/api/progress/{run_id}"),
160
+ "results_zip_url": app_path(f"/outputs/{run_id}/results.zip"),
161
+ })
162
+
163
+ input_name = f"input{ext if ext != '.jpeg' else '.jpg'}"
164
+ input_path = os.path.join(run_dir, input_name)
165
+ image_file.save(input_path)
166
+
167
+ result = process_single_image(client, provider, model, input_path, run_dir)
168
+ if result["status"] == "none":
169
+ return jsonify({
170
+ "run_id": run_id,
171
+ "data_csv": result.get("data_csv", "None"),
172
+ "status": "none",
173
+ "input_url": app_path(f"/outputs/{run_id}/{input_name}"),
174
+ })
175
+ if result["status"] == "error":
176
+ return jsonify({
177
+ "error": "Replot code failed after retries.",
178
+ "details": result.get("details", ""),
179
+ "data_csv": result.get("data_csv", ""),
180
+ "run_id": run_id,
181
+ }), 500
182
+
183
+ return jsonify({
184
+ "run_id": run_id,
185
+ "status": "ok",
186
+ "data_csv": result["data_csv"],
187
+ "code": result["code"],
188
+ "validation": result["validation"],
189
+ "validated": result["validated"],
190
+ "input_url": app_path(f"/outputs/{run_id}/{input_name}"),
191
+ "replot_url": app_path(f"/outputs/{run_id}/replot.png"),
192
+ "stacked_url": app_path(f"/outputs/{run_id}/stacked.png"),
193
+ "comparison_url": app_path(f"/outputs/{run_id}/comparison.png"),
194
+ })
195
+ except Exception as exc:
196
+ return jsonify({
197
+ "error": "Unexpected error.",
198
+ "details": str(exc),
199
+ "trace": traceback.format_exc(),
200
+ }), 500
201
+
202
+
203
+ @app.route("/api/progress/<run_id>")
204
+ def progress(run_id):
205
+ progress_path = os.path.join(OUTPUT_DIR, run_id, "progress.json")
206
+ if not os.path.exists(progress_path):
207
+ return jsonify({"error": "Progress not found."}), 404
208
+ try:
209
+ with open(progress_path, "r", encoding="utf-8") as handle:
210
+ return jsonify(json.loads(handle.read()))
211
+ except Exception:
212
+ return jsonify({"error": "Failed to read progress."}), 500
213
+
214
+
215
+ @app.route("/api/models", methods=["POST"])
216
+ def list_models():
217
+ payload = request.get_json(silent=True) or {}
218
+ api_key = (payload.get("api_key") or request.form.get("api_key") or "").strip()
219
+ provider = detect_provider(api_key)
220
+
221
+ if not api_key:
222
+ return jsonify({"error": "Missing API key."}), 400
223
+ if not provider:
224
+ return jsonify({"error": "Unsupported API key format. Use an Anthropic or OpenAI API key."}), 400
225
+
226
+ try:
227
+ client = init_provider_client(api_key, provider)
228
+ except Exception as exc:
229
+ return jsonify({
230
+ "error": f"Failed to initialize {provider_label(provider)} client. Check your API key.",
231
+ "details": str(exc),
232
+ }), 400
233
+
234
+ try:
235
+ models = fetch_all_models(client, provider)
236
+ return jsonify({
237
+ "models": models,
238
+ "default_model": choose_default_model(models, provider),
239
+ "provider": provider,
240
+ })
241
+ except Exception as exc:
242
+ return jsonify({
243
+ "error": f"Failed to fetch models from {provider_label(provider)}.",
244
+ "details": str(exc),
245
+ }), 500
246
+
247
+
248
+ def encode_image(image_path):
249
+ with open(image_path, "rb") as image_file:
250
+ return base64.b64encode(image_file.read()).decode("utf-8")
251
+
252
+
253
+ def parse_model_list_response(items):
254
+ models = []
255
+ seen = set()
256
+ for item in items or []:
257
+ if isinstance(item, dict):
258
+ model_id = item.get("id")
259
+ display_name = item.get("display_name") or item.get("name")
260
+ created_at = item.get("created_at") or item.get("created")
261
+ else:
262
+ model_id = getattr(item, "id", None)
263
+ display_name = getattr(item, "display_name", None) or getattr(item, "name", None)
264
+ created_at = getattr(item, "created_at", None) or getattr(item, "created", None)
265
+
266
+ if not model_id or model_id in seen:
267
+ continue
268
+ seen.add(model_id)
269
+
270
+ created_text = ""
271
+ if created_at is not None:
272
+ if isinstance(created_at, (int, float)):
273
+ try:
274
+ created_text = datetime.fromtimestamp(created_at, tz=timezone.utc).isoformat()
275
+ except Exception:
276
+ created_text = str(created_at)
277
+ elif hasattr(created_at, "isoformat"):
278
+ created_text = created_at.isoformat()
279
+ else:
280
+ created_text = str(created_at)
281
+
282
+ models.append({
283
+ "id": str(model_id),
284
+ "display_name": str(display_name or model_id),
285
+ "created_at": created_text,
286
+ })
287
+ return models
288
+
289
+
290
+ def fetch_all_anthropic_models(client):
291
+ page = client.models.list(limit=1000)
292
+ collected = []
293
+
294
+ while True:
295
+ page_data = getattr(page, "data", None) or []
296
+ collected.extend(page_data)
297
+ if hasattr(page, "has_next_page") and page.has_next_page():
298
+ page = page.get_next_page()
299
+ continue
300
+ break
301
+
302
+ return parse_model_list_response(collected)
303
+
304
+
305
+ def fetch_all_openai_models(client):
306
+ page = client.models.list()
307
+ collected = []
308
+
309
+ while True:
310
+ page_data = getattr(page, "data", None) or []
311
+ collected.extend(page_data)
312
+ if hasattr(page, "has_next_page") and page.has_next_page():
313
+ page = page.get_next_page()
314
+ continue
315
+ break
316
+
317
+ models = parse_model_list_response(collected)
318
+ return [model for model in models if "gpt" in (model.get("id") or "").lower()]
319
+
320
+
321
+ def fetch_all_models(client, provider):
322
+ if provider == "anthropic":
323
+ return fetch_all_anthropic_models(client)
324
+ if provider == "openai":
325
+ return fetch_all_openai_models(client)
326
+ return []
327
+
328
+
329
+ def extract_date_key(text):
330
+ value = (text or "").lower()
331
+ compact = re.search(r"(20\d{2})(\d{2})(\d{2})", value)
332
+ if compact:
333
+ return int("".join(compact.groups()))
334
+ dashed = re.search(r"(20\d{2})[-_](\d{2})[-_](\d{2})", value)
335
+ if dashed:
336
+ return int("".join(dashed.groups()))
337
+ return -1
338
+
339
+
340
+ def model_priority(model):
341
+ model_id = (model.get("id") or "").lower()
342
+ is_latest_alias = 1 if "latest" in model_id else 0
343
+ date_key = max(extract_date_key(model_id), extract_date_key(model.get("created_at") or ""))
344
+ created_key = model.get("created_at") or ""
345
+ return (is_latest_alias, date_key, created_key, model_id)
346
+
347
+
348
+ def choose_default_model(models, provider):
349
+ if provider == "anthropic":
350
+ sonnets = [model for model in models if "sonnet" in (model.get("id") or "").lower()]
351
+ if sonnets:
352
+ return max(sonnets, key=model_priority)["id"]
353
+ if provider == "openai":
354
+ gpt_models = [model for model in models if "gpt" in (model.get("id") or "").lower()]
355
+ if gpt_models:
356
+ return max(gpt_models, key=model_priority)["id"]
357
+ if models:
358
+ return max(models, key=model_priority)["id"]
359
+ return ""
360
+
361
+
362
+ def media_type_for_path(image_path):
363
+ ext = os.path.splitext(image_path)[-1].lower()
364
+ if ext in [".jpg", ".jpeg"]:
365
+ return "image/jpeg"
366
+ return "image/png"
367
+
368
+
369
+ def write_progress(run_dir, data):
370
+ progress_path = os.path.join(run_dir, "progress.json")
371
+ try:
372
+ with open(progress_path, "w", encoding="utf-8") as handle:
373
+ handle.write(json.dumps(data))
374
+ except Exception:
375
+ pass
376
+
377
+
378
+ def process_single_image(client, provider, model, input_path, output_dir):
379
+ os.makedirs(output_dir, exist_ok=True)
380
+ replot_path = os.path.join(output_dir, "replot.png")
381
+ stacked_path = os.path.join(output_dir, "stacked.png")
382
+ comparison_path = os.path.join(output_dir, "comparison.png")
383
+ data_path = os.path.join(output_dir, "data.csv")
384
+ code_path = os.path.join(output_dir, "replot_code.py")
385
+ validation_path = os.path.join(output_dir, "validation.json")
386
+
387
+ base64_image = encode_image(input_path)
388
+ context, data_csv = prompt_extract(client, provider, model, base64_image, media_type_for_path(input_path))
389
+
390
+ if not data_csv or "none" in data_csv.strip().lower():
391
+ try:
392
+ with open(data_path, "w", encoding="utf-8") as handle:
393
+ handle.write(data_csv.strip() if data_csv else "None")
394
+ except Exception:
395
+ pass
396
+ return {"status": "none", "data_csv": data_csv.strip() if data_csv else "None"}
397
+
398
+ code, convo = prompt_replot_code(client, provider, model, data_csv, replot_path, context)
399
+ code, error_output = exec_replot_code(client, provider, model, code, replot_path, convo)
400
+
401
+ if error_output:
402
+ error_log = os.path.join(output_dir, "replot_error.txt")
403
+ try:
404
+ with open(error_log, "w", encoding="utf-8") as handle:
405
+ handle.write(error_output)
406
+ except Exception:
407
+ pass
408
+ return {"status": "error", "details": error_output, "data_csv": data_csv}
409
+
410
+ try:
411
+ with open(data_path, "w", encoding="utf-8") as handle:
412
+ handle.write(data_csv)
413
+ with open(code_path, "w", encoding="utf-8") as handle:
414
+ handle.write(code)
415
+ except Exception:
416
+ pass
417
+
418
+ stacked_path = stack_images_vertically(
419
+ input_path,
420
+ replot_path,
421
+ stacked_path,
422
+ border_color=None,
423
+ border_size=0,
424
+ )
425
+ validation = run_comparisons(client, provider, model, stacked_path)
426
+ validated = "yes" if not validation["wrong"] else "no"
427
+
428
+ comparison_path = stack_images_vertically(
429
+ input_path,
430
+ replot_path,
431
+ comparison_path,
432
+ border_color=validated,
433
+ border_size=24,
434
+ )
435
+
436
+ try:
437
+ with open(validation_path, "w", encoding="utf-8") as handle:
438
+ handle.write(json.dumps(validation, indent=2))
439
+ except Exception:
440
+ pass
441
+
442
+ return {
443
+ "status": "ok",
444
+ "data_csv": data_csv,
445
+ "code": code,
446
+ "validation": validation,
447
+ "validated": validated,
448
+ }
449
+
450
+
451
+ def prepare_zip_run(zip_path, run_dir, run_id):
452
+ extract_dir = os.path.join(run_dir, "zip_in")
453
+ results_dir = os.path.join(run_dir, "results")
454
+ os.makedirs(extract_dir, exist_ok=True)
455
+ os.makedirs(results_dir, exist_ok=True)
456
+
457
+ extract_zip_safe(zip_path, extract_dir)
458
+
459
+ image_paths = []
460
+ for root, _, files in os.walk(extract_dir):
461
+ for name in files:
462
+ lower = name.lower()
463
+ if lower.endswith((".png", ".jpg", ".jpeg")):
464
+ image_paths.append(os.path.join(root, name))
465
+
466
+ image_paths.sort()
467
+ if not image_paths:
468
+ return {"error": "No PNG or JPG files found in the ZIP."}
469
+
470
+ used_names = set()
471
+ jobs = []
472
+ for idx, image_path in enumerate(image_paths, 1):
473
+ base = os.path.splitext(os.path.basename(image_path))[0]
474
+ safe_base = "".join(ch if ch.isalnum() else "_" for ch in base).strip("_") or f"image_{idx}"
475
+ name = safe_base
476
+ suffix = 1
477
+ while name in used_names:
478
+ suffix += 1
479
+ name = f"{safe_base}_{suffix}"
480
+ used_names.add(name)
481
+
482
+ item_dir = os.path.join(results_dir, name)
483
+ os.makedirs(item_dir, exist_ok=True)
484
+ ext = os.path.splitext(image_path)[-1].lower()
485
+ input_name = f"input{ext if ext != '.jpeg' else '.jpg'}"
486
+ input_path = os.path.join(item_dir, input_name)
487
+ shutil.copy(image_path, input_path)
488
+
489
+ jobs.append({
490
+ "name": name,
491
+ "input_path": input_path,
492
+ "item_dir": item_dir,
493
+ })
494
+
495
+ write_progress(run_dir, {
496
+ "status": "running",
497
+ "total": len(jobs),
498
+ "processed": 0,
499
+ "current": "",
500
+ "items": [],
501
+ })
502
+
503
+ return {
504
+ "run_id": run_id,
505
+ "run_dir": run_dir,
506
+ "results_dir": results_dir,
507
+ "jobs": jobs,
508
+ }
509
+
510
+ def start_zip_worker(api_key, provider, model, payload):
511
+ thread = threading.Thread(
512
+ target=process_zip_async,
513
+ args=(api_key, provider, model, payload),
514
+ daemon=True,
515
+ )
516
+ thread.start()
517
+
518
+
519
+ def process_zip_async(api_key, provider, model, payload):
520
+ run_dir = payload["run_dir"]
521
+ results_dir = payload["results_dir"]
522
+ jobs = payload["jobs"]
523
+
524
+ try:
525
+ client = init_provider_client(api_key, provider)
526
+ except Exception as exc:
527
+ write_progress(run_dir, {
528
+ "status": "error",
529
+ "error": f"Failed to initialize {provider_label(provider)} client.",
530
+ "details": str(exc),
531
+ })
532
+ return
533
+
534
+ items = []
535
+ total = len(jobs)
536
+ for idx, job in enumerate(jobs, 1):
537
+ write_progress(run_dir, {
538
+ "status": "running",
539
+ "total": total,
540
+ "processed": idx - 1,
541
+ "current": job["name"],
542
+ "items": items,
543
+ })
544
+ result = process_single_image(client, provider, model, job["input_path"], job["item_dir"])
545
+ items.append({
546
+ "name": job["name"],
547
+ "status": result.get("status"),
548
+ "validated": result.get("validated", ""),
549
+ "wrong_why": result.get("validation", {}).get("wrong_why", "") if result.get("validation") else "",
550
+ })
551
+ write_progress(run_dir, {
552
+ "status": "running",
553
+ "total": total,
554
+ "processed": idx,
555
+ "current": job["name"],
556
+ "items": items,
557
+ })
558
+
559
+ summary_path = os.path.join(results_dir, "summary.json")
560
+ try:
561
+ with open(summary_path, "w", encoding="utf-8") as handle:
562
+ handle.write(json.dumps({"items": items}, indent=2))
563
+ except Exception:
564
+ pass
565
+
566
+ zip_out = os.path.join(run_dir, "results.zip")
567
+ with zipfile.ZipFile(zip_out, "w", compression=zipfile.ZIP_DEFLATED) as zf:
568
+ for root, _, files in os.walk(results_dir):
569
+ for file_name in files:
570
+ full_path = os.path.join(root, file_name)
571
+ rel_path = os.path.relpath(full_path, results_dir)
572
+ zf.write(full_path, arcname=rel_path)
573
+
574
+ write_progress(run_dir, {
575
+ "status": "done",
576
+ "total": total,
577
+ "processed": total,
578
+ "current": "",
579
+ "items": items,
580
+ "results_zip_url": f"{(payload.get('base_path') or '').rstrip('/')}/outputs/{payload['run_id']}/results.zip",
581
+ })
582
+
583
+
584
+ def extract_zip_safe(zip_path, dest_dir):
585
+ with zipfile.ZipFile(zip_path, "r") as zf:
586
+ for member in zf.infolist():
587
+ if member.filename.endswith("/"):
588
+ continue
589
+ extracted_path = os.path.normpath(os.path.join(dest_dir, member.filename))
590
+ if not extracted_path.startswith(os.path.abspath(dest_dir) + os.sep):
591
+ continue
592
+ os.makedirs(os.path.dirname(extracted_path), exist_ok=True)
593
+ with zf.open(member) as source, open(extracted_path, "wb") as target:
594
+ shutil.copyfileobj(source, target)
595
+
596
+
597
+ def extract_openai_text(response):
598
+ if isinstance(response, dict):
599
+ output_text = response.get("output_text")
600
+ if output_text:
601
+ return str(output_text)
602
+ outputs = response.get("output") or []
603
+ else:
604
+ output_text = getattr(response, "output_text", None)
605
+ outputs = getattr(response, "output", None) or []
606
+ if output_text:
607
+ return output_text
608
+
609
+ parts = []
610
+ for item in outputs:
611
+ content = item.get("content") if isinstance(item, dict) else getattr(item, "content", None)
612
+ for block in content or []:
613
+ block_type = block.get("type") if isinstance(block, dict) else getattr(block, "type", None)
614
+ if block_type not in ["output_text", "text"]:
615
+ continue
616
+ text = block.get("text") if isinstance(block, dict) else getattr(block, "text", None)
617
+ if not text and not isinstance(block, dict):
618
+ text = getattr(block, "value", None)
619
+ if text:
620
+ parts.append(str(text))
621
+ return "\n".join(parts).strip()
622
+
623
+
624
+ def prompt_extract(client, provider, model, base64_image, media_type):
625
+ if provider == "anthropic":
626
+ messages = [
627
+ {
628
+ "role": "user",
629
+ "content": [
630
+ {
631
+ "type": "image",
632
+ "source": {
633
+ "type": "base64",
634
+ "media_type": media_type,
635
+ "data": base64_image,
636
+ },
637
+ },
638
+ {"type": "text", "text": PROMPTS["extract"]},
639
+ ],
640
+ }
641
+ ]
642
+ response = client.messages.create(
643
+ model=model,
644
+ max_tokens=2048,
645
+ #temperature=0,
646
+ messages=messages,
647
+ )
648
+ return messages, response.content[0].text
649
+
650
+ image_data_url = f"data:{media_type};base64,{base64_image}"
651
+ messages = [
652
+ {
653
+ "role": "user",
654
+ "content": [
655
+ {"type": "input_image", "image_url": image_data_url},
656
+ {"type": "input_text", "text": PROMPTS["extract"]},
657
+ ],
658
+ }
659
+ ]
660
+ response = client.responses.create(
661
+ model=model,
662
+ input=messages,
663
+ max_output_tokens=2048,
664
+ )
665
+ return messages, extract_openai_text(response)
666
+
667
+
668
+ def prompt_replot_code(client, provider, model, data_csv, replot_path, messages):
669
+ prompt = (
670
+ "Please analyze the figure and create a python code that will reproduce the plot exactly, "
671
+ "including colors, line types, point shapes, axis labels, axis ranges, etc. "
672
+ f"Save the plot as a file \"{replot_path}\" only and do not show it. "
673
+ "Use only matplotlib and numpy (plus the Python standard library). "
674
+ "Respond with the code only so that it can be directly copied and executed, do not output the markdown code fence.\n\n"
675
+ f"Use the following data on the plot: {data_csv}"
676
+ )
677
+ if provider == "anthropic":
678
+ convo = list(messages)
679
+ convo.append({"role": "assistant", "content": data_csv})
680
+ convo.append({"role": "user", "content": prompt})
681
+ response = client.messages.create(
682
+ model=model,
683
+ max_tokens=2048,
684
+ #temperature=0,
685
+ messages=convo,
686
+ )
687
+ return response.content[0].text, convo
688
+
689
+ convo = list(messages)
690
+ convo.append({
691
+ "role": "user",
692
+ "content": [
693
+ {
694
+ "type": "input_text",
695
+ "text": f"Use the following extracted CSV data:\n{data_csv}\n\n{prompt}",
696
+ }
697
+ ],
698
+ })
699
+ response = client.responses.create(
700
+ model=model,
701
+ input=convo,
702
+ max_output_tokens=2048,
703
+ )
704
+ return extract_openai_text(response), convo
705
+
706
+
707
+ def exec_replot_code(client, provider, model, code, replot_path, convo=None):
708
+ error_output = None
709
+
710
+ def strip_code_fences(text):
711
+ if not text:
712
+ return text
713
+ cleaned = text.strip()
714
+ if cleaned.startswith("```"):
715
+ lines = cleaned.splitlines()
716
+ lines = lines[1:]
717
+ if lines and lines[-1].strip().startswith("```"):
718
+ lines = lines[:-1]
719
+ cleaned = "\n".join(lines).strip()
720
+ return cleaned
721
+
722
+ def run_code(script):
723
+ exec_globals = {"__name__": "__main__"}
724
+ try:
725
+ import matplotlib
726
+ matplotlib.use("Agg")
727
+ import matplotlib.pyplot as plt
728
+ plt.show = lambda *args, **kwargs: None
729
+ exec_globals["plt"] = plt
730
+ except Exception:
731
+ pass
732
+ exec(script, exec_globals)
733
+
734
+ try:
735
+ code = strip_code_fences(code)
736
+ run_code(code)
737
+ except Exception:
738
+ error_output = traceback.format_exc()
739
+
740
+ attempts = 0
741
+ while error_output and attempts < 2:
742
+ attempts += 1
743
+ fix_prompt = error_output + "\n\n" + PROMPTS["code_fix"]
744
+ if provider == "anthropic":
745
+ fix_messages = [
746
+ {"role": "assistant", "content": code},
747
+ {"role": "user", "content": fix_prompt},
748
+ ]
749
+ if convo:
750
+ fix_messages = list(convo) + fix_messages
751
+ response = client.messages.create(
752
+ model=model,
753
+ max_tokens=2048,
754
+ #temperature=0,
755
+ messages=fix_messages,
756
+ )
757
+ code = strip_code_fences(response.content[0].text)
758
+ else:
759
+ fix_messages = []
760
+ if convo:
761
+ fix_messages = list(convo) + fix_messages
762
+ fix_messages.append(
763
+ {
764
+ "role": "user",
765
+ "content": [
766
+ {
767
+ "type": "input_text",
768
+ "text": f"Current code:\n{code}\n\nExecution error:\n{fix_prompt}",
769
+ }
770
+ ],
771
+ }
772
+ )
773
+ response = client.responses.create(
774
+ model=model,
775
+ input=fix_messages,
776
+ max_output_tokens=2048,
777
+ )
778
+ code = strip_code_fences(extract_openai_text(response))
779
+ try:
780
+ run_code(code)
781
+ error_output = None
782
+ except Exception:
783
+ error_output = traceback.format_exc()
784
+
785
+ return code, error_output
786
+
787
+
788
+ def run_comparisons(client, provider, model, stacked_path):
789
+ base64_image = encode_image(stacked_path)
790
+ media_type = media_type_for_path(stacked_path)
791
+ results = {}
792
+ wrong = False
793
+ wrong_why = []
794
+
795
+ for key, label in [
796
+ ("compare_x", "X"),
797
+ ("compare_y", "Y"),
798
+ ("compare_number", "N"),
799
+ ("compare_trend", "T"),
800
+ ]:
801
+ if provider == "anthropic":
802
+ response = client.messages.create(
803
+ model=model,
804
+ max_tokens=32,
805
+ #temperature=0,
806
+ messages=[
807
+ {
808
+ "role": "user",
809
+ "content": [
810
+ {
811
+ "type": "image",
812
+ "source": {
813
+ "type": "base64",
814
+ "media_type": media_type,
815
+ "data": base64_image,
816
+ },
817
+ },
818
+ {"type": "text", "text": PROMPTS[key]},
819
+ ],
820
+ }
821
+ ],
822
+ )
823
+ answer = response.content[0].text.strip().lower()
824
+ else:
825
+ image_data_url = f"data:{media_type};base64,{base64_image}"
826
+ response = client.responses.create(
827
+ model=model,
828
+ input=[
829
+ {
830
+ "role": "user",
831
+ "content": [
832
+ {"type": "input_image", "image_url": image_data_url},
833
+ {"type": "input_text", "text": PROMPTS[key]},
834
+ ],
835
+ }
836
+ ],
837
+ max_output_tokens=32,
838
+ )
839
+ answer = extract_openai_text(response).strip().lower()
840
+ results[key] = answer
841
+ if answer.startswith("no"):
842
+ wrong = True
843
+ wrong_why.append(label)
844
+
845
+ return {
846
+ "answers": results,
847
+ "wrong": wrong,
848
+ "wrong_why": "; ".join(wrong_why) if wrong_why else "",
849
+ }
850
+
851
+
852
+ def stack_images_vertically(image1_path, image2_path, output_path, border_color=None, border_size=30):
853
+ img1 = Image.open(image1_path).convert("RGB")
854
+ img2 = Image.open(image2_path).convert("RGB")
855
+
856
+ width = max(img1.width, img2.width)
857
+ img1_resized = img1.resize((width, int(img1.height * width / img1.width)), Image.LANCZOS)
858
+ img2_resized = img2.resize((width, int(img2.height * width / img2.width)), Image.LANCZOS)
859
+
860
+ combined_height = img1_resized.height + img2_resized.height
861
+ combined = Image.new("RGB", (width, combined_height), (0, 0, 0))
862
+ combined.paste(img1_resized, (0, 0))
863
+ combined.paste(img2_resized, (0, img1_resized.height))
864
+
865
+ if border_color:
866
+ if "yes" in border_color.lower():
867
+ color = (16, 185, 129)
868
+ elif "no" in border_color.lower():
869
+ color = (239, 68, 68)
870
+ else:
871
+ color = (99, 102, 241)
872
+ combined = ImageOps.expand(combined, border=border_size, fill=color)
873
+
874
+ combined.save(output_path)
875
+ return output_path
876
+
877
+
878
+ if __name__ == "__main__":
879
+ os.makedirs(OUTPUT_DIR, exist_ok=True)
880
+ app.run(debug=True, port=5173)
plotextract/logo.svg ADDED
plotextract/templates/index.html ADDED
@@ -0,0 +1,121 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!doctype html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="UTF-8" />
5
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
6
+ <title>PlotExtract Web</title>
7
+ <link rel="preconnect" href="https://fonts.googleapis.com" />
8
+ <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
9
+ <link
10
+ href="https://fonts.googleapis.com/css2?family=Electrolize&family=JetBrains+Mono:wght@400;600&family=Space+Grotesk:wght@400;500;600;700&display=swap"
11
+ rel="stylesheet"
12
+ />
13
+ <link rel="stylesheet" href="{{ url_for('static', filename='styles.css') }}" />
14
+ </head>
15
+ <body data-app-base="{{ request.script_root }}">
16
+ <div class="glow"></div>
17
+ <main class="shell">
18
+ <header class="hero">
19
+ <div>
20
+ <div class="brand">
21
+ <img src="{{ url_for('static', filename='logo.svg') }}" alt="PlotExtract logo" />
22
+ <span>PlotExtract</span>
23
+ </div>
24
+ <p class="subhead">
25
+ Upload or paste a plot image, supply your Anthropic or OpenAI API key, and get back CSV data.
26
+ </p>
27
+ </div>
28
+ </header>
29
+
30
+ <section class="panel">
31
+ <div class="panel-head">
32
+ <p>Everything stays in your browser except the image which is sent to Anthropic or OpenAI.</p>
33
+ </div>
34
+ <div class="panel-grid inputs-row">
35
+ <div class="stack compact">
36
+ <label class="label" for="model">Model</label>
37
+ <select id="model" disabled>
38
+ <option value="">Enter API key to load models</option>
39
+ </select>
40
+ <label class="label" for="apiKey">API Key</label>
41
+ <div class="input-row">
42
+ <input id="apiKey" type="password" placeholder="sk-ant-... or sk-proj-..." autocomplete="off" />
43
+ <button class="ghost" id="toggleKey" type="button">Show</button>
44
+ </div>
45
+ <p class="hint left">We never store your key. It is used only for Anthropic or OpenAI API requests.</p>
46
+ </div>
47
+ <div class="stack">
48
+ <div class="dropzone tall" id="dropzone">
49
+ <input id="imageInput" type="file" accept="image/png,image/jpeg,.zip" />
50
+ <div class="dropzone-content">
51
+ <p>Drag & drop, click to upload, or paste from clipboard.</p>
52
+ <span class="small">PNG, JPG, or ZIP of images. Paste any image to auto-load.</span>
53
+ </div>
54
+ </div>
55
+ </div>
56
+ </div>
57
+ <div class="panel-grid layout-row">
58
+ <div class="stack">
59
+ <label class="label">Original</label>
60
+ <div class="preview" id="preview">
61
+ <p class="hint">Preview will appear here.</p>
62
+ </div>
63
+ </div>
64
+ <div class="stack" id="replotPane">
65
+ <label class="label">Replotted</label>
66
+ <div class="preview" id="replotPreview">
67
+ <p class="hint">Plot recreated using the extracted data will appear hear once the extraction process is finished.</p>
68
+ </div>
69
+ </div>
70
+ </div>
71
+ <div class="actions">
72
+ <button class="primary" id="runBtn" type="button">Extract Data</button>
73
+ <div class="status" id="status">Idle</div>
74
+ </div>
75
+ <div class="progress" id="progressBar" aria-hidden="true">
76
+ <div class="progress-fill" id="progressFill" style="width: 0%;"></div>
77
+ </div>
78
+ <pre class="error-details" id="errorDetails"></pre>
79
+ </section>
80
+
81
+ <section class="panel results" id="results">
82
+ <div class="panel-head">
83
+ <h2>Results</h2>
84
+ <p>Review the extracted CSV, generated plot, and validation overlay.</p>
85
+ </div>
86
+ <div class="results-grid" id="resultCards">
87
+ <div class="result-card">
88
+ <div class="card-head">
89
+ <h3>Extracted CSV</h3>
90
+ <button class="ghost" id="copyCsv" type="button">Copy CSV</button>
91
+ </div>
92
+ <textarea id="csvOutput" spellcheck="false"></textarea>
93
+ </div>
94
+ <div class="result-card">
95
+ <div class="card-head">
96
+ <h3>Generated Python</h3>
97
+ <button class="ghost" id="copyCode" type="button">Copy Code</button>
98
+ </div>
99
+ <textarea id="codeOutput" spellcheck="false"></textarea>
100
+ </div>
101
+ </div>
102
+ <div class="zip-download" id="zipDownload"></div>
103
+ <div class="validation" id="validation"></div>
104
+ </section>
105
+
106
+ <footer class="footer">
107
+ <p>
108
+ Disclaimer: This tool is designed for typical 2D XY plots. It generally works
109
+ best when figures are high-resolution, axis labels and tick values are clearly readable, and plots are
110
+ not overly crowded (especially when individual points or markers are visible). Performance may degrade
111
+ on low-quality scans, complex multi-panel figures, heavy overlap, unusual scales, or ambiguous labels.
112
+ Because extraction and validation rely on LLMs, outputs can contain mistakes, omissions, or formatting
113
+ issues and are not guaranteed to be correct. Always review and verify results before using them for
114
+ analysis, reporting, or decision-making.
115
+ </p>
116
+ </footer>
117
+ </main>
118
+
119
+ <script src="{{ url_for('static', filename='app.js') }}"></script>
120
+ </body>
121
+ </html>
requirements.txt CHANGED
@@ -16,3 +16,8 @@ networkx
16
  matplotlib
17
  Pillow
18
  regex
 
 
 
 
 
 
16
  matplotlib
17
  Pillow
18
  regex
19
+ flask>=3.0.0
20
+ anthropic>=0.40.0
21
+ openai>=1.0.0
22
+ numpy>=1.26.0
23
+ langchain-anthropic>=0.3.0,<1.0.0