retromarz commited on
Commit
b4b2465
·
verified ·
1 Parent(s): 2af4a1b

Use huggingface_hub for pushing captions.json to Space repo;

Browse files
Files changed (2) hide show
  1. app.py +59 -17
  2. requirements.txt +2 -1
app.py CHANGED
@@ -5,32 +5,52 @@ import json
5
  import uuid
6
  import os
7
  from PIL import Image
8
- from transformers import AutoProcessor, AutoModelForCausalLM
 
9
 
10
  # Configure logging
11
  logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
12
  logger = logging.getLogger(__name__)
13
 
14
  # Define output JSON path
15
- OUTPUT_JSON_PATH = "captions.json"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
16
 
17
  # Initialize model and processor
18
  try:
19
  processor = AutoProcessor.from_pretrained("microsoft/git-large-coco")
20
- model = AutoModelForCausalLM.from_pretrained("microsoft/git-large-coco").to("cuda" if torch.cuda.is_available() else "cpu")
 
21
  logger.info("Model and processor loaded successfully")
22
  except Exception as e:
23
  logger.error(f"Failed to load model or processor: {str(e)}")
24
  raise
25
 
26
- # Ensure output JSON file exists
27
- if not os.path.exists(OUTPUT_JSON_PATH):
28
- with open(OUTPUT_JSON_PATH, 'w') as f:
29
- json.dump([], f)
30
-
31
- # Function to save results to JSON
32
  def save_to_json(image_name: str, caption: str, caption_type: str, caption_length: str, error: str = None):
33
  try:
 
34
  with open(OUTPUT_JSON_PATH, 'r+') as f:
35
  data = json.load(f)
