Spaces:
Sleeping
Sleeping
File size: 10,570 Bytes
b47201f |
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 |
"""
Test the Hugging Face V4 JSON streaming endpoint with Outlines.
"""
import asyncio
import json
import httpx
async def test_hf_stream_json_endpoint():
"""Test HF V4 JSON streaming endpoint with URL scraping."""
# Hugging Face Space URL
hf_space_url = "https://colin730-summarizerapp.hf.space"
url = "https://www.nzherald.co.nz/nz/auckland/mt-wellington-homicide-jury-find-couple-not-guilty-of-murder-after-soldier-stormed-their-house-with-knife/B56S6KBHRVFCZMLDI56AZES6KY/"
print("=" * 80)
print("Hugging Face V4 JSON Streaming Endpoint Test (Outlines)")
print("=" * 80)
print(f"\nHF Space: {hf_space_url}")
print(f"Endpoint: {hf_space_url}/api/v4/scrape-and-summarize/stream-json")
print(f"Article URL: {url[:80]}...")
print(f"Style: executive\n")
payload = {
"url": url,
"style": "executive",
"include_metadata": True,
"use_cache": True,
}
# Longer timeout for HF (first request can be slow if cold start)
async with httpx.AsyncClient(timeout=600.0) as client:
try:
print("๐ Sending request to Hugging Face...")
print("โฑ๏ธ Note: First request may take 30-60s if instance is cold\n")
# Make streaming request
async with client.stream(
"POST",
f"{hf_space_url}/api/v4/scrape-and-summarize/stream-json",
json=payload,
) as response:
print(f"Status: {response.status_code}")
if response.status_code != 200:
error_text = await response.aread()
error_str = error_text.decode()
print(f"\nโ Error Response:")
print(error_str)
# Check if it's a 404 (endpoint not found)
if response.status_code == 404:
print("\n๐ก The endpoint might not be deployed yet.")
print(" The HF Space may still be building (~5-10 minutes).")
print(f" Check status at: https://huggingface.co/spaces/colin730/SummarizerApp")
return
print("\n" + "=" * 80)
print("STREAMING JSON TOKENS")
print("=" * 80)
metadata = None
json_buffer = ""
token_count = 0
# Parse SSE stream
async for line in response.aiter_lines():
if line.startswith("data: "):
data_content = line[6:] # Remove "data: " prefix
try:
# Try to parse as JSON (might be metadata or error event)
try:
event = json.loads(data_content)
# Handle metadata event
if event.get("type") == "metadata":
metadata = event["data"]
print("\n--- Metadata Event ---")
print(json.dumps(metadata, indent=2))
print("\n" + "-" * 80)
continue
# Handle error event
if event.get("type") == "error" or "error" in event:
error_msg = event.get('error', 'Unknown error')
error_detail = event.get('detail', '')
print(f"\nโ ERROR: {error_msg}")
if error_detail:
print(f" Detail: {error_detail}")
if "Outlines" in str(event.get("error", "")) or "Outlines" in str(error_detail):
print("\n๐ก This means:")
print(" - The endpoint is working โ
")
print(" - But Outlines is not available/installed")
print(f"\nFull error event:")
print(json.dumps(event, indent=2))
return
except json.JSONDecodeError:
# This is a raw JSON token - concatenate it
json_buffer += data_content
token_count += 1
if token_count % 10 == 0:
print(f"๐ Received {token_count} tokens...", end="\r")
except Exception as e:
print(f"\nโ ๏ธ Error processing line: {e}")
print(f"Raw: {data_content[:100]}")
# Print final results
print("\n" + "=" * 80)
print("FINAL RESULTS")
print("=" * 80)
if metadata:
print(f"\n--- Scraping Info ---")
print(f"Input type: {metadata.get('input_type')}")
print(f"Article title: {metadata.get('title')}")
print(f"Site: {metadata.get('site_name')}")
print(f"Scrape method: {metadata.get('scrape_method')}")
print(f"Scrape latency: {metadata.get('scrape_latency_ms', 0):.2f}ms")
print(f"Text extracted: {metadata.get('extracted_text_length', 0)} chars")
print(f"\nTotal tokens received: {token_count}")
print(f"JSON buffer length: {len(json_buffer)} chars")
# Try to parse the complete JSON
if json_buffer.strip():
try:
final_json = json.loads(json_buffer)
# Check if the JSON itself is an error object
if "error" in final_json:
print(f"\nโ ERROR IN JSON RESPONSE:")
print(f" Error: {final_json.get('error', 'Unknown error')}")
if "detail" in final_json:
print(f" Detail: {final_json.get('detail', '')}")
print(f"\nFull error JSON:")
print(json.dumps(final_json, indent=2))
return
print("\n--- Final JSON Object (StructuredSummary) ---")
print(json.dumps(final_json, indent=2, ensure_ascii=False))
# Validate structure
print("\n--- Validation ---")
required_fields = ["title", "main_summary", "key_points", "category", "sentiment", "read_time_min"]
all_valid = True
for field in required_fields:
value = final_json.get(field)
if field == "key_points":
if isinstance(value, list) and len(value) > 0:
print(f"โ
{field}: {len(value)} items")
else:
print(f"โ ๏ธ {field}: empty or not a list")
all_valid = False
else:
if value is not None:
value_str = str(value)[:50] + "..." if len(str(value)) > 50 else str(value)
print(f"โ
{field}: {value_str}")
else:
print(f"โ ๏ธ {field}: None")
all_valid = False
# Check sentiment is valid
sentiment = final_json.get("sentiment")
valid_sentiments = ["positive", "negative", "neutral"]
if sentiment in valid_sentiments:
print(f"โ
sentiment value is valid: {sentiment}")
else:
print(f"โ ๏ธ sentiment value is invalid: {sentiment}")
all_valid = False
print("\n" + "=" * 80)
if all_valid:
print("โ
ALL VALIDATIONS PASSED - HF JSON STREAMING ENDPOINT WORKING!")
print("โ
Outlines JSON schema enforcement is working!")
else:
print("โ ๏ธ Some validations failed")
print("=" * 80)
except json.JSONDecodeError as e:
print(f"\nโ Failed to parse final JSON: {e}")
print(f"\nJSON buffer (first 500 chars):")
print(json_buffer[:500])
print("\n๐ก The JSON might be incomplete or malformed")
else:
print("\nโ ๏ธ No JSON tokens received")
except httpx.ConnectError:
print(f"\nโ Could not connect to {hf_space_url}")
print("\n๐ก Possible reasons:")
print(" 1. HF Space is still building/deploying")
print(" 2. HF Space is sleeping (free tier)")
print(" 3. Network connectivity issue")
print(f"\n๐ Check space status: https://huggingface.co/spaces/colin730/SummarizerApp")
except httpx.ReadTimeout:
print("\nโฑ๏ธ Request timed out")
print(" This might mean the HF Space is cold-starting")
print(" Try again in a few moments")
except Exception as e:
print(f"\nโ Error: {e}")
import traceback
traceback.print_exc()
if __name__ == "__main__":
print("\n๐ Testing Hugging Face V4 JSON Streaming Endpoint (Outlines)\n")
asyncio.run(test_hf_stream_json_endpoint())
|