th Claude commited on
Commit
741463e
Β·
1 Parent(s): 3ec8c5d

Add robust ASCII-safe name conversion + detailed logging

Browse files

✨ Features:
- Smart name conversion: keeps ASCII names, converts non-ASCII to 'User'
- Detailed logging for debugging
- Empty SVG validation
- Full error traceback logging

πŸ› Fixes:
- Handles Chinese names (小鱼 β†’ User)
- Handles mixed names (TH123 β†’ TH123)
- Prevents empty SVG responses

πŸ€– Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>

Files changed (1) hide show
  1. app.py +40 -10
app.py CHANGED
@@ -11,12 +11,40 @@ from kerykeion import AstrologicalSubject, KerykeionChartSVG
11
  from typing import Optional, Any, Dict
12
  import logging
13
  import io
 
14
 
15
  logging.basicConfig(level=logging.INFO)
16
  logger = logging.getLogger(__name__)
17
 
18
  app = FastAPI(title="Sisi Astrology API", version="1.0.0")
19
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
20
  app.add_middleware(
21
  CORSMiddleware,
22
  allow_origins=["*"],
@@ -130,12 +158,9 @@ async def generate_chart_svg(req: BirthRequest):
130
  year, month, day = map(int, req.date.split('-'))
131
  hour, minute = map(int, req.time.split(':'))
132
 
133
- # Convert Chinese name to ASCII-safe version for SVG generation
134
- # KerykeionChartSVG doesn't support UTF-8 names well
135
- safe_name = req.name.encode('ascii', 'ignore').decode('ascii') or "User"
136
- if not safe_name or safe_name != req.name:
137
- # If name has non-ASCII characters, use generic name
138
- safe_name = "Chart"
139
 
140
  # Create AstrologicalSubject (Kerykeion 4.x)
141
  subject = AstrologicalSubject(
@@ -157,18 +182,23 @@ async def generate_chart_svg(req: BirthRequest):
157
  # Get SVG content as string
158
  svg_content = chart.makeSVG()
159
 
160
- logger.info(f"βœ… SVG generated for {req.name}")
 
 
 
161
 
162
  return Response(
163
  content=svg_content,
164
- media_type="image/svg+xml; charset=utf-8",
165
  headers={
166
- "Content-Disposition": f'inline; filename="birth-chart.svg"'
167
  }
168
  )
169
 
170
  except Exception as e:
171
- logger.error(f"❌ SVG Error: {e}")
 
 
172
  raise HTTPException(status_code=500, detail=str(e))
173
 
174
 
 
11
  from typing import Optional, Any, Dict
12
  import logging
13
  import io
14
+ import re
15
 
16
  logging.basicConfig(level=logging.INFO)
17
  logger = logging.getLogger(__name__)
18
 
19
  app = FastAPI(title="Sisi Astrology API", version="1.0.0")
20
 
21
+ def to_ascii_safe(name: str) -> str:
22
+ """
23
+ Convert any name to ASCII-safe version for SVG generation
24
+ - Chinese characters: Use first letter or initials
25
+ - Other non-ASCII: Remove or transliterate
26
+ - Already ASCII: Keep as is
27
+ """
28
+ if not name:
29
+ return "User"
30
+
31
+ # Check if name is already ASCII
32
+ try:
33
+ name.encode('ascii')
34
+ return name
35
+ except UnicodeEncodeError:
36
+ pass
37
+
38
+ # For Chinese/non-ASCII names, create initials or use "User"
39
+ # Simple approach: extract ASCII letters if any, otherwise use "User"
40
+ ascii_only = ''.join(c for c in name if ord(c) < 128)
41
+
42
+ if ascii_only and len(ascii_only) >= 2:
43
+ return ascii_only
44
+
45
+ # If name is purely non-ASCII (like "小鱼"), use generic name
46
+ return "User"
47
+
48
  app.add_middleware(
49
  CORSMiddleware,
50
  allow_origins=["*"],
 
158
  year, month, day = map(int, req.date.split('-'))
159
  hour, minute = map(int, req.time.split(':'))
160
 
161
+ # Convert name to ASCII-safe version for SVG generation
162
+ safe_name = to_ascii_safe(req.name)
163
+ logger.info(f"πŸ“ Name conversion: {req.name} β†’ {safe_name}")
 
 
 
164
 
165
  # Create AstrologicalSubject (Kerykeion 4.x)
166
  subject = AstrologicalSubject(
 
182
  # Get SVG content as string
183
  svg_content = chart.makeSVG()
184
 
185
+ if not svg_content or len(svg_content) < 100:
186
+ raise HTTPException(status_code=500, detail="SVG generation returned empty content")
187
+
188
+ logger.info(f"βœ… SVG generated ({len(svg_content)} bytes) for {req.name}")
189
 
190
  return Response(
191
  content=svg_content,
192
+ media_type="image/svg+xml",
193
  headers={
194
+ "Content-Disposition": 'inline; filename="birth-chart.svg"'
195
  }
196
  )
197
 
198
  except Exception as e:
199
+ logger.error(f"❌ SVG Error: {str(e)}")
200
+ import traceback
201
+ logger.error(traceback.format_exc())
202
  raise HTTPException(status_code=500, detail=str(e))
203
 
204