Upload 2 files
Browse files10 unmodified lines1112131415161718192010 unmodified lines# 3D Figure Render StudioUpload an OBJ file, optionally with its MTL and texture files, then render a studio-style image or a black model with yellow wireframe topology.- Blender is installed through `packages.txt`.- Output resolution is at least 2000 × 2000.- The CPU render button runs without requesting ZeroGPU. The GPU render button is decorated with `@spaces.GPU(duration=120)` and requests ZeroGPU quota.- Cycles supports CPU rendering; GPU rendering is available only when the Space's Blender build and hardware expose a supported backend (CUDA/OptiX/HIP/oneAPI/Metal).- Eevee is a real-time rasterizer and may require a working GPU/graphics context on the Space host.10 unmodified lines11121314151617181920212210 unmodified lines# 3D Figure Render StudioUpload an OBJ file, optionally with its MTL and texture files, choose one camera angle, then render one studio-style image or a black model with yellow wireframe topology. The app automatically centers and frames the model based on its geometry bounds; it does not render extra views.- Blender is installed through `packages.txt`.- Output resolution is at least 2000 × 2000.- Camera presets: front, back, left, right, diagonal, or a manually selected angle. Exactly one image is rendered per run.- The mesh is centered from its actual vertex bounds, normalized proportionally, and the orthographic camera framing is fitted to the projected model bounds for the selected angle.- The CPU render button runs without requesting ZeroGPU. The GPU render button is decorated with `@spaces.GPU(duration=120)` and requests ZeroGPU quota.- Cycles supports CPU rendering; GPU rendering is available only when the Space's Blender build and hardware expose a supported backend (CUDA/OptiX/HIP/oneAPI/Metal).- Eevee is a real-time rasterizer and may require a working GPU/graphics context on the Space host.
21 unmodified lines2223242526272829303132333435363738394034 unmodified lines7576777879808182838485865 unmodified lines929394959697983 unmodified lines1021031041051061071 unmodified line1091101111121131141151161171181191201211228 unmodified lines1311321331341351361371382 unmodified lines14114214314414514614721 unmodified linesbpy.context.view_layer.objects.active=meshes[0]if len(meshes)>1:bpy.ops.object.join()obj=bpy.context.view_layer.objects.active; obj.name="Figure"# Smooth shading improves the appearance without changing mesh geometry.if a.smooth == "1":for poly in obj.data.polygons: poly.use_smooth=True# Optional subdivision is deliberately conservative; it can soften tiny sculpt details.if a.subdivision in ("1","2"):sub=obj.modifiers.new("Optional surface subdivision", "SUBSURF"); sub.subdivision_type="CATMULL_CLARK"; sub.levels=int(a.subdivision); sub.render_levels=int(a.subdivision)bpy.context.view_layer.update()corners=[obj.matrix_world@Vector(c) for c in obj.bound_box]mn=Vector((min(v.x for v in corners),min(v.y for v in corners),min(v.z for v in corners))); mx=Vector((max(v.x for v in corners),max(v.y for v in corners),max(v.z for v in corners)))obj.location-=(mn+mx)/2; bpy.context.view_layer.update()corners=[obj.matrix_world@Vector(c) for c in obj.bound_box]extent=max(max(v.x for v in corners)-min(v.x for v in corners),max(v.y for v in corners)-min(v.y for v in corners),max(v.z for v in corners)-min(v.z for v in corners),.001)obj.scale*=2.2/extentscene=bpy.context.scene; scene.render.engine="CYCLES" if a.engine=="Cycles" else ("BLENDER_EEVEE_NEXT" if "BLENDER_EEVEE_NEXT" in bpy.types.RenderSettings.bl_rna.properties["engine"].enum_items.keys() else "BLENDER_EEVEE")scene.render.resolution_x=int(a.resolution); scene.render.resolution_y=int(a.resolution); scene.render.resolution_percentage=100scene.render.image_settings.file_format="PNG"; scene.render.image_settings.color_mode="RGBA" if a.transparent=="1" else "RGB"; scene.render.film_transparent=(a.transparent=="1")34 unmodified lines}world_bg, floor_color, lights = styles.get(a.style, styles["Studio Teal"])world.node_tree.nodes["Background"].inputs["Color"].default_value=(.006,.008,.012,1) if wire else world_bg; world.node_tree.nodes["Background"].inputs["Strength"].default_value=.35if not wire:bpy.ops.mesh.primitive_plane_add(size=200,location=(0,0,-1.16)); floor=bpy.context.object; fm=bpy.data.materials.new("Teal studio"); fm.use_nodes=Truefm.node_tree.nodes["Principled BSDF"].inputs["Base Color"].default_value=floor_color; fm.node_tree.nodes["Principled BSDF"].inputs["Roughness"].default_value=.42; floor.data.materials.append(fm)target=Vector((0,0,0)); az=math.radians(float(a.azimuth)); el=math.radians(float(a.elevation)); dist=4.6bpy.ops.object.camera_add(location=(dist*math.cos(el)*math.cos(az),dist*math.cos(el)*math.sin(az),dist*math.sin(el)))cam=bpy.context.object; cam.data.type="ORTHO"; cam.data.ortho_scale=3.05; cam.rotation_euler=(target-cam.location).to_track_quat("-Z","Y").to_euler(); scene.camera=camdef area(name,loc,energy,size,color):bpy.ops.object.light_add(type="AREA",location=loc); l=bpy.context.object; l.name=name; l.data.energy=energy; l.data.shape="DISK"; l.data.size=size; l.data.color=color; l.rotation_euler=(target-l.location).to_track_quat("-Z","Y").to_euler()for light_data in lights: area(*light_data)5 unmodified linesscene.render.filepath=a.out; bpy.ops.render.render(write_still=True)'''def _render_model(files, mode, engine, device, resolution, samples, azimuth, elevation, transparent, style, smooth, subdivision):if not files: raise gr.Error("Загрузите OBJ и при необходимости MTL/текстуры.")paths=[Path(f.name if hasattr(f,"name") else str(f)) for f in files]source=next((p for p in paths if p.suffix.lower()==".obj"),None)3 unmodified linesjob=OUT/uuid.uuid4().hex[:10]; job.mkdir(parents=True)for p in paths: shutil.copy2(p,job/p.name)obj=job/source.name; resolution=max(2000,int(resolution)); output=job/("wireframe.png" if mode.startswith("Wireframe") else "beauty.png")script=job/"render_scene.py"; script.write_text(BLENDER_SCRIPT,encoding="utf-8")cmd=[blender,"-b","--python",str(script),"--","--obj",str(obj),"--out",str(output),"--mode",mode,"--engine",engine,"--device",device,"--resolution",str(resolution),"--samples",str(int(samples)),"--azimuth",str(float(azimuth)),"--elevation",str(float(elevation)),"--transparent","1" if transparent else "0","--style",style,"--smooth","1" if smooth else "0","--subdivision",str(subdivision)]try: proc=subprocess.run(cmd,capture_output=True,text=True,timeout=1800)1 unmodified lineif proc.returncode or not output.exists(): raise gr.Error("Blender не смог выполнить рендер:\n"+(proc.stderr+"\n"+proc.stdout)[-3000:])return str(output),str(output),f"Готово · {resolution}×{resolution} · {engine} · {device}"def render_cpu(files, mode, engine, resolution, samples, azimuth, elevation, transparent, style, smooth, subdivision):return _render_model(files, mode, engine, "CPU", resolution, samples, azimuth, elevation, transparent, style, smooth, subdivision)@spaces.GPU(duration=120)def render_gpu(files, mode, engine, resolution, samples, azimuth, elevation, transparent, style, smooth, subdivision):if engine != "Cycles":raise gr.Error("Выбор GPU доступен только для Cycles. Для Eevee выберите CPU или переключите рендерер на Cycles.")return _render_model(files, mode, engine, "GPU", resolution, samples, azimuth, elevation, transparent, style, smooth, subdivision)with gr.Blocks(title="3D Figure Render Studio",theme=gr.themes.Soft()) as demo:gr.Markdown("# 3D Figure Render Studio\nЗагрузи OBJ, настрой студийный свет и сохрани PNG. Для OBJ с материалами загрузи также MTL и текстуры одним набором файлов. GPU-рендер использует ZeroGPU-квоту.")8 unmodified linesstyle=gr.Dropdown(["Studio Teal","Neutral Product","Sunset Orange","Bright Summer","Cyberpunk Neon"],value="Studio Teal",label="Стиль освещения")smooth=gr.Checkbox(value=True,label="Гладкое затенение (без изменения геометрии)")subdivision=gr.Radio(["0","1","2"],value="0",label="Subdivision поверхности (0 = выкл.)",info="Подразделение может смягчить или уменьшить мелкие детали. Начни с 0; при необходимости попробуй 1.")azimuth=gr.Slider(-180,180,value=-55,step=5,label="Азимут камеры")elevation=gr.Slider(-10,80,value=20,step=5,label="Высота камеры")transparent=gr.Checkbox(value=False,label="Прозрачный фон (без студийного пола)")run_cpu=gr.Button("Рендерить на CPU",variant="primary",visible=True)run_gpu=gr.Button("Рендерить на GPU (ZeroGPU)",variant="primary",visible=False)2 unmodified linesdownload=gr.File(label="Скачать PNG")status=gr.Markdown()device.change(lambda d: (gr.update(visible=d=="CPU"), gr.update(visible=d=="GPU")), inputs=device, outputs=[run_cpu,run_gpu])inputs=[files,mode,engine,resolution,samples,azimuth,elevation,transparent,style,smooth,subdivision]outputs=[preview,download,status]run_cpu.click(render_cpu,inputs=inputs,outputs=outputs)run_gpu.click(render_gpu,inputs=inputs,outputs=outputs)21 unmodified lines2223242526272829303132333435363738394041424344454647484950515234 unmodified lines878889909192939495969798991001011021031041051061071081091105 unmodified lines1161171181191201211223 unmodified lines1261271281291301311321331341 unmodified line1361371381391401411421431441451461471481498 unmodified lines1581591601611621631641651662 unmodified lines16917017117217317417521 unmodified linesbpy.context.view_layer.objects.active=meshes[0]if len(meshes)>1:bpy.ops.object.join()obj=bpy.context.view_layer.objects.active; obj.name="Figure"# Bake imported object transforms into the mesh first. This makes centering# reliable even when the OBJ has an offset origin or non-applied transforms.bpy.ops.object.transform_apply(location=True, rotation=True, scale=True)# Smooth shading improves the appearance without changing mesh geometry.if a.smooth == "1":for poly in obj.data.polygons: poly.use_smooth=True# Optional subdivision is deliberately conservative; it can soften tiny sculpt details.if a.subdivision in ("1","2"):sub=obj.modifiers.new("Optional surface subdivision", "SUBSURF"); sub.subdivision_type="CATMULL_CLARK"; sub.levels=int(a.subdivision); sub.render_levels=int(a.subdivision)# Find the true geometry bounds in mesh-local coordinates, move the geometry# itself to the origin, then normalize its largest dimension without changing# the aspect ratio. This avoids origin/pivot offsets shifting the figure.coords=[v.co.copy() for v in obj.data.vertices]if not coords: raise RuntimeError("В OBJ нет вершин")mn=Vector((min(v.x for v in coords),min(v.y for v in coords),min(v.z for v in coords)))mx=Vector((max(v.x for v in coords),max(v.y for v in coords),max(v.z for v in coords)))center=(mn+mx)*0.5extent=max(mx.x-mn.x,mx.y-mn.y,mx.z-mn.z,0.001)normal_scale=2.2/extentfor v in obj.data.vertices:v.co=(v.co-center)*normal_scaleobj.data.update(); bpy.context.view_layer.update()# Re-read bounds after normalization; the floor is placed just below the model.corners=[Vector(c) for c in obj.bound_box]min_z=min(v.z for v in corners); max_z=max(v.z for v in corners)scene=bpy.context.scene; scene.render.engine="CYCLES" if a.engine=="Cycles" else ("BLENDER_EEVEE_NEXT" if "BLENDER_EEVEE_NEXT" in bpy.types.RenderSettings.bl_rna.properties["engine"].enum_items.keys() else "BLENDER_EEVEE")scene.render.resolution_x=int(a.resolution); scene.render.resolution_y=int(a.resolution); scene.render.resolution_percentage=100scene.render.image_settings.file_format="PNG"; scene.render.image_settings.color_mode="RGBA" if a.transparent=="1" else "RGB"; scene.render.film_transparent=(a.transparent=="1")34 unmodified lines}world_bg, floor_color, lights = styles.get(a.style, styles["Studio Teal"])world.node_tree.nodes["Background"].inputs["Color"].default_value=(.006,.008,.012,1) if wire else world_bg; world.node_tree.nodes["Background"].inputs["Strength"].default_value=.35if not wire and a.transparent!="1":bpy.ops.mesh.primitive_plane_add(size=200,location=(0,0,min_z-0.035)); floor=bpy.context.object; fm=bpy.data.materials.new("Teal studio"); fm.use_nodes=Truefm.node_tree.nodes["Principled BSDF"].inputs["Base Color"].default_value=floor_color; fm.node_tree.nodes["Principled BSDF"].inputs["Roughness"].default_value=.42; floor.data.materials.append(fm)target=Vector((0,0,0)); az=math.radians(float(a.azimuth)); el=math.radians(float(a.elevation))# Camera distance is derived from the normalized model size. The orthographic# framing is then calculated from the model's projected width AND height for# this exact viewing angle, so front/side/diagonal views all fit automatically.model_radius=max((Vector(c).length for c in obj.bound_box), default=1.1)dist=max(model_radius*3.0, 3.5)cam_location=Vector((dist*math.cos(el)*math.cos(az),dist*math.cos(el)*math.sin(az),dist*math.sin(el)))bpy.ops.object.camera_add(location=cam_location)cam=bpy.context.object; cam.data.type="ORTHO"; cam.rotation_euler=(target-cam.location).to_track_quat("-Z","Y").to_euler(); scene.camera=cambpy.context.view_layer.update()inv_cam=cam.matrix_world.inverted()projected=[inv_cam @ (obj.matrix_world @ Vector(c)) for c in obj.bound_box]proj_w=max(v.x for v in projected)-min(v.x for v in projected)proj_h=max(v.y for v in projected)-min(v.y for v in projected)cam.data.ortho_scale=max(proj_w,proj_h,0.01)*1.16def area(name,loc,energy,size,color):bpy.ops.object.light_add(type="AREA",location=loc); l=bpy.context.object; l.name=name; l.data.energy=energy; l.data.shape="DISK"; l.data.size=size; l.data.color=color; l.rotation_euler=(target-l.location).to_track_quat("-Z","Y").to_euler()for light_data in lights: area(*light_data)5 unmodified linesscene.render.filepath=a.out; bpy.ops.render.render(write_still=True)'''def _render_model(files, mode, engine, device, resolution, samples, view, azimuth, elevation, transparent, style, smooth, subdivision):if not files: raise gr.Error("Загрузите OBJ и при необходимости MTL/текстуры.")paths=[Path(f.name if hasattr(f,"name") else str(f)) for f in files]source=next((p for p in paths if p.suffix.lower()==".obj"),None)3 unmodified linesjob=OUT/uuid.uuid4().hex[:10]; job.mkdir(parents=True)for p in paths: shutil.copy2(p,job/p.name)obj=job/source.name; resolution=max(2000,int(resolution)); output=job/("wireframe.png" if mode.startswith("Wireframe") else "beauty.png")preset_angles={"Спереди":(-90,0),"Сзади":(90,0),"Слева":(180,0),"Справа":(0,0)}if view in preset_angles:azimuth,elevation=preset_angles[view]script=job/"render_scene.py"; script.write_text(BLENDER_SCRIPT,encoding="utf-8")cmd=[blender,"-b","--python",str(script),"--","--obj",str(obj),"--out",str(output),"--mode",mode,"--engine",engine,"--device",device,"--resolution",str(resolution),"--samples",str(int(samples)),"--azimuth",str(float(azimuth)),"--elevation",str(float(elevation)),"--transparent","1" if transparent else "0","--style",style,"--smooth","1" if smooth else "0","--subdivision",str(subdivision)]try: proc=subprocess.run(cmd,capture_output=True,text=True,timeout=1800)1 unmodified lineif proc.returncode or not output.exists(): raise gr.Error("Blender не смог выполнить рендер:\n"+(proc.stderr+"\n"+proc.stdout)[-3000:])return str(output),str(output),f"Готово · {resolution}×{resolution} · {engine} · {device}"def render_cpu(files, mode, engine, resolution, samples, view, azimuth, elevation, transparent, style, smooth, subdivision):return _render_model(files, mode, engine, "CPU", resolution, samples, view, azimuth, elevation, transparent, style, smooth, subdivision)@spaces.GPU(duration=120)def render_gpu(files, mode, engine, resolution, samples, view, azimuth, elevation, transparent, style, smooth, subdivision):if engine != "Cycles":raise gr.Error("Выбор GPU доступен только для Cycles. Для Eevee выберите CPU или переключите рендерер на Cycles.")return _render_model(files, mode, engine, "GPU", resolution, samples, view, azimuth, elevation, transparent, style, smooth, subdivision)with gr.Blocks(title="3D Figure Render Studio",theme=gr.themes.Soft()) as demo:gr.Markdown("# 3D Figure Render Studio\nЗагрузи OBJ, настрой студийный свет и сохрани PNG. Для OBJ с материалами загрузи также MTL и текстуры одним набором файлов. GPU-рендер использует ZeroGPU-квоту.")8 unmodified linesstyle=gr.Dropdown(["Studio Teal","Neutral Product","Sunset Orange","Bright Summer","Cyberpunk Neon"],value="Studio Teal",label="Стиль освещения")smooth=gr.Checkbox(value=True,label="Гладкое затенение (без изменения геометрии)")subdivision=gr.Radio(["0","1","2"],value="0",label="Subdivision поверхности (0 = выкл.)",info="Подразделение может смягчить или уменьшить мелкие детали. Начни с 0; при необходимости попробуй 1.")view=gr.Dropdown(["Под углом","Спереди","Сзади","Слева","Справа","Свободный угол"],value="Под углом",label="Ракурс одного рендера",info="За один запуск создаётся только один выбранный кадр.")azimuth=gr.Slider(-180,180,value=-55,step=5,label="Азимут камеры (для свободного угла)")elevation=gr.Slider(-10,80,value=20,step=5,label="Высота камеры (для свободного угла)")transparent=gr.Checkbox(value=False,label="Прозрачный фон (без студийного пола)")run_cpu=gr.Button("Рендерить на CPU",variant="primary",visible=True)run_gpu=gr.Button("Рендерить на GPU (ZeroGPU)",variant="primary",visible=False)2 unmodified linesdownload=gr.File(label="Скачать PNG")status=gr.Markdown()device.change(lambda d: (gr.update(visible=d=="CPU"), gr.update(visible=d=="GPU")), inputs=device, outputs=[run_cpu,run_gpu])inputs=[files,mode,engine,resolution,samples,view,azimuth,elevation,transparent,style,smooth,subdivision]outputs=[preview,download,status]run_cpu.click(render_cpu,inputs=inputs,outputs=outputs)run_gpu.click(render_gpu,inputs=inputs,outputs=outputs)
README.md+3-1
app.py+48-20