Ani14 commited on
Commit
111e016
Β·
verified Β·
1 Parent(s): 8468c97

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +110 -81
app.py CHANGED
@@ -5,118 +5,147 @@ import streamlit as st
5
  from dotenv import load_dotenv
6
  from duckduckgo_search import DDGS
7
  import subprocess
 
8
 
9
- # Load API
10
  load_dotenv()
11
  API_KEY = os.getenv("OPENROUTER_API_KEY")
12
 
13
- def call_llm(prompt):
14
- url = "https://openrouter.ai/api/v1/chat/completions"
15
- headers = {"Authorization": f"Bearer {API_KEY}", "Content-Type": "application/json"}
16
- data = {
17
- "model": "google/gemma-3-1b-it:free",
18
- "messages": [{"role": "user", "content": prompt}]
 
 
 
19
  }
20
- res = requests.post(url, headers=headers, json=data)
21
- if res.status_code == 200:
22
- return res.json()['choices'][0]['message']['content']
23
- else:
24
- return f"❌ Error: {res.status_code} - {res.text}"
25
-
26
- def get_arxiv_papers(topic):
27
- search = arxiv.Search(query=topic, max_results=5, sort_by=arxiv.SortCriterion.SubmittedDate)
28
- papers = []
29
- for result in search.results():
30
- paper = {
31
- "title": result.title,
32
- "summary": result.summary,
33
- "url": result.pdf_url
 
34
  }
35
- papers.append(paper)
36
- return papers
 
 
 
 
 
 
 
 
 
 
 
 
37
 
38
  def fetch_image_url(query):
39
- with DDGS() as ddgs:
40
- results = list(ddgs.images(query, max_results=1))
41
- if results:
42
- return results[0]['image']
43
- return None
44
-
45
- def create_latex(paper_title, full_content, image_url, file_name="research_paper.tex"):
46
- latex = f"""
 
 
 
 
 
 
47
  \\documentclass[12pt]{{article}}
48
- \\usepackage{{graphicx}}
49
  \\usepackage[margin=1in]{{geometry}}
 
50
  \\usepackage{{hyperref}}
51
- \\title{{\\textbf{{{paper_title}}}}}
52
  \\date{{\\today}}
53
  \\begin{{document}}
54
  \\maketitle
55
-
56
- \\begin{{figure}}[h]
57
- \\centering
58
- \\includegraphics[width=0.6\\textwidth]{{image.jpg}}
59
- \\caption{{Relevant diagram for {paper_title}}}
60
- \\end{{figure}}
61
-
62
- {full_content.replace('\\n', '\\\\ \\n')}
63
-
64
- \\end{{document}}
65
  """
66
- with open(file_name, "w") as f:
67
- f.write(latex)
68
 
69
- # Save image
70
  if image_url:
71
  img_data = requests.get(image_url).content
72
  with open("image.jpg", "wb") as img:
73
  img.write(img_data)
 
 
 
 
 
 
 
 
 
 
 
 
 
74
 
75
- subprocess.run(["pdflatex", file_name], stdout=subprocess.DEVNULL)
76
- return "research_paper.pdf"
77
 
78
- # Streamlit UI
79
- st.set_page_config("MTech AI Research Generator", layout="wide")
80
- st.title("πŸ“š Deep Research Paper Generator (AI + arXiv + PDF Export)")
81
 
82
  topic = st.text_input("πŸ” Enter your research topic:")
83
 
84
  if topic:
85
- with st.spinner("Fetching latest papers from arXiv..."):
86
- papers = get_arxiv_papers(topic)
87
  summaries = "\n\n".join([f"Title: {p['title']}\nSummary: {p['summary']}" for p in papers])
