more fixes
Browse files36 unmodified lines37383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091270 unmodified lines36236336436536636717 unmodified lines385386387388389390391392393394199 unmodified lines59459559659759859960060160260360460536 unmodified linesdef parse_transformers_js_output(code: str) -> Dict[str, str]:"""Parse transformers.js output into separate files"""files = {}# First try: Pattern to match === filename === sectionspattern = r'===\s*(\S+\.(?:html|js|css))\s*===\s*(.*?)(?====|$)'matches = re.finditer(pattern, code, re.DOTALL | re.IGNORECASE)for match in matches:filename = match.group(1).strip()content = match.group(2).strip()# Clean up code blocks if presentcontent = re.sub(r'^```\w*\s*', '', content, flags=re.MULTILINE)content = re.sub(r'```\s*$', '', content, flags=re.MULTILINE)files[filename] = content# Fallback: Try to extract from markdown code blocks if === format not foundif not files:print("[Deploy] === format not found, trying markdown code blocks fallback")# Try to find ```html, ```javascript, ```css blockshtml_match = re.search(r'```html\s*(.*?)```', code, re.DOTALL | re.IGNORECASE)js_match = re.search(r'```javascript\s*(.*?)```', code, re.DOTALL | re.IGNORECASE)css_match = re.search(r'```css\s*(.*?)```', code, re.DOTALL | re.IGNORECASE)if html_match:content = html_match.group(1).strip()# Remove comment lines like "<!-- index.html content here -->"content = re.sub(r'<!--\s*index\.html.*?-->\s*', '', content, flags=re.IGNORECASE)files['index.html'] = contentif js_match:content = js_match.group(1).strip()# Remove comment lines like "// index.js content here"content = re.sub(r'//\s*index\.js.*?\n', '', content, flags=re.IGNORECASE)files['index.js'] = contentif css_match:content = css_match.group(1).strip()# Remove comment lines like "/* style.css content here */"content = re.sub(r'/\*\s*style\.css.*?\*/', '', content, flags=re.IGNORECASE)files['style.css'] = content# Last resort: try to extract as single HTML fileif not files:html_content = parse_html_code(code)if html_content:files['index.html'] = html_contentreturn files270 unmodified linesfiles = parse_transformers_js_output(code)print(f"[Deploy] Parsed transformers.js files: {list(files.keys())}")# Validate all three files are presentmissing_files = []if not files.get('index.html'):17 unmodified linesprint(f"[Deploy] {error_msg}")return False, error_msg, None# Write transformers.js filesfor filename, content in files.items():print(f"[Deploy] Writing {filename} ({len(content)} chars)")(temp_path / filename).write_text(content, encoding='utf-8')# For transformers.js, we'll upload files individually (not via upload_folder)use_individual_uploads = True199 unmodified linestemp_file_path = Nonetry:# Create a NEW temp file for this upload (key difference from old approach)with tempfile.NamedTemporaryFile("w", suffix=f".{file_name.split('.')[-1]}", delete=False, encoding='utf-8') as f:f.write(file_content)f.flush() # Ensure all content is written to disk before closingtemp_file_path = f.name# File is now closed and flushed, safe to upload# Upload the file without commit_message (HF handles this for spaces)api.upload_file(path_or_fileobj=temp_file_path,36 unmodified lines373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123270 unmodified lines39439539639739839940040140240340440540617 unmodified lines424425426427428429430431432433434435436437199 unmodified lines63763863964064164264364464564664764864965065165265365436 unmodified linesdef parse_transformers_js_output(code: str) -> Dict[str, str]:"""Parse transformers.js output into separate files (index.html, index.js, style.css)Uses comprehensive parsing patterns to handle various LLM output formats."""files = {'index.html': '','index.js': '','style.css': ''}# Multiple patterns to match the three code blocks with different variationshtml_patterns = [r'```html\s*\n([\s\S]*?)(?:```|\Z)',r'```htm\s*\n([\s\S]*?)(?:```|\Z)',r'```\s*(?:index\.html|html)\s*\n([\s\S]*?)(?:```|\Z)']js_patterns = [r'```javascript\s*\n([\s\S]*?)(?:```|\Z)',r'```js\s*\n([\s\S]*?)(?:```|\Z)',r'```\s*(?:index\.js|javascript|js)\s*\n([\s\S]*?)(?:```|\Z)']css_patterns = [r'```css\s*\n([\s\S]*?)(?:```|\Z)',r'```\s*(?:style\.css|css)\s*\n([\s\S]*?)(?:```|\Z)']# Extract HTML contentfor pattern in html_patterns:html_match = re.search(pattern, code, re.IGNORECASE)if html_match:files['index.html'] = html_match.group(1).strip()break# Extract JavaScript contentfor pattern in js_patterns:js_match = re.search(pattern, code, re.IGNORECASE)if js_match:files['index.js'] = js_match.group(1).strip()break# Extract CSS contentfor pattern in css_patterns:css_match = re.search(pattern, code, re.IGNORECASE)if css_match:files['style.css'] = css_match.group(1).strip()break# Fallback: support === index.html === format if any file is missingif not (files['index.html'] and files['index.js'] and files['style.css']):# Use regex to extract sectionshtml_fallback = re.search(r'===\s*index\.html\s*===\s*\n([\s\S]+?)(?=\n===|$)', code, re.IGNORECASE)js_fallback = re.search(r'===\s*index\.js\s*===\s*\n([\s\S]+?)(?=\n===|$)', code, re.IGNORECASE)css_fallback = re.search(r'===\s*style\.css\s*===\s*\n([\s\S]+?)(?=\n===|$)', code, re.IGNORECASE)if html_fallback:files['index.html'] = html_fallback.group(1).strip()if js_fallback:files['index.js'] = js_fallback.group(1).strip()if css_fallback:files['style.css'] = css_fallback.group(1).strip()# Additional fallback: extract from numbered sections or file headersif not (files['index.html'] and files['index.js'] and files['style.css']):# Try patterns like "1. index.html:" or "**index.html**"patterns = [(r'(?:^\d+\.\s*|^##\s*|^\*\*\s*)index\.html(?:\s*:|\*\*:?)\s*\n([\s\S]+?)(?=\n(?:\d+\.|##|\*\*|===)|$)', 'index.html'),(r'(?:^\d+\.\s*|^##\s*|^\*\*\s*)index\.js(?:\s*:|\*\*:?)\s*\n([\s\S]+?)(?=\n(?:\d+\.|##|\*\*|===)|$)', 'index.js'),(r'(?:^\d+\.\s*|^##\s*|^\*\*\s*)style\.css(?:\s*:|\*\*:?)\s*\n([\s\S]+?)(?=\n(?:\d+\.|##|\*\*|===)|$)', 'style.css')]for pattern, file_key in patterns:if not files[file_key]:match = re.search(pattern, code, re.IGNORECASE | re.MULTILINE)if match:# Clean up the content by removing any code block markerscontent = match.group(1).strip()content = re.sub(r'^```\w*\s*\n', '', content)content = re.sub(r'\n```\s*$', '', content)files[file_key] = content.strip()return files270 unmodified linesfiles = parse_transformers_js_output(code)print(f"[Deploy] Parsed transformers.js files: {list(files.keys())}")# Log file sizes for debuggingfor fname, fcontent in files.items():if fcontent:print(f"[Deploy] {fname}: {len(fcontent)} characters")else:print(f"[Deploy] {fname}: EMPTY")# Validate all three files are presentmissing_files = []if not files.get('index.html'):17 unmodified linesprint(f"[Deploy] {error_msg}")return False, error_msg, None# Write transformers.js files to temp directoryfor filename, content in files.items():file_path = temp_path / filenameprint(f"[Deploy] Writing {filename} ({len(content)} chars) to {file_path}")file_path.write_text(content, encoding='utf-8')# Verify the write was successfulwritten_size = file_path.stat().st_sizeprint(f"[Deploy] Verified {filename}: {written_size} bytes on disk")# For transformers.js, we'll upload files individually (not via upload_folder)use_individual_uploads = True199 unmodified linestemp_file_path = Nonetry:# Create a NEW temp file for this upload (key difference from old approach)print(f"[Deploy] Creating temp file for {file_name} with {len(file_content)} chars")with tempfile.NamedTemporaryFile("w", suffix=f".{file_name.split('.')[-1]}", delete=False, encoding='utf-8') as f:f.write(file_content)f.flush() # Ensure all content is written to disk before closingtemp_file_path = f.name# File is now closed and flushed, safe to upload# Verify temp file size before uploadimport os as _ostemp_size = _os.path.getsize(temp_file_path)print(f"[Deploy] Temp file {file_name} size on disk: {temp_size} bytes (expected ~{len(file_content)} chars)")# Upload the file without commit_message (HF handles this for spaces)api.upload_file(path_or_fileobj=temp_file_path,
backend_deploy.py+94-45