Anuji commited on
Commit
3c6abc9
·
verified ·
1 Parent(s): 97a3816

init app.py

Browse files
Files changed (1) hide show
  1. app.py +128 -0
app.py ADDED
@@ -0,0 +1,128 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Step 2: Verify GPU
2
+ import torch
3
+ print("CUDA Available:", torch.cuda.is_available())
4
+ print("Device:", torch.cuda.current_device() if torch.cuda.is_available() else "CPU")
5
+ print("Device Name:", torch.cuda.get_device_name(0) if torch.cuda.is_available() else "N/A")
6
+
7
+ # Step 3: Modified app.py for Colab with debugging
8
+ import os
9
+ import gradio as gr
10
+ import torch
11
+ from PIL import Image
12
+ from deepseek_vl2.serve.inference import load_model, deepseek_generate, convert_conversation_to_prompts
13
+ from deepseek_vl2.models.conversation import SeparatorStyle
14
+ from deepseek_vl2.serve.app_modules.utils import configure_logger, strip_stop_words, pil_to_base64
15
+ from google.colab import files
16
+
17
+ logger = configure_logger()
18
+
19
+ MODELS = ["deepseek-ai/deepseek-vl2-tiny"]
20
+ DEPLOY_MODELS = {}
21
+ IMAGE_TOKEN = "<image>"
22
+
23
+ def fetch_model(model_name: str, dtype=torch.bfloat16):
24
+ global DEPLOY_MODELS
25
+ if model_name not in DEPLOY_MODELS:
26
+ print(f"Loading {model_name}...")
27
+ model_info = load_model(model_name, dtype=dtype)
28
+ tokenizer, model, vl_chat_processor = model_info
29
+ device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
30
+ model = model.to(device)
31
+ DEPLOY_MODELS[model_name] = (tokenizer, model, vl_chat_processor)
32
+ print(f"Loaded {model_name} on {device}")
33
+ return DEPLOY_MODELS[model_name]
34
+
35
+ def generate_prompt_with_history(text, images, history, vl_chat_processor, tokenizer, max_length=2048):
36
+ conversation = vl_chat_processor.new_chat_template()
37
+ if history:
38
+ conversation.messages = history
39
+ if images:
40
+ text = f"{IMAGE_TOKEN}\n{text}"
41
+ text = (text, images)
42
+ conversation.append_message(conversation.roles[0], text)
43
+ conversation.append_message(conversation.roles[1], "")
44
+ return conversation
45
+
46
+ def to_gradio_chatbot(conv):
47
+ ret = []
48
+ for i, (role, msg) in enumerate(conv.messages[conv.offset:]):
49
+ if i % 2 == 0:
50
+ if isinstance(msg, tuple):
51
+ msg, images = msg
52
+ for image in images:
53
+ img_b64 = pil_to_base64(image, "user upload", max_size=800, min_size=400)
54
+ msg = msg.replace(IMAGE_TOKEN, img_b64, 1)
55
+ ret.append([msg, None])
56
+ else:
57
+ ret[-1][-1] = msg
58
+ return ret
59
+
60
+ def predict(text, images, chatbot, history, model_name="deepseek-ai/deepseek-vl2-tiny"):
61
+ print("Starting predict function...")
62
+ tokenizer, vl_gpt, vl_chat_processor = fetch_model(model_name)
63
+ if not text:
64
+ print("Empty text input detected.")
65
+ return chatbot, history, "Empty context."
66
+
67
+ print("Processing images...")
68
+ pil_images = [Image.open(img).convert("RGB") for img in images] if images else []
69
+ conversation = generate_prompt_with_history(
70
+ text, pil_images, history, vl_chat_processor, tokenizer
71
+ )
72
+ all_conv, _ = convert_conversation_to_prompts(conversation)
73
+ stop_words = conversation.stop_str
74
+ gradio_chatbot_output = to_gradio_chatbot(conversation)
75
+
76
+ full_response = ""
77
+ print("Generating response...")
78
+ try:
79
+ with torch.no_grad():
80
+ for x in deepseek_generate(
81
+ conversations=all_conv,
82
+ vl_gpt=vl_gpt,
83
+ vl_chat_processor=vl_chat_processor,
84
+ tokenizer=tokenizer,
85
+ stop_words=stop_words,
86
+ max_length=2048,
87
+ temperature=0.1,
88
+ top_p=0.9,
89
+ repetition_penalty=1.1
90
+ ):
91
+ full_response += x
92
+ response = strip_stop_words(full_response, stop_words)
93
+ conversation.update_last_message(response)
94
+ gradio_chatbot_output[-1][1] = response
95
+ print(f"Yielding partial response: {response[:50]}...")
96
+ yield gradio_chatbot_output, conversation.messages, "Generating..."
97
+
98
+ print("Generation complete.")
99
+ torch.cuda.empty_cache()
100
+ yield gradio_chatbot_output, conversation.messages, "Success"
101
+ except Exception as e:
102
+ print(f"Error in generation: {str(e)}")
103
+ yield gradio_chatbot_output, conversation.messages, f"Error: {str(e)}"
104
+
105
+ # Gradio interface for OCR
106
+ def upload_and_process(image):
107
+ if image is None:
108
+ return "Please upload an image.", []
109
+ prompt = "Extract all text from this image exactly as it appears, ensuring the output is in English only. Preserve spaces, bullets, numbers, and all formatting. Do not translate, generate, or include text in any other language. Stop at the last character of the image text."
110
+ chatbot = []
111
+ history = []
112
+ print("Starting upload_and_process...")
113
+ for chatbot_output, history_output, status in predict(prompt, [image], chatbot, history):
114
+ print(f"Status: {status}")
115
+ if status == "Success":
116
+ return chatbot_output[-1][1], history_output
117
+ return "Processing failed.", []
118
+
119
+ # Launch Gradio app
120
+ with gr.Blocks() as demo:
121
+ gr.Markdown("### DeepSeek-VL2 OCR in Colab")
122
+ image_input = gr.Image(type="filepath", label="Upload Image")
123
+ output_text = gr.Textbox(label="Extracted Text")
124
+ history_state = gr.State([])
125
+ submit_btn = gr.Button("Extract Text")
126
+ submit_btn.click(upload_and_process, inputs=image_input, outputs=[output_text, history_state])
127
+
128
+ demo.launch(share=True, debug=True) # Added debug=True for more Gradio logs