88
- st.success("βœ… Papers Retrieved!")
89
- st.subheader("πŸ“„ Top 5 arXiv Papers")
90
- for p in papers:
91
- st.markdown(f"**{p['title']}** \n[PDF Link]({p['url']}) \n> {p['summary'][:300]}...\n")
92
-
93
- with st.spinner("Analyzing literature & generating novel paper..."):
94
- gap = call_llm(f"Identify current research gaps based on these papers:\n\n{summaries}")
95
- idea = call_llm(f"Propose a novel research direction based on this:\n\n{gap}")
96
- paper = call_llm(f"""Write a detailed academic paper on "{topic}" using the idea:
 
97
  {idea}
 
98
  Structure:
99
- 1. Abstract
100
- 2. Introduction
101
- 3. Related Work
102
- 4. Methodology
103
- 5. Experiments
104
- 6. Results
105
- 7. Conclusion
106
- 8. References""")
107
-
108
- st.subheader("🧠 Novel Idea")
 
 
109
  st.markdown(idea)
110
 
111
- st.subheader("πŸ“ Full Paper")
112
- st.markdown(paper)
113
 
114
- st.subheader("πŸ–ΌοΈ Diagram")
115
- image_url = fetch_image_url(topic)
116
- if image_url:
117
- st.image(image_url, caption="Auto-selected diagram")
118
 
119
  if st.button("πŸ“₯ Export to PDF"):
120
- pdf = create_latex(topic, paper, image_url)
121
- with open(pdf, "rb") as f:
122
- st.download_button("Download PDF", f, file_name=f"{topic.replace(' ', '_')}.pdf")
 
 
 
5
  from dotenv import load_dotenv
6
  from duckduckgo_search import DDGS
7
  import subprocess
8
+ import re
9
 
10
+ # Load environment
11
  load_dotenv()
12
  API_KEY = os.getenv("OPENROUTER_API_KEY")
13
 
14
+ # ========== UTILITY FUNCTIONS ==========
15
+ def sanitize_filename(title):
16
+ return re.sub(r'[^\w\s-]', '', title).replace(" ", "_")[:50]
17
+
18
+ def escape_latex(text):
19
+ replacements = {
20
+ '&': r'\&', '%': r'\%', '$': r'\$', '#': r'\#',
21
+ '_': r'\_', '{': r'\{', '}': r'\}', '~': r'\textasciitilde{}',
22
+ '^': r'\^{}', '\\': r'\textbackslash{}',
23
  }
24
+ for original, replacement in replacements.items():
25
+ text = text.replace(original, replacement)
26
+ return text
27
+
28
+ # ========== LLM INTERACTION ==========
29
+ def call_llm(prompt):
30
+ try:
31
+ url = "https://openrouter.ai/api/v1/chat/completions"
32
+ headers = {
33
+ "Authorization": f"Bearer {API_KEY}",
34
+ "Content-Type": "application/json"
35
+ }
36
+ data = {
37
+ "model": "google/gemma-3-1b-it:free",
38
+ "messages": [{"role": "user", "content": prompt}]
39
  }
40
+ response = requests.post(url, headers=headers, json=data)
41
+ response.raise_for_status()
42
+ return response.json()['choices'][0]['message']['content']
43
+ except Exception as e:
44
+ return f"❌ LLM Error: {str(e)}"
45
+
46
+ # ========== FETCH RESEARCH ==========
47
+ def fetch_arxiv_papers(topic):
48
+ results = arxiv.Search(query=topic, max_results=5, sort_by=arxiv.SortCriterion.SubmittedDate)
49
+ return [{
50
+ "title": result.title,
51
+ "summary": result.summary,
52
+ "url": result.pdf_url
53
+ } for result in results.results()]
54
 
55
  def fetch_image_url(query):
