[Python] How can I improve this Python function? [closed]

Discussão em 'Python' iniciado por Stack, Maio 9, 2025.

  1. Stack

    Stack Membro Participativo

    I’ve written a program and would love your feedback. If you find any issues, please let me know so I can fix them. Thanks! I work in Iran, thank you for solving my problem, I am trying very hard

    If there is a problem with this code somewhere, tell me to fix it, or if you fix it, send it to me, it will be very good for me.

    If you have an idea, tell me, guide me so that I can take this path, I'm 22 years old, I would love to improve, and become strong like you

    Code:

    from diffusers import StableVideoDiffusionPipeline
    import torch
    from PIL import Image
    import imageio
    import argparse
    from pathlib import Path
    from tqdm import tqdm
    import logging

    # تنظیمات لاگ
    logging.basicConfig(level=logging.INFO)
    logger = logging.getLogger(__name__)

    def validate_image(image_path):
    """اعتبارسنجی و بارگذاری تصویر ورودی"""
    try:
    img = Image.open(image_path)
    if img.mode != 'RGB':
    img = img.convert('RGB')
    logger.info(f"تصویر با موفقیت بارگذاری شد: {image_path}")
    return img
    except Exception as e:
    logger.error(f"خطا در بارگذاری تصویر: {str(e)}")
    return None

    def generate_video(
    input_image,
    output_path="output_video.mp4",
    duration=10,
    fps=24,
    width=1024,
    height=576,
    motion_bucket_id=120,
    noise_aug_strength=0.02,
    device="cuda",
    output_format="mp4",
    quality=90
    ):
    """تابع اصلی برای تولید ویدیو از تصویر"""

    # 1. بارگذاری مدل
    try:
    logger.info("در حال بارگذاری مدل هوش مصنوعی...")
    torch_dtype = torch.float32 if device == "cpu" else torch.float16
    pipe = StableVideoDiffusionPipeline.from_pretrained(
    "stabilityai/stable-video-diffusion-img2vid-xt",
    torch_dtype=torch_dtype,
    variant="fp16"
    ).to(device)
    pipe.enable_model_cpu_offload()
    logger.info("مدل با موفقیت بارگذاری شد")
    except Exception as e:
    logger.error(f"خطا در بارگذاری مدل: {str(e)}")
    return False

    # 2. پردازش تصویر ورودی
    try:
    logger.info("در حال پردازش تصویر ورودی...")
    image = input_image.resize((width, height))
    except Exception as e:
    logger.error(f"خطا در پردازش تصویر: {str(e)}")
    return False

    # 3. تولید فریم‌ها
    try:
    logger.info(f"در حال تولید {duration} ثانیه ویدیو با {fps} فریم بر ثانیه...")
    frames = pipe(
    image,
    decode_chunk_size=4,
    motion_bucket_id=motion_bucket_id,
    noise_aug_strength=noise_aug_strength,
    num_frames=fps * duration,
    ).frames[0]
    logger.info(f"تولید {len(frames)} فریم با موفقیت انجام شد")
    except Exception as e:
    logger.error(f"خطا در تولید ویدیو: {str(e)}")
    return False

    # 4. ذخیره ویدیو
    try:
    logger.info(f"در حال ذخیره ویدیو با فرمت {output_format}...")
    if output_format == 'gif':
    imageio.mimsave(
    output_path,
    frames,
    fps=fps,
    quality=quality,
    subrectangles=True
    )
    else:
    with imageio.get_writer(
    output_path,
    fps=fps,
    codec='libx264',
    ffmpeg_params=[f'-crf', str(quality)]
    ) as writer:
    for frame in tqdm(frames, desc="ذخیره فریم‌ها"):
    writer.append_data(frame)
    logger.info(f"ویدیو با موفقیت در {output_path} ذخیره شد")
    except Exception as e:
    logger.error(f"خطا در ذخیره ویدیو: {str(e)}")
    return False

    return True

    if __name__ == "__main__":
    # تنظیمات خط فرمان
    parser = argparse.ArgumentParser(
    description='تبدیل عکس به ویدیو با هوش مصنوعی - نسخه حرفه‌ای',
    formatter_class=argparse.ArgumentDefaultsHelpFormatter
    )
    parser.add_argument(
    'input',
    help='مسیر تصویر ورودی (فرمت‌های JPG, PNG, etc.)'
    )
    parser.add_argument(
    '-o', '--output',
    default='output_video.mp4',
    help='مسیر ویدیوی خروجی'
    )
    parser.add_argument(
    '-d', '--duration',
    type=int,
    default=10,
    help='مدت ویدیو (ثانیه)'
    )
    parser.add_argument(
    '--fps',
    type=int,
    default=24,
    help='فریم بر ثانیه'
    )
    parser.add_argument(
    '--width',
    type=int,
    default=1024,
    help='عرض ویدیو (پیکسل)'
    )
    parser.add_argument(
    '--height',
    type=int,
    default=576,
    help='ارتفاع ویدیو (پیکسل)'
    )
    parser.add_argument(
    '--motion',
    type=int,
    default=120,
    help='میزان حرکت (80-200)'
    )
    parser.add_argument(
    '--noise',
    type=float,
    default=0.02,
    help='میزان تغییرات (0.01-0.2)'
    )
    parser.add_argument(
    '--cpu',
    action='store_true',
    help='استفاده از CPU به جای GPU'
    )
    parser.add_argument(
    '--format',
    default='mp4',
    choices=['mp4', 'gif'],
    help='فرمت خروجی ویدیو'
    )
    parser.add_argument(
    '--quality',
    type=int,
    default=90,
    help='کیفیت ویدیو (0-100)'
    )
    parser.add_argument(
    '--debug',
    action='store_true',
    help='نمایش اطلاعات دیباگ'
    )

    args = parser.parse_args()

    # تنظیم سطح لاگ
    if args.debug:
    logger.setLevel(logging.DEBUG)
    else:
    logger.setLevel(logging.INFO)

    # اعتبارسنجی ورودی‌ها
    if args.duration <= 0:
    logger.error("مدت ویدیو باید بیشتر از 0 باشد")
    exit(1)

    if not Path(args.input).exists():
    logger.error(f"فایل ورودی {args.input} یافت نشد")
    exit(1)

    if args.quality < 0 or args.quality > 100:
    logger.error("کیفیت باید بین 0 تا 100 باشد")
    exit(1)

    # اعتبارسنجی فرمت تصویر
    valid_extensions = ['.jpg', '.jpeg', '.png']
    if Path(args.input).suffix.lower() not in valid_extensions:
    logger.error(f"فرمت تصویر ورودی معتبر نیست. فرمت‌های مجاز: {', '.join(valid_extensions)}")
    exit(1)

    # انتخاب دستگاه پردازش
    device = "cpu" if args.cpu else "cuda" if torch.cuda.is_available() else "cpu"
    logger.info(f"استفاده از {device.upper()} برای پردازش")

    if not torch.cuda.is_available() and not args.cpu:
    logger.warning("هشدار: GPU در دسترس نیست. پردازش ممکن است بسیار کند باشد.")

    # بارگذاری و اعتبارسنجی تصویر
    image = validate_image(args.input)
    if not image:
    exit(1)

    # تولید ویدیو
    success = generate_video(
    input_image=image,
    output_path=args.output,
    duration=args.duration,
    fps=args.fps,
    width=args.width,
    height=args.height,
    motion_bucket_id=args.motion,
    noise_aug_strength=args.noise,
    device=device,
    output_format=args.format,
    quality=args.quality
    )

    if success:
    logger.info(f"✅ ویدیو با موفقیت در {args.output} ذخیره شد!")
    logger.info(f" مدت: {args.duration} ثانیه")
    logger.info(f" فریم ریت: {args.fps} FPS")
    logger.info(f" ابعاد: {args.width}x{args.height}")
    logger.info(f" فرمت: {args.format.upper()}")
    logger.info(f" کیفیت: {args.quality}%")
    else:
    logger.error("❌ خطا در تولید ویدیو")
    exit(1)

    Continue reading...

Compartilhe esta Página