Spaces:
Sleeping
Sleeping
Update app.py
Browse files
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
|
10 |
load_dotenv()
|
11 |
API_KEY = os.getenv("OPENROUTER_API_KEY")
|
12 |
|
13 |
-
|
14 |
-
|
15 |
-
|
16 |
-
|
17 |
-
|
18 |
-
|
|
|
|
|
|
|
19 |
}
|
20 |
-
|
21 |
-
|
22 |
-
|
23 |
-
|
24 |
-
|
25 |
-
|
26 |
-
|
27 |
-
|
28 |
-
|
29 |
-
|
30 |
-
|
31 |
-
|
32 |
-
|
33 |
-
"
|
|
|
34 |
}
|
35 |
-
|
36 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
37 |
|
38 |
def fetch_image_url(query):
|
39 |
-
|
40 |
-
|
41 |
-
|
42 |
-
|
43 |
-
|
44 |
-
|
45 |
-
|
46 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
47 |
\\documentclass[12pt]{{article}}
|
48 |
-
\\usepackage{{graphicx}}
|
49 |
\\usepackage[margin=1in]{{geometry}}
|
|
|
50 |
\\usepackage{{hyperref}}
|
51 |
-
\\title{{\\textbf{{{
|
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",
|
76 |
-
return "
|
77 |
|
78 |
-
#
|
79 |
-
st.set_page_config("
|
80 |
-
st.title("
|
81 |
|
82 |
topic = st.text_input("π Enter your research topic:")
|
83 |
|
84 |
if topic:
|
85 |
-
with st.spinner("Fetching
|
86 |
-
papers =
|
87 |
summaries = "\n\n".join([f"Title: {p['title']}\nSummary: {p['summary']}" for p in papers])
|
88 |
-
|
89 |
-
|
90 |
-
|
91 |
-
|
92 |
-
|
93 |
-
with st.spinner("Analyzing
|
94 |
-
|
95 |
-
idea = call_llm(f"
|
96 |
-
paper = call_llm(f"""Write a detailed academic paper
|
|
|
97 |
{idea}
|
|
|
98 |
Structure:
|
99 |
-
|
100 |
-
|
101 |
-
|
102 |
-
|
103 |
-
|
104 |
-
|
105 |
-
|
106 |
-
|
107 |
-
|
108 |
-
|
|
|
|
|
109 |
st.markdown(idea)
|
110 |
|
111 |
-
st.subheader("
|
112 |
-
st.
|
113 |
|
114 |
-
st.
|
115 |
-
|
116 |
-
|
117 |
-
|
118 |
|
119 |
if st.button("π₯ Export to PDF"):
|
120 |
-
|
121 |
-
|
122 |
-
|
|
|
|
|
|
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 |
+
|