Kadi-IAM commited on
Commit
ceaacaa
1 Parent(s): 551badf

Upload app.py

Browse files
Files changed (1) hide show
  1. app.py +179 -0
app.py ADDED
@@ -0,0 +1,179 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import gradio as gr
3
+ import groq
4
+ from difflib import Differ
5
+
6
+ # Set api key of Groq
7
+ api_key = os.getenv("GROQ_API")
8
+
9
+
10
+ def generate_response(prompt):
11
+ if not prompt:
12
+ return "No transcription available. Please try speaking again."
13
+
14
+ client = groq.Client(api_key=api_key)
15
+
16
+ try:
17
+ # Use Llama 3.1 70B powered by Groq for text generation
18
+ completion = client.chat.completions.create(
19
+ model="llama-3.1-70b-versatile",
20
+ messages=[
21
+ # {"role": "system", "content": "You are a helpful assistant."},
22
+ {"role": "user", "content": prompt}
23
+ ],
24
+ )
25
+ return completion.choices[0].message.content
26
+ except Exception as e:
27
+ return f"Error in response generation: {str(e)}"
28
+
29
+
30
+ def writing_improver(text, writing_prompt):
31
+ combined_propmpt = f"{writing_prompt}\n\nInput:{text}\n\nOutput:"
32
+ rephrased_text = generate_response(combined_propmpt)
33
+ return rephrased_text
34
+
35
+
36
+ def diff_texts(text1, text2):
37
+ d = Differ()
38
+ return [
39
+ (token[2:], token[0] if token[0] != " " else None)
40
+ for token in d.compare(text1, text2)
41
+ ]
42
+
43
+
44
+ def text_reviewer(text, review_prompt):
45
+ combined_propmpt = f"{review_prompt}\n\nInput:{text}\n\nOutput:"
46
+ rephrased_text = generate_response(combined_propmpt)
47
+ return rephrased_text
48
+
49
+
50
+ with gr.Blocks() as demo:
51
+ gr.Markdown(
52
+ "A simple web app to enhance scientific writing 📝 using Large Language Models (LLMs). With features like grammar correction, clarity enhancement, and technical jargon simplification, which helps researchers and academics produce more precise, and readable papers, making scientific communication more efficient and accessible."
53
+ )
54
+ gr.Markdown(
55
+ "⚠️ This is designed for research purposes, for best privacy protection, please avoid sharing sensitive or confidential data."
56
+ )
57
+
58
+ with gr.Tab("Improve writing 📝"):
59
+ with gr.Row():
60
+ with gr.Column():
61
+ text_input = gr.Textbox(
62
+ label="Text to improve",
63
+ lines=10,
64
+ placeholder="Enter your text here and click the button below to rewrite it.",
65
+ )
66
+
67
+ with gr.Accordion("Show detailed writing instruction", open=False):
68
+ gr.Markdown(
69
+ "Note: modify **[topic]** in writing instruction accordingly."
70
+ )
71
+ prompt_input = gr.Textbox(
72
+ label="Writing instruction",
73
+ value="I am writing a paper on [topic] for a leading academic journal and would like help refining a specific section. Please rephrase the section to enhance clarity, coherence, and conciseness, ensuring smooth transitions between paragraphs and logical flow. Remove any unnecessary jargon and maintain a formal, professional tone suitable for an academic audience.",
74
+ lines=5,
75
+ )
76
+
77
+ submit_btn = gr.Button("Improve Writing", variant="primary")
78
+
79
+ with gr.Column():
80
+ output = gr.Textbox(label="Improved Text", show_copy_button=True)
81
+ with gr.Accordion("Show difference", open=False):
82
+ output_diff = gr.HighlightedText(
83
+ label="Diff",
84
+ combine_adjacent=True,
85
+ show_legend=True,
86
+ color_map={"-": "red", "+": "green"},
87
+ )
88
+
89
+ submit_btn.click(
90
+ fn=writing_improver, inputs=[text_input, prompt_input], outputs=output
91
+ )
92
+
93
+ output.change(fn=diff_texts, inputs=[text_input, output], outputs=output_diff)
94
+
95
+ gr.Markdown()
96
+ gr.Markdown()
97
+ gr.Markdown()
98
+
99
+ gr.Examples(
100
+ examples=[
101
+ [
102
+ "Solid-state batteries are a new type of battery that people are working on a lot right now. They use a solid electrolyte instead of the liquid or gel-like ones in regular lithium-ion batteries, which makes them better in some ways. For example, they can be safer because there’s less chance of leaking or catching fire, and they could also have more energy density, which means they can store more energy. Some researchers say they can charge faster, too, which is really important for things like electric cars. But there are a lot of challenges that still need to be solved, like the solid electrolyte not working as well as liquid ones at room temperature, and sometimes there are problems with the materials they use breaking down or not connecting well with the battery’s electrodes. So, even though solid-state batteries could be a big deal in the future, we’re not quite there yet.",
103
+ "I am writing a paper on topic solid-state batteries for a leading academic journal and would like help refining a specific section. Please rephrase the section to enhance clarity, coherence, and conciseness, ensuring smooth transitions between paragraphs and logical flow. Remove any unnecessary jargon and maintain a formal, professional tone suitable for an academic audience.",
104
+ ],
105
+ [
106
+ """In this study, we synthesized the solid-state electrolyte using the conventional solid-state reaction method. First, the raw materials, lithium carbonate (Li2CO3), aluminum oxide (Al2O3), and sulfur powder (S), were weighed according to their stoichiometric ratios and then mixed thoroughly in a mortar for approximately 30 minutes. After mixing, the powder was transferred to a furnace and calcined at 800°C for 6 hours. Following calcination, the powder was cooled to room temperature and then ground again for another 20 minutes. Next, the calcined powder was pressed into pellets using a hydraulic press at a pressure of 2 tons for 5 minutes. The pellets were then sintered in a furnace at 850°C for 12 hours to improve their mechanical strength and ionic conductivity. After sintering, the pellets were left to cool down naturally to room temperature. The obtained solid-state electrolyte was then characterized by X-ray diffraction (XRD) to confirm phase purity and scanning electron microscopy (SEM) to observe the microstructure. To evaluate the ionic conductivity, we performed electrochemical impedance spectroscopy (EIS) in the frequency range of 1 Hz to 1 MHz at room temperature. The pelletized electrolyte was placed between two stainless steel blocking electrodes in a Swagelok cell. The impedance data were analyzed using the ZView software to calculate the bulk resistance of the electrolyte. Ionic conductivity was determined by the formula σ = L/(R × A), where L is the thickness of the pellet, R is the bulk resistance, and A is the area of the pellet.Finally, we compared the ionic conductivity of the synthesized electrolyte with previously reported values. Although the conductivity of our sample was lower than expected, we believe that optimizing the sintering temperature or modifying the stoichiometric ratio could further improve the performance.""",
107
+ """I am preparing a manuscript on topic solid-state batteries for submission to a leading academic journal and seek assistance in refining a particular section. Please revise the section to improve clarity, coherence, and conciseness, while ensuring smooth transitions between paragraphs and a logical progression of ideas. Eliminate unnecessary jargon and maintain a formal, scholarly tone appropriate for an academic audience. Prioritize enhancing readability without sacrificing depth or precision.""",
108
+ ],
109
+ [
110
+ """Research data management is really important because it helps in keeping the data organized and accessible for future use. When data is managed well, it makes it easier for other researchers to understand and use the data, which is important for collaboration and further studies. Also, good data management practices help in making sure that the data is reliable and can be trusted. Many funding agencies and universities now require researchers to follow certain data management protocols, which shows how important it is. So, having a good system for managing research data is not just a good idea, but something that is necessary for doing good research.""",
111
+ """I am authoring a research paper on research data management with the aim of submitting it to a prestigious academic journal. I require assistance in refining a particular section to ensure it meets the journal's high standards. Please revise the section to improve its overall clarity, coherence, and conciseness. Focus on creating seamless transitions between paragraphs, maintaining a logical flow of ideas, and eliminating any jargon that may hinder understanding. The tone should remain formal and professional, catering to an academic audience.""",
112
+ ],
113
+ ],
114
+ examples_per_page=1,
115
+ inputs=[text_input, prompt_input],
116
+ )
117
+
118
+ with gr.Tab("Review Assistant 👀"):
119
+ with gr.Row():
120
+ with gr.Column():
121
+ review_text_input = gr.Textbox(
122
+ label="Text to review",
123
+ lines=10,
124
+ placeholder="Enter your text here and click the button below to review it.",
125
+ )
126
+
127
+ with gr.Accordion("Show detailed review instruction", open=False):
128
+ gr.Markdown(
129
+ "Note: modify **[topic]** and **[aspects]** in review instruction accordingly."
130
+ )
131
+ review_prompt_input = gr.Textbox(
132
+ label="Review instruction",
133
+ value="Assume the role of a seasoned scholar with over 20 years of academic expertise in [topic]. Based on the following section of the paper, which focuses primarily on the [aspects], provide a detailed and structured review. Your review should include the following elements: Core Content Summary: Very briefly summarize the key points and findings of the experimental section. Identification of Limitations: Critically identify and list the limitations of the experimental work. Significance of Limitations: Explain the significance of each identified limitation, ranking them in order of importance. Maintain a concise, objective, and professional tone throughout your review. Possible Questions by Reviewer: Prepare a list of possible questions a reviewer might ask about your work. Consider aspects such as the clarity of your argument, the strength of your evidence, the originality of your ideas, and any potential weaknesses or gaps in your research. Anticipating these questions can help you refine your work and address any concerns before submission.",
134
+ lines=8,
135
+ )
136
+
137
+ review_submit_btn = gr.Button("Review", variant="primary")
138
+
139
+ with gr.Column():
140
+ gr.Markdown(
141
+ "Some comments and suggestions from the LLM reviewer will show below."
142
+ )
143
+ review_output = gr.Markdown(label="Reviews")
144
+
145
+ review_submit_btn.click(
146
+ fn=text_reviewer,
147
+ inputs=[review_text_input, review_prompt_input],
148
+ outputs=review_output,
149
+ )
150
+
151
+ gr.Markdown()
152
+ gr.Markdown()
153
+ gr.Markdown()
154
+
155
+ gr.Examples(
156
+ examples=[
157
+ [
158
+ "The synthesis of the solid-state electrolyte was carried out using a simple solid-state reaction method. First, the precursor materials, lithium carbonate (Li2CO3), aluminum oxide (Al2O3), and titanium dioxide (TiO2), were weighed in stoichiometric amounts using a digital balance. The weighed powders were then mixed together in a mortar and pestle for 10 minutes to ensure homogeneity. The mixture was then transferred to an alumina crucible and heated in a muffle furnace at 800°C for 12 hours. After heating, the sample was allowed to cool to room temperature inside the furnace. The resulting powder was then ground again in the mortar and pestle for 5 minutes to break up any agglomerates. The powder was then pressed into pellets using a hydraulic press at a pressure of 5 tons for 2 minutes. The pellets were sintered at 900°C for 6 hours in the muffle furnace. After sintering, the pellets were cooled to room temperature in the furnace. The phase purity of the synthesized electrolyte was confirmed using X-ray diffraction (XRD) with Cu Kα radiation. The microstructure of the sintered pellets was examined using scanning electron microscopy (SEM). The ionic conductivity of the electrolyte was measured using electrochemical impedance spectroscopy (EIS) in the frequency range of 1 Hz to 1 MHz at room temperature. The electrolyte was sandwiched between two stainless steel electrodes for the EIS measurements.",
159
+ "Assume the role of a seasoned scholar with over 20 years of academic expertise in solid-state batteries. Based on the following section of the paper, which focuses primarily on the experimental aspects, provide a detailed and structured review. Your review should include the following elements: Core Content Summary: Very briefly summarize the key points and findings of the experimental section. Identification of Limitations: Critically identify and list the limitations of the experimental work. Significance of Limitations: Explain the significance of each identified limitation, ranking them in order of importance. Maintain a concise, objective, and professional tone throughout your review. Possible Questions by Reviewer: Prepare a list of possible questions a reviewer might ask about your work. Consider aspects such as the clarity of your argument, the strength of your evidence, the originality of your ideas, and any potential weaknesses or gaps in your research. Anticipating these questions can help you refine your work and address any concerns before submission.",
160
+ ],
161
+ ],
162
+ examples_per_page=1,
163
+ inputs=[review_text_input, review_prompt_input],
164
+ )
165
+
166
+ with gr.Tab("About"):
167
+ gr.Markdown(
168
+ """
169
+ This simple app is designed for academic purposes to explore the possibility of using Large Language Models (LLMs) to support the process of scientific writing. It is being developed by a team from Karlsruhe, Germany, who are interested in using machine learning techniques to support various scientific topics and simplify the process of research data management. You may find more information about us [here](https://kadi.iam.kit.edu/#).
170
+
171
+ It is possible that this application will not give a perfect answer at first, and you may need to modify the instruction prompt accordingly. This is because using LLM to help with scientific writing is a collaborative process that requires the user to provide additional information or refine their instructions. The quality of the interaction usually improves the results. However, it is very important to note that the user is using the LLM as a kind of "assistant" and not as a substitute for their own judgment. It is not the role of the LLM to write the user's document for them.
172
+
173
+ **Please be very careful about potential academic ethics issues and the leakage of private data that may result**.
174
+ """
175
+ )
176
+
177
+
178
+ if __name__ == "__main__":
179
+ demo.launch(show_api=False)