Muhammad2019abdelfattah commited on
Commit
9ffc4c2
·
verified ·
1 Parent(s): 13410cf

Upload 2 files

Browse files
Files changed (2) hide show
  1. app.py +60 -0
  2. requirements.txt +4 -0
app.py ADDED
@@ -0,0 +1,60 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ from transformers import VisionEncoderDecoderModel, DonutProcessor
3
+ from PIL import Image
4
+ import torch
5
+
6
+ # Load the model and processor
7
+ model_checkpoint_path = "Muhammad2019abdelfattah/Unichart_Fine-tuning"
8
+ model = VisionEncoderDecoderModel.from_pretrained(model_checkpoint_path)
9
+ processor = DonutProcessor.from_pretrained(model_checkpoint_path) # Assuming DonutProcessor is used
10
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
11
+ model.to(device)
12
+
13
+ def generate_summary(image: Image.Image) -> str:
14
+ try:
15
+ # Define the input prompt for summarization
16
+ input_prompt = "<summarize_chart> <s_answer>"
17
+
18
+ # Load and process the image
19
+ img = image.convert("RGB")
20
+ pixel_values = processor(img, return_tensors="pt").pixel_values.to(device)
21
+
22
+ # Encode the input prompt
23
+ decoder_input_ids = processor.tokenizer(input_prompt, add_special_tokens=False, return_tensors="pt").input_ids.to(device)
24
+
25
+ # Generate the summary
26
+ outputs = model.generate(
27
+ pixel_values=pixel_values,
28
+ decoder_input_ids=decoder_input_ids,
29
+ max_length=512, # Adjust max_length as needed
30
+ early_stopping=True,
31
+ pad_token_id=processor.tokenizer.pad_token_id,
32
+ eos_token_id=processor.tokenizer.eos_token_id,
33
+ use_cache=True,
34
+ num_beams=4,
35
+ bad_words_ids=[[processor.tokenizer.unk_token_id]],
36
+ return_dict_in_generate=True,
37
+ )
38
+
39
+ # Decode the output
40
+ sequence = processor.batch_decode(outputs.sequences)[0]
41
+ sequence = sequence.replace(processor.tokenizer.eos_token, "").replace(processor.tokenizer.pad_token, "")
42
+ summary = sequence.split("<s_answer>")[1].strip()
43
+
44
+ return summary
45
+
46
+ except Exception as e:
47
+ print(f"An error occurred: {e}")
48
+ return "An error occurred during summarization."
49
+
50
+ # Create Gradio interface
51
+ iface = gr.Interface(
52
+ fn=generate_summary, # Function to call
53
+ inputs=gr.Image(type="pil"), # Input type (image)
54
+ outputs="text", # Output type (text)
55
+ title="Chart Summarization",
56
+ description="Upload a chart image to get a summary based on the image content."
57
+ )
58
+
59
+ # Launch the Gradio interface on an automatically selected port
60
+ iface.launch(share=True)
requirements.txt ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ transformers
2
+ torch
3
+ Pillow
4
+ gradio