36
  data.append({
@@ -44,31 +64,50 @@ def save_to_json(image_name: str, caption: str, caption_type: str, caption_lengt
44
  f.seek(0)
45
  json.dump(data, f, indent=4)
46
  logger.info(f"Saved result to {OUTPUT_JSON_PATH}")
 
 
 
 
 
 
47
  except Exception as e:
48
- logger.error(f"Error writing to JSON file: {str(e)}")
49
 
50
  # Define the captioning function
51
  def generate_caption(input_image: Image, caption_type: str = "descriptive", caption_length: str = "medium", prompt: str = "") -> str:
 
52
  if input_image is None:
53
  error_msg = "Please upload an image."
 
 
 
 
 
 
54
  save_to_json("unknown", error_msg, caption_type, caption_length, error=error_msg)
55
  return error_msg
56
 
57
  # Generate a unique image name
58
  image_name = f"image_{uuid.uuid4().hex}.jpg"
 
59
 
60
  try:
61
- # Resize image to reduce memory usage
 
62
  input_image = input_image.resize((256, 256))
63
 
64
  # Prepare prompt
65
  if not prompt:
66
  prompt = f"Generate a {caption_type} caption for this image."
 
67
 
68
  # Prepare inputs
 
69
  inputs = processor(images=input_image, text=prompt, return_tensors="pt").to(model.device)
 
70
 
71
  # Generate the caption
 
72
  with torch.no_grad():
73
  max_length = {"short": 20, "medium": 50, "long": 100}.get(caption_length, 50)
74
  generated_ids = model.generate(
@@ -79,13 +118,16 @@ def generate_caption(input_image: Image, caption_type: str = "descriptive", capt
79
  )
80
 
81
  # Decode the output
 
82
  caption = processor.batch_decode(generated_ids, skip_special_tokens=True)[0].strip()
83
 
84
  # Clean up caption
85
  if caption.lower().startswith(("generate a", "write a")):
86
  caption = caption.split(".", 1)[1].strip() if "." in caption else caption
 
87
 
88
- # Save to JSON
 
89
  save_to_json(image_name, caption, caption_type, caption_length, error=None)
90
  return caption
91
  except Exception as e:
@@ -109,7 +151,7 @@ def view_caption_history():
109
  def batch_generate_captions(image_list, caption_type: str = "descriptive", caption_length: str = "medium", prompt: str = ""):
110
  results = []
111
  for img in image_list:
112
- # Convert file to PIL Image
113
  img_pil = Image.open(img.name).convert("RGB")
114
  caption = generate_caption(img_pil, caption_type, caption_length, prompt)
115
  results.append(f"Image {os.path.basename(img.name)}: {caption}")
@@ -118,7 +160,7 @@ def batch_generate_captions(image_list, caption_type: str = "descriptive", capti
118
  # Create Gradio Blocks interface
119
  with gr.Blocks(title="Image Captioning with GIT") as demo:
120
  gr.Markdown("# Image Captioning with GIT")
121
- gr.Markdown("Upload an image or multiple images to generate captions using the Microsoft/git-large-coco model. Results are saved to captions.json.")
122
 
123
  # Tab for single image captioning
124
  with gr.Tab("Single Image Captioning"):
@@ -129,7 +171,7 @@ with gr.Blocks(title="Image Captioning with GIT") as demo:
129
  single_caption_length = gr.Dropdown(choices=["short", "medium", "long"], label="Caption Length", value="medium")
130
  single_prompt = gr.Textbox(label="Prompt", placeholder="Enter a prompt for the model")
131
  single_submit = gr.Button("Generate Caption")
132
- single_output = gr.Textbox(label="Generated Caption")
133
  single_submit.click(
134
  fn=generate_caption,
135
  inputs=[single_image_input, single_caption_type, single_caption_length, single_prompt],
@@ -138,7 +180,7 @@ with gr.Blocks(title="Image Captioning with GIT") as demo:
138
 
139
  # Tab for viewing caption history
140
  with gr.Tab("Caption History"):
141
- history_output = gr.Textbox(label="Caption History")
142
  history_button = gr.Button("View History")
143
  history_button.click(
144
  fn=view_caption_history,
@@ -155,7 +197,7 @@ with gr.Blocks(title="Image Captioning with GIT") as demo:
155
  batch_caption_length = gr.Dropdown(choices=["short", "medium", "long"], label="Caption Length", value="medium")
156
  batch_prompt = gr.Textbox(label="Prompt", placeholder="Enter a prompt for the model")
157
  batch_submit = gr.Button("Generate Captions")
158
- batch_output = gr.Textbox(label="Batch Caption Results")
159
  batch_submit.click(
160
  fn=batch_generate_captions,
161
  inputs=[batch_image_input, batch_caption_type, batch_caption_length, batch_prompt],
 
5
  import uuid
6
  import os
7
  from PIL import Image
8
+ from transformers import AutoProcessor, AutoModelForCausalLM, BitsAndBytesConfig
9
+ from huggingface_hub import HfApi, Repository
10
 
11
  # Configure logging
12
  logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
13
  logger = logging.getLogger(__name__)
14
 
15
  # Define output JSON path
16
+ OUTPUT_DIR = "outputs"
17
+ OUTPUT_JSON_PATH = os.path.join(OUTPUT_DIR, "captions.json")
18
+
19
+ # Initialize Hugging Face API and repository
20
+ HF_TOKEN = os.environ.get("HF_TOKEN")
21
+ REPO_URL = "https://huggingface.co/spaces/retromarz/plavu_microsoft-git-large"
22
+ try:
23
+ os.makedirs(OUTPUT_DIR, exist_ok=True)
24
+ if not os.path.exists(OUTPUT_JSON_PATH):
25
+ with open(OUTPUT_JSON_PATH, 'w') as f:
26
+ json.dump([], f)
27
+ repo = Repository(
28
+ local_dir=".", # Use current directory (Space's repo root)
29
+ clone_from=REPO_URL,
30
+ use_auth_token=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,
31
+ git_user="retromarz",
32
+ git_email="ma@pnz.de"
33
+ )
34
+ repo.lfs_track([OUTPUT_JSON_PATH]) # Track large files if needed
35
+ logger.info("Hugging Face repository initialized")
36
+ except Exception as e:
37
+ logger.error(f"Failed to initialize repository: {str(e)}")
38
+ raise
39
 
40
  # Initialize model and processor
41
  try:
42
  processor = AutoProcessor.from_pretrained("microsoft/git-large-coco")
43
+ quantization_config = BitsAndBytesConfig(load_in_8bit=True) if torch.cuda.is_available() else None
44
+ model = AutoModelForCausalLM.from_pretrained("microsoft/git-large-coco", quantization_config=quantization_config).to("cuda" if torch.cuda.is_available() else "cpu")
45
  logger.info("Model and processor loaded successfully")
46
  except Exception as e:
47
  logger.error(f"Failed to load model or processor: {str(e)}")
48
  raise
49
 
50
+ # Function to save results to JSON and push to Git
 
 
 
 
 
51
  def save_to_json(image_name: str, caption: str, caption_type: str, caption_length: str, error: str = None):
52
  try:
53
+ # Write to local JSON
54
  with open(OUTPUT_JSON_PATH, 'r+') as f:
55
  data = json.load(f)
56
  data.append({
 
64
  f.seek(0)
65
  json.dump(data, f, indent=4)
66
  logger.info(f"Saved result to {OUTPUT_JSON_PATH}")
67
+
68
+ # Commit and push to Space repo
69
+ repo.git_add(OUTPUT_JSON_PATH)
70
+ repo.git_commit(f"Update captions.json with new caption for {image_name}")
71
+ repo.git_push()
72
+ logger.info("Pushed captions.json to Hugging Face Space repository")
73
  except Exception as e:
74
+ logger.error(f"Error saving to JSON or pushing to Git: {str(e)}")
75
 
76
  # Define the captioning function
77
  def generate_caption(input_image: Image, caption_type: str = "descriptive", caption_length: str = "medium", prompt: str = "") -> str:
78
+ logger.info("Starting generate_caption")
79
  if input_image is None:
80
  error_msg = "Please upload an image."
81
+ logger.error(error_msg)
82
+ save_to_json("unknown", error_msg, caption_type, caption_length, error=error_msg)
83
+ return error_msg
84
+ if not isinstance(input_image, Image.Image):
85
+ error_msg = "Invalid image format. Please upload a valid JPG or PNG image."
86
+ logger.error(error_msg)
87
  save_to_json("unknown", error_msg, caption_type, caption_length, error=error_msg)
88
  return error_msg
89
 
90
  # Generate a unique image name
91
  image_name = f"image_{uuid.uuid4().hex}.jpg"
92
+ logger.info(f"Generated image name: {image_name}")
93
 
94
  try:
95
+ # Resize image
96
+ logger.info("Resizing image")
97
  input_image = input_image.resize((256, 256))
98
 
99
  # Prepare prompt
100
  if not prompt:
101
  prompt = f"Generate a {caption_type} caption for this image."
102
+ logger.info(f"Prompt: {prompt}")
103
 
104
  # Prepare inputs
105
+ logger.info("Processing image with processor")
106
  inputs = processor(images=input_image, text=prompt, return_tensors="pt").to(model.device)
107
+ logger.info(f"Inputs prepared: {inputs.keys()}")
108
 
109
  # Generate the caption
110
+ logger.info("Generating caption")
111
  with torch.no_grad():
112
  max_length = {"short": 20, "medium": 50, "long": 100}.get(caption_length, 50)
113
  generated_ids = model.generate(
 
118
  )
119
 
120
  # Decode the output
121
+ logger.info("Decoding caption")
122
  caption = processor.batch_decode(generated_ids, skip_special_tokens=True)[0].strip()
123
 
124
  # Clean up caption
125
  if caption.lower().startswith(("generate a", "write a")):
126
  caption = caption.split(".", 1)[1].strip() if "." in caption else caption
127
+ logger.info(f"Generated caption: {caption}")
128
 
129
+ # Save to JSON and push to Git
130
+ logger.info("Saving to JSON")
131
  save_to_json(image_name, caption, caption_type, caption_length, error=None)
132
  return caption
133
  except Exception as e:
 
151
  def batch_generate_captions(image_list, caption_type: str = "descriptive", caption_length: str = "medium", prompt: str = ""):
152
  results = []
153
  for img in image_list:
154
+ logger.info(f"Processing batch image: {img.name}")
155
  img_pil = Image.open(img.name).convert("RGB")
156
  caption = generate_caption(img_pil, caption_type, caption_length, prompt)
157
  results.append(f"Image {os.path.basename(img.name)}: {caption}")
 
160
  # Create Gradio Blocks interface
161
  with gr.Blocks(title="Image Captioning with GIT") as demo:
162
  gr.Markdown("# Image Captioning with GIT")
163
+ gr.Markdown("Upload an image or multiple images to generate captions using the Microsoft/git-large-coco model. Results are saved to outputs/captions.json and pushed to the Git repository.")
164
 
165
  # Tab for single image captioning
166
  with gr.Tab("Single Image Captioning"):
 
171
  single_caption_length = gr.Dropdown(choices=["short", "medium", "long"], label="Caption Length", value="medium")
172
  single_prompt = gr.Textbox(label="Prompt", placeholder="Enter a prompt for the model")
173
  single_submit = gr.Button("Generate Caption")
174
+ single_output = gr.Textbox(label="Generated Caption", placeholder="Caption will appear here")
175
  single_submit.click(
176
  fn=generate_caption,
177
  inputs=[single_image_input, single_caption_type, single_caption_length, single_prompt],
 
180
 
181
  # Tab for viewing caption history
182
  with gr.Tab("Caption History"):
183
+ history_output = gr.Textbox(label="Caption History", placeholder="History will appear here")
184
  history_button = gr.Button("View History")
185
  history_button.click(
186
  fn=view_caption_history,
 
197
  batch_caption_length = gr.Dropdown(choices=["short", "medium", "long"], label="Caption Length", value="medium")
198
  batch_prompt = gr.Textbox(label="Prompt", placeholder="Enter a prompt for the model")
199
  batch_submit = gr.Button("Generate Captions")
200
+ batch_output = gr.Textbox(label="Batch Caption Results", placeholder="Batch results will appear here")
201
  batch_submit.click(
202
  fn=batch_generate_captions,
203
  inputs=[batch_image_input, batch_caption_type, batch_caption_length, batch_prompt],
requirements.txt CHANGED
@@ -2,4 +2,5 @@ gradio>=4.0.0
2
  transformers>=4.37.0
3
  torch>=2.0.0
4
  pillow>=9.0.0
5
- #bitsandbytes>=0.43.0
 
 
2
  transformers>=4.37.0
3
  torch>=2.0.0
4
  pillow>=9.0.0
5
+ bitsandbytes>=0.43.0
6
+ huggingface_hub>=0.23.0