ChandimaPrabath commited on
Commit
0c19cc1
1 Parent(s): 7a8d779

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +66 -41
app.py CHANGED
@@ -1,20 +1,18 @@
1
- import gradio as gr
2
  from transformers import AutoProcessor, AutoModelForCausalLM
3
- import spaces
4
  import re
5
  from PIL import Image
 
6
 
7
  # Install the necessary packages
8
- import subprocess
9
- subprocess.run('pip install flash-attn einops --no-build-isolation', env={'FLASH_ATTENTION_SKIP_CUDA_BUILD': "TRUE"}, shell=True)
10
 
11
- model = AutoModelForCausalLM.from_pretrained('gokaygokay/Florence-2-SD3-Captioner', trust_remote_code=True).eval()
12
 
 
13
  processor = AutoProcessor.from_pretrained('gokaygokay/Florence-2-SD3-Captioner', trust_remote_code=True)
14
 
15
- TITLE = "# [Florence-2 SD3 Long Captioner](https://huggingface.co/gokaygokay/Florence-2-SD3-Captioner/)"
16
- DESCRIPTION = "[Florence-2 Base](https://huggingface.co/microsoft/Florence-2-base-ft) fine-tuned on Long SD3 Prompt and Image pairs. Check above link for datasets that are used for fine-tuning."
17
-
18
  def modify_caption(caption: str) -> str:
19
  """
20
  Removes specific prefixes from captions if present, otherwise returns the original caption.
@@ -43,9 +41,62 @@ def modify_caption(caption: str) -> str:
43
  # If the caption was modified, return the modified version; otherwise, return the original
44
  return modified_caption if modified_caption != caption else caption
45
 
46
- @spaces.GPU
47
- def run_example(image):
48
- image = Image.fromarray(image)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
49
  task_prompt = "<DESCRIPTION>"
50
  prompt = task_prompt + "Describe this image in great detail."
51
 
@@ -62,35 +113,9 @@ def run_example(image):
62
  )
63
  generated_text = processor.batch_decode(generated_ids, skip_special_tokens=False)[0]
64
  parsed_answer = processor.post_process_generation(generated_text, task=task_prompt, image_size=(image.width, image.height))
65
- return modify_caption(parsed_answer["<DESCRIPTION>"])
66
-
67
- css = """
68
- #output {
69
- height: 500px;
70
- overflow: auto;
71
- border: 1px solid #ccc;
72
- }
73
- """
74
-
75
- with gr.Blocks(css=css) as demo:
76
- gr.Markdown(TITLE)
77
- gr.Markdown(DESCRIPTION)
78
- with gr.Tab(label="Florence-2 SD3 Prompts"):
79
- with gr.Row():
80
- with gr.Column():
81
- input_img = gr.Image(label="Input Picture")
82
- submit_btn = gr.Button(value="Submit")
83
- with gr.Column():
84
- output_text = gr.Textbox(label="Output Text")
85
-
86
- gr.Examples(
87
- [["image1.jpg"], ["image2.jpg"], ["image3.png"], ["image4.jpg"], ["image5.jpg"], ["image6.PNG"]],
88
- inputs = [input_img],
89
- outputs = [output_text],
90
- fn=run_example,
91
- label='Try captioning on below examples'
92
- )
93
 
94
- submit_btn.click(run_example, [input_img], [output_text])
95
 
96
- demo.launch(debug=True)
 
 
1
+ from flask import Flask, request, jsonify, render_template_string
2
  from transformers import AutoProcessor, AutoModelForCausalLM
3
+ import subprocess
4
  import re
5
  from PIL import Image
6
+ import io
7
 
8
  # Install the necessary packages
9
+ subprocess.run('pip install flash-attn einops flask', env={'FLASH_ATTENTION_SKIP_CUDA_BUILD': "TRUE"}, shell=True)
 
10
 
11
+ app = Flask(__name__)
12
 
13
+ model = AutoModelForCausalLM.from_pretrained('gokaygokay/Florence-2-SD3-Captioner', trust_remote_code=True).eval()
14
  processor = AutoProcessor.from_pretrained('gokaygokay/Florence-2-SD3-Captioner', trust_remote_code=True)
15
 
 
 
 
16
  def modify_caption(caption: str) -> str:
17
  """
18
  Removes specific prefixes from captions if present, otherwise returns the original caption.
 
41
  # If the caption was modified, return the modified version; otherwise, return the original
42
  return modified_caption if modified_caption != caption else caption
43
 
44
+ @app.route('/')
45
+ def index():
46
+ html = '''
47
+ <!DOCTYPE html>
48
+ <html>
49
+ <head>
50
+ <title>Florence-2 SD3 Long Captioner</title>
51
+ <style>
52
+ #output {
53
+ height: 500px;
54
+ overflow: auto;
55
+ border: 1px solid #ccc;
56
+ }
57
+ </style>
58
+ </head>
59
+ <body>
60
+ <h1>Florence-2 SD3 Long Captioner</h1>
61
+ <p>Florence-2 Base fine-tuned on Long SD3 Prompt and Image pairs. Check the Hugging Face link for datasets that are used for fine-tuning.</p>
62
+ <form id="uploadForm">
63
+ <label for="imageInput">Input Picture</label>
64
+ <input type="file" id="imageInput" name="image">
65
+ <button type="submit">Submit</button>
66
+ </form>
67
+ <div id="output">
68
+ <h3>Output Text</h3>
69
+ <p id="outputText"></p>
70
+ </div>
71
+ <script>
72
+ document.getElementById('uploadForm').onsubmit = async function(event) {
73
+ event.preventDefault();
74
+ const formData = new FormData();
75
+ const imageFile = document.getElementById('imageInput').files[0];
76
+ formData.append('image', imageFile);
77
+
78
+ const response = await fetch('/generate', {
79
+ method: 'POST',
80
+ body: formData
81
+ });
82
+
83
+ const data = await response.json();
84
+ document.getElementById('outputText').innerText = data.caption;
85
+ };
86
+ </script>
87
+ </body>
88
+ </html>
89
+ '''
90
+ return render_template_string(html)
91
+
92
+ @app.route('/generate', methods=['POST'])
93
+ def generate():
94
+ if 'image' not in request.files:
95
+ return jsonify({"error": "No image provided"}), 400
96
+
97
+ image_file = request.files['image']
98
+ image = Image.open(image_file.stream)
99
+
100
  task_prompt = "<DESCRIPTION>"
101
  prompt = task_prompt + "Describe this image in great detail."
102
 
 
113
  )
114
  generated_text = processor.batch_decode(generated_ids, skip_special_tokens=False)[0]
115
  parsed_answer = processor.post_process_generation(generated_text, task=task_prompt, image_size=(image.width, image.height))
116
+ caption = modify_caption(parsed_answer["<DESCRIPTION>"])
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
117
 
118
+ return jsonify({"caption": caption})
119
 
120
+ if __name__ == '__main__':
121
+ app.run(debug=True)