Repository navigation
Expand file tree
/
Copy pathmain.py
More file actions
2314 lines (2148 loc) · 87.6 KB
/
Copy pathmain.py
File metadata and controls
2314 lines (2148 loc) · 87.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from __future__ import annotations
import json
import logging
import os
import re
import uuid
from collections import Counter
from typing import Any, Optional
from urllib.parse import urljoin, urlparse
import requests
from bs4 import BeautifulSoup
from dotenv import load_dotenv
from fastapi import Body, FastAPI, HTTPException, Query, Request
from fastapi.responses import HTMLResponse
from openai import APIError, APITimeoutError, OpenAI
from pydantic import BaseModel, Field, HttpUrl
load_dotenv()
TINYFISH_API_KEY = os.getenv("TINYFISH_API_KEY")
OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")
if not TINYFISH_API_KEY:
raise RuntimeError("Missing required environment variable: TINYFISH_API_KEY")
if not OPENAI_API_KEY:
raise RuntimeError("Missing required environment variable: OPENAI_API_KEY")
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger("web2api")
app = FastAPI(
title="Web2API",
description=(
"Autonomous web extraction for modern product discovery.\n\n"
"Web2API turns messy storefronts and listing pages into structured JSON by combining "
"TinyFish browser automation with OpenAI-powered schema inference and semantic filtering."
),
version="1.0.0",
)
openai_client = OpenAI(api_key=OPENAI_API_KEY, timeout=45.0)
TINYFISH_URL = os.getenv("TINYFISH_URL", "https://agent.tinyfish.ai/v1/automation/run")
DEFAULT_MAX_ITEMS = 15
SYSTEM_PROMPT = (
"You are an expert data extraction agent. Parse the raw website data and return a JSON array "
"of objects matching the exact requested schema. If a field is missing, use null. Prices must be numbers."
)
SHOWCASE_SYSTEM_PROMPT = (
"You are a product merchandising strategist. Given extracted products, create a concise storefront "
"showcase JSON object. Make it polished, commercial, and grounded in the provided data. "
"Do not invent technical specs."
)
OPENAI_MODEL = "gpt-4.1-mini"
RAW_DATA_CHAR_LIMIT = 120_000
USER_AGENT = (
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) "
"AppleWebKit/537.36 (KHTML, like Gecko) Chrome/123.0.0.0 Safari/537.36"
)
REQUEST_TIMEOUT = 12
ANALYSIS_STORE: dict[str, dict[str, Any]] = {}
SCHEMA_PRESETS: dict[str, dict[str, Any]] = {
"product_standard": {
"label": "Product Standard",
"description": "Balanced product catalog schema for storefront data and showcase generation.",
"fields": [
"product_name",
"subtitle",
"current_price",
"original_price",
"product_url",
"image_url",
],
},
"pricing_audit": {
"label": "Pricing Audit",
"description": "Focus on pricing, discount visibility, and basic landing links.",
"fields": [
"product_name",
"category",
"current_price",
"original_price",
"discount_amount",
"price_status",
"product_url",
],
},
"merchandising_cards": {
"label": "Merchandising Cards",
"description": "Creative product-card schema for quick demo grids and editorial previews.",
"fields": [
"product_name",
"subtitle",
"price_label",
"badge",
"product_url",
"image_url",
"image_description",
],
},
}
class ProductSchema(BaseModel):
product_name: str
subtitle: Optional[str] = None
current_price: float
original_price: float
product_url: str
image_url: str
class ShowcaseRequest(BaseModel):
source_url: str
semantic_query: Optional[str] = None
products: list[ProductSchema] = Field(min_length=1, max_length=15)
class ShowcaseCard(BaseModel):
product_name: str
subtitle: Optional[str] = None
price_label: str
image_url: str
product_url: str
image_description: str
marketing_copy: str
badge: str
class ShowcaseResponse(BaseModel):
collection_title: str
collection_subtitle: str
visual_direction: str
cards: list[ShowcaseCard]
class ExtractionDetailResponse(BaseModel):
source_url: str
semantic_query: Optional[str] = None
max_items: int
schema_preset: str
schema_fields: list[str]
tinyfish_status: Optional[str] = None
raw_product_count: int
schema_preview: list[dict[str, Any]]
normalized_products: list[ProductSchema]
raw_openai_items: list[dict[str, Any]]
dropped_reasons: list[str]
class AnalyzeRequest(BaseModel):
url: HttpUrl
goal: str
def _to_float(value: Any) -> Optional[float]:
if value is None:
return None
if isinstance(value, (int, float)):
return float(value)
if isinstance(value, str):
cleaned = value.replace(",", "")
match = re.search(r"-?\d+(?:\.\d+)?", cleaned)
if match:
try:
return float(match.group(0))
except ValueError:
return None
return None
def _format_price(current_price: float, original_price: float) -> str:
current_label = f"${current_price:,.2f}"
if original_price > current_price:
return f"{current_label} (was ${original_price:,.2f})"
return current_label
def _build_tinyfish_goal(max_items: int) -> str:
return (
"Extract product listing data from the collection page. Wait for the main product grid to load, "
"close any popups, and scroll only as much as needed to reveal more product cards and lazy-loaded images. "
f"Extract up to the first {max_items} product cards that become visible across the loaded grid. "
"For each product card, explicitly capture product_name, subtitle or category, current_price, "
"original_price if present, product_url or href, image_url or image src, and any badges or labels. "
"Prefer absolute URLs for product_url and image_url. Return raw text/JSON."
)
def _get_schema_preset(schema_preset: str) -> dict[str, Any]:
preset = SCHEMA_PRESETS.get(schema_preset)
if not preset:
raise HTTPException(status_code=422, detail=f"Unknown schema_preset: {schema_preset}")
return preset
def _build_schema_instructions(schema_preset: str) -> str:
preset = _get_schema_preset(schema_preset)
fields = ", ".join(preset["fields"])
return (
f"Use the '{schema_preset}' schema preset. "
f"Return a JSON array of objects with these exact fields in each item: {fields}. "
"If a field is missing, use null. Prices must be numbers when numeric fields exist."
)
def _build_user_prompt(raw_data: str, semantic_query: Optional[str], schema_preset: str) -> str:
prompt = (
f"{_build_schema_instructions(schema_preset)} "
f"Here is the raw data: {raw_data}. Extract the items."
)
if semantic_query:
prompt += (
f" FILTERING REQUIREMENT: The user only wants items that match this description: "
f"'{semantic_query}'. Filter the list and ONLY return items that semantically match "
f"this vibe or description based on your reasoning."
)
return prompt
def _parse_json_array(text: str) -> list[dict[str, Any]]:
cleaned = text.strip()
if cleaned.startswith("```"):
cleaned = re.sub(
r"^```(?:json)?\s*|\s*```$",
"",
cleaned,
flags=re.IGNORECASE | re.DOTALL,
).strip()
parsed: Any
try:
parsed = json.loads(cleaned)
except json.JSONDecodeError:
start = cleaned.find("[")
end = cleaned.rfind("]")
if start == -1 or end == -1 or start >= end:
raise ValueError("OpenAI response was not valid JSON.")
parsed = json.loads(cleaned[start : end + 1])
if isinstance(parsed, dict):
for key in ("items", "data", "results", "products"):
if isinstance(parsed.get(key), list):
parsed = parsed[key]
break
if not isinstance(parsed, list):
raise ValueError("OpenAI did not return a JSON array.")
return [item for item in parsed if isinstance(item, dict)]
def _parse_json_object(text: str) -> dict[str, Any]:
cleaned = text.strip()
if cleaned.startswith("```"):
cleaned = re.sub(
r"^```(?:json)?\s*|\s*```$",
"",
cleaned,
flags=re.IGNORECASE | re.DOTALL,
).strip()
try:
parsed = json.loads(cleaned)
except json.JSONDecodeError:
start = cleaned.find("{")
end = cleaned.rfind("}")
if start == -1 or end == -1 or start >= end:
raise ValueError("OpenAI response was not valid JSON.")
parsed = json.loads(cleaned[start : end + 1])
if not isinstance(parsed, dict):
raise ValueError("OpenAI did not return a JSON object.")
return parsed
def normalize_url(url: str) -> str:
parsed = urlparse(url)
path = parsed.path.rstrip("/") or "/"
return f"{parsed.scheme}://{parsed.netloc}{path}"
def fetch_html(url: str) -> tuple[str, requests.Response]:
response = requests.get(
url,
timeout=REQUEST_TIMEOUT,
headers={"User-Agent": USER_AGENT, "Accept-Language": "en-US,en;q=0.9"},
)
response.raise_for_status()
return response.text, response
def clean_text(value: str | None) -> str:
if not value:
return ""
return re.sub(r"\s+", " ", value).strip()
def same_host_links(soup: BeautifulSoup, base_url: str) -> list[str]:
parsed_base = urlparse(base_url)
collected: list[str] = []
for anchor in soup.select("a[href]"):
href = anchor.get("href", "").strip()
if not href or href.startswith(("#", "mailto:", "tel:", "javascript:")):
continue
absolute = urljoin(base_url, href)
parsed = urlparse(absolute)
if parsed.scheme not in {"http", "https"} or parsed.netloc != parsed_base.netloc:
continue
normalized = normalize_url(absolute)
if normalized != normalize_url(base_url):
collected.append(normalized)
return list(dict.fromkeys(collected))[:20]
def detect_entity(goal: str, title: str, url: str) -> str:
text = f"{goal} {title} {url}".lower()
mapping = {
"product": [
"product", "price", "store", "shop", "cart", "buy", "shoe", "shoes", "sneaker",
"sneakers", "apparel", "collection", "men", "women", "kids", "tops", "bottoms",
],
"job_listing": ["job", "career", "hiring", "role", "position"],
"property_listing": ["property", "listing", "rent", "sale", "home", "condo", "apartment"],
"event": ["event", "conference", "meetup", "workshop", "register"],
}
for entity, keywords in mapping.items():
if any(keyword in text for keyword in keywords):
return entity
return "article"
def extract_price_text(value: str) -> str:
match = re.search(r"((?:sgd|usd|eur|gbp|aud|cad|s\$|\$|€|£)\s?\d[\d,]*(?:\.\d{1,2})?)", value, re.IGNORECASE)
if match:
return clean_text(match.group(1))
return ""
def product_candidates_from_containers(soup: BeautifulSoup, base_url: str) -> list[dict[str, Any]]:
base_host = urlparse(base_url).netloc
seen: set[str] = set()
candidates: list[dict[str, Any]] = []
for container in soup.select("article, div, li"):
anchor = container.select_one("a[href]")
image_node = container.select_one("img")
if not anchor:
continue
href = urljoin(base_url, anchor.get("href", "").strip())
parsed = urlparse(href)
if parsed.scheme not in {"http", "https"} or parsed.netloc != base_host:
continue
normalized = normalize_url(href)
if normalized in seen or normalized == normalize_url(base_url):
continue
if not looks_like_product_url(normalized, base_host):
continue
title = ""
heading = container.select_one("h1, h2, h3, h4")
if heading:
title = clean_text(heading.get_text(" ", strip=True))
if not title:
title = clean_text(anchor.get_text(" ", strip=True))
if len(title) < 4:
continue
if "/w/" in normalized and re.search(r"\(\d+\)", title):
continue
text_blob = clean_text(container.get_text(" ", strip=True))
price_text = extract_price_text(text_blob)
if not heading and not image_node and not price_text:
continue
image_url = ""
if image_node and image_node.get("src"):
image_url = urljoin(base_url, image_node.get("src"))
summary_node = container.select_one("p, span")
summary = clean_text(summary_node.get_text(" ", strip=True)) if summary_node else ""
candidate: dict[str, Any] = {
"title": title,
"url": normalized,
"summary": summary,
}
if price_text:
candidate["price_text"] = price_text
if image_url:
candidate["image_url"] = image_url
candidates.append(candidate)
seen.add(normalized)
return candidates[:12]
def looks_like_article_url(url: str, base_host: str) -> bool:
parsed = urlparse(url)
path = parsed.path.lower().strip("/")
if parsed.netloc != base_host or not path:
return False
disallowed = {
"about", "contact", "privacy", "terms", "advertise", "latest", "tag", "category", "topics",
"newsletter", "events", "podcasts", "news", "newest", "front", "newcomments", "ask", "show",
"jobs", "submit", "login", "best", "item", "user",
}
first = path.split("/")[0]
if first in disallowed:
return False
return len(path.split("/")) >= 2 or re.search(r"\d{4}", path) is not None
def looks_like_product_url(url: str, base_host: str) -> bool:
parsed = urlparse(url)
if parsed.netloc != base_host:
return False
path = parsed.path.lower().strip("/")
if not path:
return False
disallowed = {
"help", "retail", "orders", "member", "members", "login", "join", "cart",
"favorites", "wishlist", "privacy", "terms", "about", "contact",
}
segments = [segment for segment in path.split("/") if segment]
if any(segment in disallowed for segment in segments):
return False
return len(segments) >= 2
def extract_hacker_news_records(soup: BeautifulSoup) -> list[dict[str, Any]]:
records: list[dict[str, Any]] = []
for index, row in enumerate(soup.select("tr.athing"), start=1):
title_link = row.select_one(".titleline > a, .title a")
if not title_link:
continue
story_url = clean_text(title_link.get("href"))
if story_url.startswith("item?id="):
story_url = urljoin("https://news.ycombinator.com/", story_url)
title = clean_text(title_link.get_text(" ", strip=True))
if not title:
continue
subtext_row = row.find_next_sibling("tr")
score = author = age = comments = ""
if subtext_row:
score_node = subtext_row.select_one(".score")
author_node = subtext_row.select_one(".hnuser")
age_node = subtext_row.select_one(".age")
comment_links = subtext_row.select("a")
score = clean_text(score_node.get_text(" ", strip=True)) if score_node else ""
author = clean_text(author_node.get_text(" ", strip=True)) if author_node else ""
age = clean_text(age_node.get_text(" ", strip=True)) if age_node else ""
for link in reversed(comment_links):
text = clean_text(link.get_text(" ", strip=True))
if "comment" in text.lower() or text.lower() == "discuss":
comments = text
break
record = {"id": index, "title": title, "url": story_url}
if author:
record["author"] = author
if age:
record["published_at"] = age
if score:
record["score"] = score
if comments:
record["comments"] = comments
records.append(record)
return records[:12]
def article_candidates_from_containers(soup: BeautifulSoup, base_url: str) -> list[dict[str, Any]]:
base_host = urlparse(base_url).netloc
seen: set[str] = set()
candidates: list[dict[str, Any]] = []
for container in soup.select("article, div, li"):
headings = container.select("h1 a[href], h2 a[href], h3 a[href], h4 a[href]")
if not headings:
continue
anchor = headings[0]
href = urljoin(base_url, anchor.get("href", "").strip())
normalized = normalize_url(href)
if not looks_like_article_url(normalized, base_host) or normalized in seen:
continue
if container.find_parent(["header", "nav"]):
continue
title = clean_text(anchor.get_text(" ", strip=True))
if len(title) < 20:
continue
summary_node = container.select_one("p")
time_node = container.select_one("time")
author_node = container.select_one('[rel="author"], .author, [class*="author"], [data-testid*="author"]')
image_node = container.select_one("img")
candidates.append(
{
"title": title,
"url": normalized,
"summary": clean_text(summary_node.get_text(" ", strip=True)) if summary_node else "",
"published_at": clean_text(time_node.get("datetime") or time_node.get_text(" ", strip=True)) if time_node else "",
"author": clean_text(author_node.get_text(" ", strip=True)) if author_node else "",
"image_url": urljoin(base_url, image_node.get("src")) if image_node and image_node.get("src") else "",
}
)
seen.add(normalized)
return candidates[:12]
def article_candidates_from_links(soup: BeautifulSoup, base_url: str) -> list[dict[str, Any]]:
base_host = urlparse(base_url).netloc
seen: set[str] = set()
candidates: list[dict[str, Any]] = []
for anchor in soup.select("a[href]"):
href = urljoin(base_url, anchor.get("href", "").strip())
normalized = normalize_url(href)
title = clean_text(anchor.get_text(" ", strip=True))
if normalized in seen or len(title) < 28:
continue
if not looks_like_article_url(normalized, base_host):
continue
seen.add(normalized)
candidates.append({"title": title, "url": normalized, "summary": "", "published_at": "", "author": "", "image_url": ""})
return candidates[:12]
def extract_article_records(soup: BeautifulSoup, base_url: str) -> list[dict[str, Any]]:
if urlparse(base_url).netloc == "news.ycombinator.com":
records = extract_hacker_news_records(soup)
if records:
return records
candidates = article_candidates_from_containers(soup, base_url)
if len(candidates) < 3:
candidates = article_candidates_from_links(soup, base_url)
records: list[dict[str, Any]] = []
for index, candidate in enumerate(candidates[:8], start=1):
record = {"id": index, "title": candidate["title"], "url": candidate["url"]}
for key in ("summary", "published_at", "author", "image_url"):
if candidate.get(key):
record[key] = candidate[key]
records.append(record)
return records
def make_sample_records(
entity: str,
landing_title: str,
landing_url: str,
internal_links: list[str],
soup: BeautifulSoup,
) -> list[dict[str, Any]]:
if entity == "product":
product_candidates = product_candidates_from_containers(soup, landing_url)
if product_candidates:
records: list[dict[str, Any]] = []
for index, candidate in enumerate(product_candidates[:8], start=1):
record: dict[str, Any] = {
"id": index,
"title": candidate["title"],
"url": candidate["url"],
}
if candidate.get("summary"):
record["summary"] = candidate["summary"]
if candidate.get("price_text"):
record["price_text"] = candidate["price_text"]
if candidate.get("image_url"):
record["image_url"] = candidate["image_url"]
records.append(record)
return records
if entity == "article":
article_records = extract_article_records(soup, landing_url)
if article_records:
return article_records
description = ""
meta_description = soup.select_one('meta[name="description"]')
if meta_description:
description = clean_text(meta_description.get("content"))
if not internal_links:
internal_links = [landing_url]
records: list[dict[str, Any]] = []
for index, link in enumerate(internal_links[:6], start=1):
link_title = link.rstrip("/").split("/")[-1].replace("-", " ").replace("_", " ").strip().title()
if not link_title:
link_title = landing_title
record: dict[str, Any] = {"id": index, "title": link_title or f"{entity.title()} {index}", "url": link}
if entity == "product":
record["summary"] = description or f"Detected product-like page from {landing_title}."
record["price_text"] = "Price detected on page"
elif entity == "job_listing":
record["summary"] = description or f"Detected hiring-related content from {landing_title}."
record["team"] = "Unknown team"
record["location"] = "Unknown location"
elif entity == "property_listing":
record["summary"] = description or f"Detected property-related content from {landing_title}."
record["location"] = "Unknown location"
record["price_text"] = "Price detected on page"
elif entity == "event":
record["summary"] = description or f"Detected event-related content from {landing_title}."
record["date_text"] = "Date not parsed"
record["location"] = "Location not parsed"
else:
record["summary"] = description or f"Extracted from {landing_title}."
record["published_hint"] = "No explicit publish date parsed"
records.append(record)
return records
def infer_schema_from_samples(samples: list[dict[str, Any]]) -> list[dict[str, str]]:
if not samples:
return [{"name": "title", "type": "string"}, {"name": "url", "type": "string"}]
field_types: dict[str, str] = {}
for key in samples[0].keys():
value = next((sample.get(key) for sample in samples if sample.get(key) not in (None, "")), "")
field_types[key] = "number" if isinstance(value, int) else "string"
ordered: list[dict[str, str]] = []
preferred_order = ["id", "title", "summary", "author", "published_at", "score", "comments", "price_text", "location", "url", "image_url"]
for field in preferred_order:
if field in field_types:
ordered.append({"name": field, "type": field_types[field]})
for field, field_type in field_types.items():
if field not in {item["name"] for item in ordered}:
ordered.append({"name": field, "type": field_type})
return ordered
def summarize_link_patterns(links: list[str], canonical_url: str, entity: str) -> list[dict[str, str]]:
if not links:
return [{"page_type": "landing", "pattern": urlparse(canonical_url).path or "/", "notes": "Only the root page was accessible."}]
parsed_paths = [urlparse(link).path or "/" for link in links]
segment_counter = Counter(path.strip("/").split("/")[0] if path.strip("/") else "root" for path in parsed_paths)
common_segment, _ = segment_counter.most_common(1)[0]
listing_pattern = urlparse(canonical_url).path or "/"
detail_pattern = f"/{common_segment}/:slug" if common_segment != "root" else "/:slug"
detail_note = "Detail pages are inferred from deeper internal links."
if entity == "article":
detail_note = "Article detail pages are inferred from repeated editorial links."
return [
{"page_type": "landing", "pattern": "/", "notes": "Fetched the entry page successfully."},
{"page_type": "listing", "pattern": listing_pattern, "notes": "This page behaves like a collection or category view."},
{"page_type": "detail", "pattern": detail_pattern, "notes": detail_note},
]
def build_generated_api(analysis_id: str, entity: str, origin: str) -> dict[str, Any]:
base_url = f"{origin.rstrip('/')}/api/generated"
return {
"base_url": base_url,
"endpoints": [
f"GET /items?analysis_id={analysis_id}",
f"GET /items/{{id}}?analysis_id={analysis_id}",
f"GET /schema?analysis_id={analysis_id}",
],
"description": f"Working API endpoints for the stored '{entity}' analysis.",
}
def build_quickstart(analysis_id: str, origin: str) -> dict[str, str]:
base_url = f"{origin.rstrip('/')}/api/generated"
return {
"curl": f"curl '{base_url}/items?analysis_id={analysis_id}' \\\n -H 'Accept: application/json'",
"python": (
"import requests\n\n"
f"response = requests.get('{base_url}/items', params={{'analysis_id': '{analysis_id}'}})\n"
"response.raise_for_status()\nprint(response.json())"
),
"javascript": (
f"const response = await fetch('{base_url}/items?analysis_id={analysis_id}');\n"
"const data = await response.json();\nconsole.log(data);"
),
}
def analyze_website(url: str, goal: str, origin: str) -> dict[str, Any]:
html, response = fetch_html(url)
soup = BeautifulSoup(html, "html.parser")
title = clean_text(soup.title.string if soup.title and soup.title.string else "") or urlparse(str(response.url)).netloc
hostname = urlparse(str(response.url)).netloc.replace("www.", "") or "unknown-site"
entity = detect_entity(goal, title, str(response.url))
internal_links = same_host_links(soup, str(response.url))
samples = make_sample_records(entity, title, str(response.url), internal_links, soup)
fields = infer_schema_from_samples(samples)
site_map = summarize_link_patterns(internal_links, str(response.url), entity)
analysis_id = uuid.uuid4().hex[:12]
confidence = 0.64
if len(internal_links) >= 5:
confidence += 0.12
if len(fields) >= 4:
confidence += 0.08
if samples:
confidence += 0.06
result = {
"status": "success",
"mode": "live",
"analysis_id": analysis_id,
"site": {
"url": str(response.url),
"hostname": hostname,
"entity_guess": entity,
"confidence": round(min(confidence, 0.96), 2),
"title": title,
},
"site_map": site_map,
"schema": {"entity": entity, "fields": fields},
"generated_api": build_generated_api(analysis_id, entity, origin),
"samples": samples,
"agent_notes": [
f"Fetched the live page for {hostname} and parsed its visible HTML structure.",
f"Discovered {len(internal_links)} internal links and prioritized likely content pages over generic navigation.",
f"Inferred a '{entity}' schema from the actual extracted records rather than guessing from navigation labels.",
"Stored the analysis in memory and exposed working generated endpoints for the extracted result.",
],
"quickstart": build_quickstart(analysis_id, origin),
"product_summary": {
"headline": "Turn a website into a structured data product.",
"description": (
"This backend performs a real live fetch of the target website, infers a schema from the returned HTML, "
"and creates working API endpoints for the generated records."
),
},
"goal": goal,
}
ANALYSIS_STORE[analysis_id] = result
return result
def get_saved_analysis(analysis_id: str) -> dict[str, Any]:
analysis = ANALYSIS_STORE.get(analysis_id)
if not analysis:
raise HTTPException(status_code=404, detail="Unknown analysis_id. Run /api/analyze first.")
return analysis
def _call_tinyfish(target_url: str, max_items: int) -> str:
headers = {
"X-API-Key": TINYFISH_API_KEY,
"Content-Type": "application/json",
}
payload = {
"url": target_url,
"goal": _build_tinyfish_goal(max_items),
"browser_profile": "lite",
"proxy_config": {"enabled": False},
"api_integration": "web2api",
}
try:
response = requests.post(
TINYFISH_URL,
headers=headers,
json=payload,
timeout=180,
)
response.raise_for_status()
except requests.Timeout as exc:
logger.exception("TinyFish request timed out")
raise HTTPException(status_code=500, detail="TinyFish request timed out.") from exc
except requests.ConnectionError as exc:
logger.exception("TinyFish host connection failed")
raise HTTPException(
status_code=500,
detail=(
f"TinyFish host connection failed for {TINYFISH_URL}. "
"Check the TinyFish endpoint, DNS, or your network."
),
) from exc
except requests.RequestException as exc:
logger.exception("TinyFish request failed")
raise HTTPException(status_code=500, detail=f"TinyFish request failed: {exc}") from exc
try:
return json.dumps(response.json(), ensure_ascii=False)
except ValueError:
return response.text
def _parse_tinyfish_payload(raw_data: str) -> dict[str, Any]:
try:
parsed = json.loads(raw_data)
except json.JSONDecodeError:
return {}
return parsed if isinstance(parsed, dict) else {}
def _call_openai(raw_data: str, semantic_query: Optional[str], schema_preset: str) -> list[dict[str, Any]]:
truncated_raw_data = raw_data[:RAW_DATA_CHAR_LIMIT]
user_prompt = _build_user_prompt(truncated_raw_data, semantic_query, schema_preset)
try:
completion = openai_client.chat.completions.create(
model=OPENAI_MODEL,
temperature=0,
messages=[
{"role": "system", "content": SYSTEM_PROMPT},
{"role": "user", "content": user_prompt},
],
)
except APITimeoutError as exc:
logger.exception("OpenAI request timed out")
raise HTTPException(status_code=500, detail="OpenAI request timed out.") from exc
except APIError as exc:
logger.exception("OpenAI request failed")
raise HTTPException(status_code=500, detail=f"OpenAI request failed: {exc}") from exc
except Exception as exc:
logger.exception("Unexpected OpenAI error")
raise HTTPException(status_code=500, detail=f"Unexpected OpenAI error: {exc}") from exc
content = ""
if completion.choices:
content = (completion.choices[0].message.content or "").strip()
if not content:
raise HTTPException(status_code=500, detail="OpenAI returned an empty response.")
try:
return _parse_json_array(content)
except ValueError as exc:
raise HTTPException(status_code=500, detail=f"Failed to parse OpenAI JSON output: {exc}") from exc
def _normalize_products(items: list[dict[str, Any]]) -> list[ProductSchema]:
normalized: list[ProductSchema] = []
for item in items:
candidate = {
"product_name": str(item.get("product_name") or "").strip(),
"subtitle": str(item["subtitle"]).strip() if item.get("subtitle") not in (None, "") else None,
"current_price": _to_float(item.get("current_price")),
"original_price": _to_float(item.get("original_price")),
"product_url": str(item.get("product_url") or "").strip(),
"image_url": str(item.get("image_url") or "").strip(),
}
if (
not candidate["product_name"]
or candidate["current_price"] is None
or candidate["original_price"] is None
or not candidate["product_url"]
or not candidate["image_url"]
):
continue
try:
normalized.append(ProductSchema(**candidate))
except Exception:
logger.warning("Skipping invalid product payload: %s", item)
return normalized
def _build_schema_candidate(item: dict[str, Any], schema_preset: str) -> dict[str, Any]:
subtitle = item.get("subtitle")
if subtitle in (None, ""):
subtitle = item.get("category")
current_price = _to_float(item.get("current_price"))
if current_price is None:
current_price = _to_float(item.get("price"))
original_price = _to_float(item.get("original_price"))
if original_price is None:
original_price = current_price
product_url = item.get("product_url") or item.get("url")
image_url = item.get("image_url") or item.get("image")
base_name = str(item.get("product_name") or item.get("name") or "").strip() or None
base_subtitle = str(subtitle).strip() if subtitle not in (None, "") else None
base_product_url = str(product_url).strip() if product_url else None
base_image_url = str(image_url).strip() if image_url else None
category = str(item.get("category") or "").strip() or None
badge = str(item.get("badge") or "").strip() if item.get("badge") else None
labels = item.get("labels")
if not badge and isinstance(labels, list) and labels:
badge = str(labels[0]).strip() or None
if schema_preset == "pricing_audit":
discount_amount = None
if current_price is not None and original_price is not None:
discount_amount = max(original_price - current_price, 0.0)
price_status = "discounted" if discount_amount and discount_amount > 0 else "full_price"
return {
"product_name": base_name,
"category": category,
"current_price": current_price,
"original_price": original_price,
"discount_amount": discount_amount,
"price_status": price_status,
"product_url": base_product_url,
}
if schema_preset == "merchandising_cards":
price_label = None
if current_price is not None:
price_label = _format_price(current_price, original_price or current_price)
return {
"product_name": base_name,
"subtitle": base_subtitle,
"price_label": price_label,
"badge": badge,
"product_url": base_product_url,
"image_url": base_image_url,
"image_description": (
f"Product image for {base_name}" if base_name else None
),
}
return {
"product_name": base_name,
"subtitle": base_subtitle,
"current_price": current_price,
"original_price": original_price,
"product_url": base_product_url,
"image_url": base_image_url,
}
def _extract_raw_product_cards(tinyfish_payload: dict[str, Any]) -> list[dict[str, Any]]:
result = tinyfish_payload.get("result")
if not isinstance(result, dict):
return []
for key in ("product_cards", "products", "items", "results"):
value = result.get(key)
if isinstance(value, list):
return [item for item in value if isinstance(item, dict)]
return []
def _build_dropped_reasons(schema_preview: list[dict[str, Any]], schema_preset: str) -> list[str]:
if schema_preset != "product_standard":
return []
reasons: list[str] = []
for item in schema_preview:
missing = []
if not item.get("product_name"):
missing.append("product_name")
if item.get("current_price") is None:
missing.append("current_price")
if item.get("original_price") is None:
missing.append("original_price")
if not item.get("product_url"):
missing.append("product_url")
if not item.get("image_url"):
missing.append("image_url")
if missing:
reasons.append(
f"{item.get('product_name') or 'Unknown item'} missing required fields: {', '.join(missing)}"
)
return reasons
def _extract_details(
url: str,
semantic_query: Optional[str],
max_items: int = DEFAULT_MAX_ITEMS,
schema_preset: str = "product_standard",
) -> ExtractionDetailResponse:
if not re.match(r"^https?://", url, flags=re.IGNORECASE):
raise HTTPException(status_code=422, detail="`url` must start with http:// or https://")
if max_items < 1 or max_items > 40:
raise HTTPException(status_code=422, detail="`max_items` must be between 1 and 40.")
preset = _get_schema_preset(schema_preset)
raw_data = _call_tinyfish(url, max_items)
if not raw_data.strip():
raise HTTPException(status_code=500, detail="TinyFish returned empty data.")
tinyfish_payload = _parse_tinyfish_payload(raw_data)
raw_cards = _extract_raw_product_cards(tinyfish_payload)
openai_items = _call_openai(raw_data, semantic_query, schema_preset)
preview_source = openai_items or raw_cards
schema_preview = [_build_schema_candidate(item, schema_preset) for item in preview_source]
normalized_products = _normalize_products(openai_items) if schema_preset == "product_standard" else []
return ExtractionDetailResponse(
source_url=url,
semantic_query=semantic_query,
max_items=max_items,
schema_preset=schema_preset,
schema_fields=list(preset["fields"]),
tinyfish_status=tinyfish_payload.get("status") if isinstance(tinyfish_payload, dict) else None,
raw_product_count=len(raw_cards),
schema_preview=schema_preview,
normalized_products=normalized_products,
raw_openai_items=openai_items,
dropped_reasons=_build_dropped_reasons(schema_preview, schema_preset) if not normalized_products else [],
)
def _extract_products(url: str, semantic_query: Optional[str]) -> list[ProductSchema]:
return _extract_details(url, semantic_query, DEFAULT_MAX_ITEMS, "product_standard").normalized_products
def _build_showcase_prompt(payload: ShowcaseRequest) -> str:
products = [