import os, shutil, subprocess, tempfile, uuid from pathlib import Path import gradio as gr import spaces OUT = Path(tempfile.gettempdir()) / "figure_render_outputs" OUT.mkdir(exist_ok=True) BLENDER_SCRIPT = r'''import bpy, sys, math, argparse from mathutils import Vector args=sys.argv[sys.argv.index("--")+1:] p=argparse.ArgumentParser() for n in ["obj","out","mode","engine","device","resolution","samples","azimuth","elevation","transparent","style","smooth","subdivision"]: p.add_argument("--"+n,required=True) a=p.parse_args(args) bpy.ops.object.select_all(action="SELECT"); bpy.ops.object.delete(use_global=False) if hasattr(bpy.ops.wm,"obj_import"): bpy.ops.wm.obj_import(filepath=a.obj) else: bpy.ops.import_scene.obj(filepath=a.obj,use_split_objects=False,use_split_groups=False) meshes=[o for o in bpy.context.scene.objects if o.type=="MESH"] if not meshes: raise RuntimeError("OBJ не содержит mesh-геометрии") bpy.ops.object.select_all(action="DESELECT") for o in meshes:o.select_set(True) bpy.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.5 extent=max(mx.x-mn.x,mx.y-mn.y,mx.z-mn.z,0.001) normal_scale=2.2/extent for v in obj.data.vertices: v.co=(v.co-center)*normal_scale obj.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=100 scene.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") if a.engine=="Cycles": scene.cycles.samples=int(a.samples); scene.cycles.use_denoising=False; scene.cycles.device="CPU" # This Blender build may lack OpenImageDenoiser (OIDN) if a.device=="GPU": prefs=bpy.context.preferences.addons.get("cycles"); found=False if prefs: cp=prefs.preferences for backend in ("OPTIX","CUDA","HIP","ONEAPI","METAL"): try: cp.compute_device_type=backend; cp.get_devices(); devs=[d for d in cp.devices if d.type!="CPU"] if devs: for d in cp.devices:d.use=(d.type!="CPU") scene.cycles.device="GPU"; found=True; break except Exception:pass if not found:raise RuntimeError("GPU Cycles недоступен в этой сборке Blender. Выберите CPU.") else: scene.eevee.taa_render_samples=max(16,min(int(a.samples),256)) wire=a.mode.startswith("Wireframe") if wire: mat=bpy.data.materials.new("Black + yellow wireframe"); mat.use_nodes=True; nodes=mat.node_tree.nodes; links=mat.node_tree.links; nodes.clear() outn=nodes.new("ShaderNodeOutputMaterial"); bs=nodes.new("ShaderNodeBsdfPrincipled"); bs.inputs["Base Color"].default_value=(.003,.003,.003,1); bs.inputs["Roughness"].default_value=.85 wf=nodes.new("ShaderNodeWireframe"); wf.use_pixel_size=False; wf.inputs["Size"].default_value=.006 em=nodes.new("ShaderNodeEmission"); em.inputs["Color"].default_value=(1,.62,.01,1); em.inputs["Strength"].default_value=1.3 mix=nodes.new("ShaderNodeMixShader"); links.new(wf.outputs["Fac"],mix.inputs[0]); links.new(bs.outputs[0],mix.inputs[1]); links.new(em.outputs[0],mix.inputs[2]); links.new(mix.outputs[0],outn.inputs["Surface"]) obj.data.materials.clear(); obj.data.materials.append(mat) elif not obj.data.materials or all(m is None for m in obj.data.materials): mat=bpy.data.materials.new("Soft pink clay"); mat.use_nodes=True; bs=mat.node_tree.nodes.get("Principled BSDF"); bs.inputs["Base Color"].default_value=(.78,.48,.43,1); bs.inputs["Roughness"].default_value=.28 if "Subsurface Weight" in bs.inputs:bs.inputs["Subsurface Weight"].default_value=.06 obj.data.materials.clear(); obj.data.materials.append(mat) world=bpy.data.worlds.new("Studio World") if not scene.world else scene.world; scene.world=world; world.use_nodes=True styles={ "Studio Teal": ((.012,.12,.15,1),(.012,.28,.31,1),[("Key softbox",(-3.2,-4,4.2),520,4,(1,.78,.68)),("Fill",(4,-1.5,1.8),330,3.2,(.64,.82,1)),("Rim",(.5,3,3.5),650,2.8,(.55,.9,1))]), "Sunset Orange": ((.16,.045,.012,1),(.20,.065,.018,1),[("Sunset key",(-3,-4,3.8),650,2.4,(1,.30,.08)),("Warm fill",(4,-2,1.2),180,4,(1,.62,.28)),("Golden rim",(.5,3,3.4),850,2,(1,.22,.035))]), "Bright Summer": ((.20,.28,.34,1),(.24,.32,.36,1),[("Summer sun",(-3,-4,5),900,1.5,(1,.91,.76)),("Sky fill",(4,-1,2),450,4,(.66,.83,1)),("Back sunlight",(.5,3,4),700,2.5,(1,.94,.82))]), "Cyberpunk Neon": ((.018,.004,.045,1),(.025,.008,.045,1),[("Magenta neon",(-3,-3,2.5),600,2,(1,.015,.24)),("Cyan neon",(3,-1,1.8),650,2,(.01,.85,1)),("Violet rim",(.5,3,3.5),900,1.8,(.38,.03,1))]), "Neutral Product": ((.075,.075,.075,1),(.11,.11,.11,1),[("Large softbox",(-3,-4,4),650,4,(1,1,1)),("Fill",(4,-1.5,1.8),300,3.5,(.82,.88,1)),("Rim",(.5,3,3.5),500,2.8,(1,.9,.78))]) } 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=.35 if 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=True fm.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=cam bpy.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.16 def 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) # AgX is available in newer Blender versions; Blender 3.4 uses Filmic. view_items=scene.view_settings.bl_rna.properties["view_transform"].enum_items.keys() if "AgX" in view_items: scene.view_settings.view_transform="AgX" elif "Filmic" in view_items: scene.view_settings.view_transform="Filmic" else: scene.view_settings.view_transform="Standard" scene.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) if source is None: raise gr.Error("В загрузке должен быть файл .obj.") blender=shutil.which("blender") if not blender: raise gr.Error("Blender не установлен. Проверьте packages.txt и логи сборки Space.") job=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) except subprocess.TimeoutExpired: raise gr.Error("Превышен лимит рендера 30 минут. Уменьшите samples или выберите Eevee.") if 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-квоту.") with gr.Row(): with gr.Column(scale=1): files=gr.File(label="OBJ + MTL + текстуры",file_count="multiple",file_types=[".obj",".mtl",".png",".jpg",".jpeg",".tif",".tiff",".bmp"]) mode=gr.Radio(["Beauty Render — студийный свет","Wireframe — чёрная модель + жёлтая сетка"],value="Beauty Render — студийный свет",label="Режим") engine=gr.Radio(["Eevee","Cycles"],value="Cycles",label="Рендерер") device=gr.Radio(["CPU","GPU"],value="CPU",label="Устройство (GPU только для Cycles)") resolution=gr.Dropdown(["2000","2500","3000","4000"],value="2000",label="Разрешение (квадратное, px)") samples=gr.Slider(16,3000,value=256,step=16,label="Samples / качество (Cycles)",info="Больше Samples = меньше шума, но гораздо дольше рендер. 3000 — максимум, не рекомендуем для обычного CPU-рендера.") style=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) with gr.Column(scale=1): preview=gr.Image(label="Результат",type="filepath") download=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) demo.queue(default_concurrency_limit=1).launch()