56
+ try:
57
+ with DDGS() as ddgs:
58
+ results = list(ddgs.images(query, max_results=1))
59
+ if results:
60
+ return results[0]['image']
61
+ except:
62
+ pass
63
+ return None
64
+
65
+ # ========== PDF EXPORT ==========
66
+ def create_latex(title, content, image_url):
67
+ title_safe = sanitize_filename(title)
68
+ content = escape_latex(content)
69
+ tex = f"""
70
  \\documentclass[12pt]{{article}}
 
71
  \\usepackage[margin=1in]{{geometry}}
72
+ \\usepackage{{graphicx}}
73
  \\usepackage{{hyperref}}
74
+ \\title{{\\textbf{{{escape_latex(title)}}}}}
75
  \\date{{\\today}}
76
  \\begin{{document}}
77
  \\maketitle
 
 
 
 
 
 
 
 
 
 
78
  """
 
 
79
 
 
80
  if image_url:
81
  img_data = requests.get(image_url).content
82
  with open("image.jpg", "wb") as img:
83
  img.write(img_data)
84
+ tex += """
85
+ \\begin{figure}[h]
86
+ \\centering
87
+ \\includegraphics[width=0.7\\textwidth]{image.jpg}
88
+ \\caption{Auto-fetched Diagram}
89
+ \\end{figure}
90
+ """
91
+
92
+ tex += f"{content}\n\\end{{document}}"
93
+
94
+ tex_file = f"{title_safe}.tex"
95
+ with open(tex_file, "w", encoding="utf-8") as f:
96
+ f.write(tex)
97
 
98
+ subprocess.run(["pdflatex", tex_file], stdout=subprocess.DEVNULL)
99
+ return f"{title_safe}.pdf"
100
 
101
+ # ========== STREAMLIT UI ==========
102
+ st.set_page_config("AI Research Assistant", layout="wide")
103
+ st.title("πŸ§ͺ AI-Powered Research Assistant")
104
 
105
  topic = st.text_input("πŸ” Enter your research topic:")
106
 
107
  if topic:
108
+ with st.spinner("πŸ”Ž Fetching relevant arXiv papers..."):
109
+ papers = fetch_arxiv_papers(topic)
110
  summaries = "\n\n".join([f"Title: {p['title']}\nSummary: {p['summary']}" for p in papers])
111
+
112
+ st.subheader("πŸ“„ Recent arXiv Papers")
113
+ for p in papers:
114
+ st.markdown(f"**{p['title']}**\n[πŸ”— PDF Link]({p['url']})\n> {p['summary'][:300]}...")
115
+
116
+ with st.spinner("🧠 Analyzing gaps and proposing ideas..."):
117
+ gaps = call_llm(f"You're a top AI researcher. Read the summaries and find research gaps:\n\n{summaries}")
118
+ idea = call_llm(f"Based on the gaps below, propose a novel research idea:\n\n{gaps}")
119
+ paper = call_llm(f"""Write a detailed academic paper titled: "{topic}".
120
+ Incorporate the following novel idea:
121
  {idea}
122
+
123
  Structure:
124
+ - Abstract
125
+ - Introduction
126
+ - Related Work
127
+ - Methodology
128
+ - Experiments
129
+ - Results & Discussion
130
+ - Conclusion
131
+ - References
132
+
133
+ Write clearly in LaTeX-ready format.""")
134
+
135
+ st.subheader("πŸ’‘ Novel Research Idea")
136
  st.markdown(idea)
137
 
138
+ st.subheader("πŸ“ƒ Full Generated Paper")
139
+ st.text_area("Academic Paper", paper, height=600)
140
 
141
+ with st.spinner("πŸ–ΌοΈ Fetching diagram..."):
142
+ image_url = fetch_image_url(topic)
143
+ if image_url:
144
+ st.image(image_url, caption="Auto-fetched relevant diagram")
145
 
146
  if st.button("πŸ“₯ Export to PDF"):
147
+ with st.spinner("πŸ“„ Generating PDF..."):
148
+ pdf_file = create_latex(topic, paper, image_url)
149
+ with open(pdf_file, "rb") as f:
150
+ st.download_button("Download Paper as PDF", f, file_name=pdf_file)
151
+