angt HF Staff commited on
Commit
820f8a0
·
verified ·
1 Parent(s): ab6cbd0

Upload generate-image.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. generate-image.py +62 -0
generate-image.py ADDED
@@ -0,0 +1,62 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # /// script
2
+ # requires-python = ">=3.11"
3
+ # dependencies = [
4
+ # "huggingface-hub[hf_transfer]",
5
+ # "pillow",
6
+ # "torch",
7
+ # "diffusers",
8
+ # "accelerate",
9
+ # "transformers",
10
+ # "python-slugify",
11
+ # ]
12
+ #
13
+ # ///
14
+
15
+ import argparse
16
+ import os
17
+ import torch
18
+ from diffusers import AutoPipelineForText2Image
19
+ from huggingface_hub import HfApi, login
20
+ from slugify import slugify
21
+
22
+ def main(prompt: str, repo: str, hf_token: str = None):
23
+ HF_TOKEN = hf_token or os.environ.get("HF_TOKEN")
24
+
25
+ if HF_TOKEN:
26
+ login(token=HF_TOKEN)
27
+
28
+ name = slugify(prompt)
29
+ filename = f"{name}.png"
30
+ model_id = "stabilityai/stable-diffusion-xl-base-1.0"
31
+ api = HfApi()
32
+
33
+ print(f"Loading model: {model_id}...")
34
+ pipe = AutoPipelineForText2Image.from_pretrained(
35
+ model_id, torch_dtype=torch.float16, variant="fp16"
36
+ ).to("cuda")
37
+
38
+ print(f"Generating image for prompt: '{prompt}'...")
39
+ image = pipe(prompt=prompt).images[0]
40
+ temp_image_path = f"/tmp/{filename}"
41
+ image.save(temp_image_path)
42
+ print(f"Image saved temporarily to {temp_image_path}")
43
+
44
+ print(f"Uploading {filename} to dataset repository: {repo}...")
45
+ api.upload_file(
46
+ path_or_fileobj=temp_image_path,
47
+ path_in_repo=filename,
48
+ repo_id=repo,
49
+ repo_type="dataset",
50
+ commit_message=f"add {filename}"
51
+ )
52
+ repo_url = f"https://huggingface.co/datasets/{repo}/tree/main"
53
+ print(f"View it here: {repo_url}")
54
+
55
+
56
+ if __name__ == "__main__":
57
+ parser = argparse.ArgumentParser(description="Generate a single image using HF Jobs.")
58
+ parser.add_argument("--prompt", required=True, help="The text prompt to generate an image from.")
59
+ parser.add_argument("--repo", required=True, help="Your destination dataset repository ID.")
60
+ parser.add_argument("--hf-token", help="Hugging Face API token.")
61
+ args = parser.parse_args()
62
+ main(prompt=args.prompt, repo=args.repo, hf_token=args.hf_token)