DYDYLAN commited on
Commit
2009574
·
verified ·
1 Parent(s): f01d54f

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +96 -94
app.py CHANGED
@@ -3,8 +3,7 @@ from transformers import pipeline
3
  from PIL import Image, ImageEnhance
4
  from pypdf import PdfReader
5
 
6
- # ===================== 1. 加载模型CPU + flan-t5-base) =====================
7
-
8
  vision_pipe = pipeline(
9
  "image-to-text",
10
  model="nlpconnect/vit-gpt2-image-captioning",
@@ -13,13 +12,12 @@ vision_pipe = pipeline(
13
 
14
  text_pipe = pipeline(
15
  "text2text-generation",
16
- model="t5-small",
17
  max_length=256,
18
  device=-1
19
  )
20
 
21
- # ===================== 2. 论文 PDF 上下处理 =====================
22
-
23
  def extract_paper_context(paper_file):
24
  if paper_file is None:
25
  return ""
@@ -27,30 +25,27 @@ def extract_paper_context(paper_file):
27
  path = paper_file if isinstance(paper_file, str) else paper_file.name
28
  reader = PdfReader(path)
29
  text = ""
30
- for i, page in enumerate(reader.pages[:3]):
31
  page_text = page.extract_text() or ""
32
  text += page_text + "\n"
33
- return text.strip()[:4000]
34
- except:
 
 
35
  return ""
36
 
37
  def summarize_paper_context(raw_text):
38
  if not raw_text:
39
  return ""
40
- prompt = f"""
41
- Summarize in 4-6 sentences the research background most relevant for understanding
42
- a result figure. Focus on variables, comparisons, and experimental conditions.
43
-
44
- Paper text:
45
- {raw_text}
46
-
47
- Summary:
48
- """
49
  return text_pipe(prompt)[0]["generated_text"]
50
 
51
-
52
- # ===================== 3. 核心工作流 =====================
53
-
54
  def analyze_and_enhance(image, style, language, paper_file):
55
  if image is None:
56
  return None, "请先上传图表。", "", None, "", ""
@@ -59,108 +54,115 @@ def analyze_and_enhance(image, style, language, paper_file):
59
  paper_raw = extract_paper_context(paper_file)
60
  paper_context = summarize_paper_context(paper_raw) if paper_raw else ""
61
 
62
- # 图像描述
63
  raw_caption = vision_pipe(image)[0]["generated_text"]
64
  rc = raw_caption.lower()
65
  if not any(k in rc for k in ["bar", "chart", "graph", "plot", "curve", "line"]):
66
- raw_caption = "a bar chart comparing multiple experimental groups under different conditions"
67
-
68
- # Academic explanation
69
- if paper_context:
70
- context_part = f"Here is relevant context from the paper:\n{paper_context}\n"
71
- else:
72
- context_part = "No additional paper context available.\n"
73
-
74
- prompt_academic = f"""
75
- You are writing the Results section of a scientific paper.
76
-
77
- {context_part}
78
-
79
- Write a structured academic explanation (3–4 sentences) of the figure:
80
-
81
- 1. Identify the figure type.
82
- 2. Describe generically what is on the horizontal axis.
83
- 3. Describe generically what is on the vertical axis.
84
- 4. Describe overall trends.
85
- 5. Summarize the main comparison, consistent with the paper context.
86
-
87
- Do NOT repeat sentences or invent specific numbers.
88
-
89
- Figure description: {raw_caption}
90
- """
91
  academic_desc = text_pipe(prompt_academic)[0]["generated_text"]
92
 
93
- # Caption
94
- caption_prompt = f"""
95
- Write a concise 1–2 sentence academic figure caption.
96
- Keep it consistent with the paper context.
97
-
98
- Description: {academic_desc}
99
-
100
- Caption:
101
- """
102
  caption_text = text_pipe(caption_prompt)[0]["generated_text"]
103
 
104
- # Summary paragraph
105
- summary_prompt = f"""
106
- Write a 3–4 sentence paragraph explaining the key message of this figure,
107
- consistent with the paper context. Do not fabricate numbers.
108
-
109
- Description: {academic_desc}
110
-
111
- Paragraph:
112
- """
113
  summary_text = text_pipe(summary_prompt)[0]["generated_text"]
114
 
115
- # Language translation
116
  if language == "中文":
117
- academic_desc = text_pipe(f"Translate into Chinese:\n{academic_desc}")[0]["generated_text"]
118
- caption_text = text_pipe(f"Translate into Chinese:\n{caption_text}")[0]["generated_text"]
119
- summary_text = text_pipe(f"Translate into Chinese:\n{summary_text}")[0]["generated_text"]
 
 
 
 
 
 
 
 
120
 
121
- # 图像增强
122
  img_rgb = image.convert("RGB")
123
  img_c = ImageEnhance.Contrast(img_rgb).enhance(1.4)
124
  enhanced_image = ImageEnhance.Brightness(img_c).enhance(1.1)
125
 
126
- return image, raw_caption, academic_desc, enhanced_image, caption_text, summary_text
127
-
128
 
129
- # ===================== 4. Gradio UI(宽文本框 + 全宽布局) =====================
130
-
131
- with gr.Blocks() as demo:
 
 
 
 
 
132
  gr.Markdown("# ChartSmith – AI 论文图表生成助手")
133
 
134
  with gr.Row():
135
- with gr.Column():
136
  img_in = gr.Image(type="pil", label="上传你的学术图表(截图也可以)")
137
-
138
  style = gr.Dropdown(
139
  ["Formal academic", "Infographic", "Magazine-style"],
140
  value="Formal academic",
141
- label="重绘风格"
142
  )
143
-
144
- language = gr.Radio(
145
- ["English", "中文"],
146
- value="English",
147
- label="输出语言"
148
- )
149
-
150
  paper_file = gr.File(
151
- label="上传相关论文(可选,用于更精准解释)",
152
- file_types=[".txt", ".pdf", ".md"]
153
  )
 
154
 
155
- btn = gr.Button("分析并美化图表")
156
-
157
- with gr.Column():
158
  orig_img = gr.Image(label="原始图表")
159
- raw_caption_box = gr.Textbox(label="Step 2: 初步自动描述(Vision-LLM)", lines=4)
160
- academic_box = gr.Textbox(label="Step 3: 学术化解释结合论文上下文)", lines=6)
161
- enhanced_img = gr.Image(label="Step 4: 强化后的图表(亮度/对比度提升)")
162
- caption_box = gr.Textbox(label="Step 5: 自动生成图注(Caption)", lines=4)
163
- summary_box = gr.Textbox(label="Step 5: 图表简短摘要 / 讨论", lines=6)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
164
 
165
  btn.click(
166
  analyze_and_enhance,
 
3
  from PIL import Image, ImageEnhance
4
  from pypdf import PdfReader
5
 
6
+ # ========== 1. 模型:方便在 CPU Basic 上跑 ==========
 
7
  vision_pipe = pipeline(
8
  "image-to-text",
9
  model="nlpconnect/vit-gpt2-image-captioning",
 
12
 
13
  text_pipe = pipeline(
14
  "text2text-generation",
15
+ model="google/flan-t5-small",
16
  max_length=256,
17
  device=-1
18
  )
19
 
20
+ # ========== 2. 论文 PDF ==========
 
21
  def extract_paper_context(paper_file):
22
  if paper_file is None:
23
  return ""
 
25
  path = paper_file if isinstance(paper_file, str) else paper_file.name
26
  reader = PdfReader(path)
27
  text = ""
28
+ for page in reader.pages[:3]:
29
  page_text = page.extract_text() or ""
30
  text += page_text + "\n"
31
+ text = text.strip()
32
+ return text[:3000] # 截短一点,避免太长
33
+ except Exception as e:
34
+ print("PDF error:", e)
35
  return ""
36
 
37
  def summarize_paper_context(raw_text):
38
  if not raw_text:
39
  return ""
40
+ prompt = (
41
+ "Here is an excerpt from a scientific paper. "
42
+ "In 4-5 sentences, summarize the experimental setup and the main "
43
+ "variables or comparisons that the results focus on.\n\n"
44
+ f"{raw_text}\n\nSummary:"
45
+ )
 
 
 
46
  return text_pipe(prompt)[0]["generated_text"]
47
 
48
+ # ========== 3. 核心工作流 ==========
 
 
49
  def analyze_and_enhance(image, style, language, paper_file):
50
  if image is None:
51
  return None, "请先上传图表。", "", None, "", ""
 
54
  paper_raw = extract_paper_context(paper_file)
55
  paper_context = summarize_paper_context(paper_raw) if paper_raw else ""
56
 
57
+ # Step 2: 图像粗略描述
58
  raw_caption = vision_pipe(image)[0]["generated_text"]
59
  rc = raw_caption.lower()
60
  if not any(k in rc for k in ["bar", "chart", "graph", "plot", "curve", "line"]):
61
+ # 避免“clock and a building”这类离谱 caption
62
+ raw_caption = "a bar chart showing experimental results described in the paper"
63
+
64
+ # Step 3: 学术化解释(简单指令,不再列一堆 1,2,3,4)
65
+ context_part = (
66
+ f"Paper context: {paper_context}\n\n"
67
+ if paper_context else
68
+ ""
69
+ )
70
+ prompt_academic = (
71
+ "You are writing the Results section of a scientific paper.\n\n"
72
+ f"{context_part}"
73
+ f"Figure description: {raw_caption}\n\n"
74
+ "In 3–4 sentences, explain what this figure shows and what the main "
75
+ "pattern or comparison is. Use formal academic English. "
76
+ "Answer directly with the explanation:"
77
+ )
 
 
 
 
 
 
 
 
78
  academic_desc = text_pipe(prompt_academic)[0]["generated_text"]
79
 
80
+ # Step 5: Caption(基于刚才那段 explanation)
81
+ caption_prompt = (
82
+ "Write a 1–2 sentence figure caption for an academic paper based on "
83
+ "the explanation below. Mention the type of figure and the main "
84
+ "comparison or trend.\n\n"
85
+ f"{academic_desc}\n\nCaption:"
86
+ )
 
 
87
  caption_text = text_pipe(caption_prompt)[0]["generated_text"]
88
 
89
+ # Step 5: Summary / 讨论段落
90
+ summary_prompt = (
91
+ "Rewrite the following explanation as a short paragraph (3–4 sentences) "
92
+ "for the Results section of a paper, highlighting the key trend and conclusion.\n\n"
93
+ f"{academic_desc}\n\nParagraph:"
94
+ )
 
 
 
95
  summary_text = text_pipe(summary_prompt)[0]["generated_text"]
96
 
97
+ # 语言切换
98
  if language == "中文":
99
+ academic_desc_out = text_pipe(
100
+ f"Translate the following academic explanation into Chinese:\n{academic_desc}"
101
+ )[0]["generated_text"]
102
+ caption_text = text_pipe(
103
+ f"Translate the following figure caption into Chinese:\n{caption_text}"
104
+ )[0]["generated_text"]
105
+ summary_text = text_pipe(
106
+ f"Translate the following paragraph into Chinese:\n{summary_text}"
107
+ )[0]["generated_text"]
108
+ else:
109
+ academic_desc_out = academic_desc
110
 
111
+ # Step 4: 图像增强
112
  img_rgb = image.convert("RGB")
113
  img_c = ImageEnhance.Contrast(img_rgb).enhance(1.4)
114
  enhanced_image = ImageEnhance.Brightness(img_c).enhance(1.1)
115
 
116
+ return image, raw_caption, academic_desc_out, enhanced_image, caption_text, summary_text
 
117
 
118
+ # ========== 4. Gradio UI ==========
119
+ with gr.Blocks(css="""
120
+ .wide_textbox textarea {
121
+ font-size: 14px;
122
+ line-height: 1.5;
123
+ min-height: 120px;
124
+ }
125
+ """) as demo:
126
  gr.Markdown("# ChartSmith – AI 论文图表生成助手")
127
 
128
  with gr.Row():
129
+ with gr.Column(scale=1):
130
  img_in = gr.Image(type="pil", label="上传你的学术图表(截图也可以)")
 
131
  style = gr.Dropdown(
132
  ["Formal academic", "Infographic", "Magazine-style"],
133
  value="Formal academic",
134
+ label="重绘风格(当前版本仅用于说明)"
135
  )
136
+ language = gr.Radio(["English", "中文"], value="English", label="输出语言")
 
 
 
 
 
 
137
  paper_file = gr.File(
138
+ label="上传相关论文 PDF(可选,用于更精准解释)",
139
+ file_types=[".pdf"]
140
  )
141
+ btn = gr.Button("分析并美化图表", variant="primary")
142
 
143
+ with gr.Column(scale=1.2):
 
 
144
  orig_img = gr.Image(label="原始图表")
145
+ raw_caption_box = gr.Textbox(
146
+ label="Step 2: 初步自动描述Vision-LLM)",
147
+ lines=3,
148
+ elem_classes=["wide_textbox"]
149
+ )
150
+ academic_box = gr.Textbox(
151
+ label="Step 3: 学术化解释(结合论文上下文)",
152
+ lines=5,
153
+ elem_classes=["wide_textbox"]
154
+ )
155
+ enhanced_img = gr.Image(label="Step 4: 增强后的图表(亮度/对比度提升)")
156
+ caption_box = gr.Textbox(
157
+ label="Step 5: 自动生成图注(Caption)",
158
+ lines=3,
159
+ elem_classes=["wide_textbox"]
160
+ )
161
+ summary_box = gr.Textbox(
162
+ label="Step 5: 图表相关简短摘要 / 讨论",
163
+ lines=5,
164
+ elem_classes=["wide_textbox"]
165
+ )
166
 
167
  btn.click(
168
  analyze_and_enhance,