Spaces:
Paused
Paused
File size: 11,903 Bytes
0dfc5f5 | 1 2 3 4 5 6 7 8 9 10 11 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 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 | import requests
import json
import time
import re
import pandas as pd
from datetime import datetime
import gradio as gr
import io
# API Configuration
API_KEY = "AIzaSyD3Cxik2gssEgGsa3eUAHsBsDU6vxGSgw0"
BASE_URL = "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash:generateContent"
headers = {
"Content-Type": "application/json",
"X-goog-api-key": API_KEY
}
# Define search tools for Gemini
search_tools = [
{
"google_search": {}
}
]
def ask_gemini_with_tools(question, temperature):
"""Send question to Gemini API with search tools"""
enhanced_question = f"""
{question}
IMPORTANT: Please search extensively and provide a COMPLETE LIST of specific publications including:
1. Exact paper titles
2. Author names
3. Journal names
4. Publication years
5. DOI or PubMed IDs if available
Search multiple times with different keywords to find all relevant papers.
Include case reports, clinical studies, and review articles.
Format the results as a numbered list at the end of your response.
"""
payload = {
"contents": [
{
"parts": [
{
"text": enhanced_question
}
]
}
],
"tools": search_tools,
"generationConfig": {
"temperature": temperature,
"maxOutputTokens": 4000,
"topK": 40,
"topP": 0.95
}
}
try:
response = requests.post(BASE_URL, headers=headers, json=payload)
result = response.json()
if response.status_code != 200:
return None
if 'candidates' in result and len(result['candidates']) > 0:
candidate = result['candidates'][0]
if 'content' in candidate and 'parts' in candidate['content']:
parts = candidate['content']['parts']
response_text = ""
function_calls = []
for part in parts:
if 'text' in part:
response_text += part['text']
elif 'functionCall' in part:
function_calls.append(part['functionCall'])
return {
"response": response_text,
"function_calls": len(function_calls),
"temperature": temperature
}
return None
except Exception as e:
return None
def extract_publications_from_text(text):
"""Extract publications from the response text"""
publications = []
lines = text.split('\n')
current_publication = {}
for line in lines:
line = line.strip()
numbered_match = re.match(r'^(\d+)\.?\s*(.*)', line)
if numbered_match:
if current_publication and 'title' in current_publication and current_publication['title']:
publications.append(current_publication.copy())
number = numbered_match.group(1)
title_line = numbered_match.group(2).strip()
current_publication = {
'title': title_line,
'authors': '',
'journal': '',
'year': '',
'doi': '',
'pmid': '',
'summary': ''
}
year_match = re.search(r'\b(19|20)\d{2}\b', title_line)
if year_match:
current_publication['year'] = year_match.group(0)
elif current_publication and line:
lower_line = line.lower()
if 'author' in lower_line and not current_publication['authors']:
author_text = re.sub(r'authors?:?\s*', '', line, flags=re.IGNORECASE)
current_publication['authors'] = author_text.strip()
elif 'journal' in lower_line and not current_publication['journal']:
journal_text = re.sub(r'journal:?\s*', '', line, flags=re.IGNORECASE)
current_publication['journal'] = journal_text.strip()
elif 'doi' in lower_line:
doi_match = re.search(r'(10\.\d+/[^\s]+)', line)
if doi_match:
current_publication['doi'] = doi_match.group(1)
elif 'pmid' in lower_line:
pmid_match = re.search(r'(\d+)', line)
if pmid_match:
current_publication['pmid'] = pmid_match.group(1)
elif len(line) > 30 and not any(x in lower_line for x in ['title:', 'year:', 'published:']):
if current_publication['summary']:
current_publication['summary'] += ' ' + line
else:
current_publication['summary'] = line
if current_publication and 'title' in current_publication and current_publication['title']:
publications.append(current_publication)
filtered_pubs = []
for pub in publications:
if len(pub['title']) > 10 and not pub['title'].lower().startswith('here'):
filtered_pubs.append(pub)
return filtered_pubs
def run_temperature_test(research_question, temp_min, temp_max, temp_steps, progress=gr.Progress()):
"""Run temperature testing and return results"""
if not research_question.strip():
return "Please enter a research question.", None
question = research_question.strip()
# Generate temperature range
if temp_steps <= 1:
temperatures = [temp_min]
else:
temp_step = (temp_max - temp_min) / (temp_steps - 1)
temperatures = [temp_min + i * temp_step for i in range(temp_steps)]
all_data = []
total_iterations = len(temperatures)
current_iteration = 0
status_text = f"Processing question: {question[:100]}...\n"
for temp in temperatures:
current_iteration += 1
progress(current_iteration / total_iterations, f"Testing temperature {temp:.2f}")
status_text += f"Temperature {temp:.2f}: "
result = ask_gemini_with_tools(question, temp)
if result and result['response']:
publications = extract_publications_from_text(result['response'])
status_text += f"Found {len(publications)} publications\n"
for pub in publications:
all_data.append({
'Temperature': round(temp, 2),
'Function_Calls': result['function_calls'],
'Title': pub['title'],
'Authors': pub['authors'],
'Journal': pub['journal'],
'Year': pub['year'],
'DOI': pub['doi'],
'PMID': pub['pmid'],
'Summary': pub['summary'][:200] if pub['summary'] else ''
})
else:
status_text += "No results\n"
time.sleep(2) # Rate limiting
if not all_data:
return "No publications found in any of the tests.", None
# Create Excel file
df = pd.DataFrame(all_data)
# Create Excel file in memory
excel_buffer = io.BytesIO()
with pd.ExcelWriter(excel_buffer, engine='openpyxl') as writer:
df.to_excel(writer, sheet_name='Publications', index=False)
# Auto-adjust column widths
worksheet = writer.sheets['Publications']
for column in worksheet.columns:
max_length = 0
column_letter = column[0].column_letter
for cell in column:
try:
if len(str(cell.value)) > max_length:
max_length = len(str(cell.value))
except:
pass
adjusted_width = min(max_length + 2, 50)
worksheet.column_dimensions[column_letter].width = adjusted_width
excel_buffer.seek(0)
# Generate summary
summary = f"""
Test completed successfully!
Research Question: {question}
Total publications found: {len(all_data)}
Summary by temperature:
"""
summary_df = df.groupby(['Temperature']).size().reset_index(name='Publications')
summary += summary_df.to_string(index=False)
return summary + "\n\n" + status_text, excel_buffer.getvalue()
def create_interface():
"""Create Gradio interface"""
with gr.Blocks(title="Gemini Temperature Testing for Publications") as interface:
gr.Markdown("# Gemini Temperature Testing for Medical Publications")
gr.Markdown("Test how different temperature settings affect Gemini's publication search results")
with gr.Row():
with gr.Column():
gr.Markdown("### Research Question")
research_question = gr.Textbox(
label="Enter your research question",
placeholder="Example: Find papers about machine learning applications in medical diagnosis",
lines=4,
info="Enter any research question you want to test across different temperatures"
)
with gr.Column():
gr.Markdown("### Temperature Settings")
temp_min = gr.Slider(
minimum=0.0,
maximum=1.0,
step=0.1,
value=0.0,
label="Minimum Temperature"
)
temp_max = gr.Slider(
minimum=0.0,
maximum=1.0,
step=0.1,
value=1.0,
label="Maximum Temperature"
)
temp_steps = gr.Slider(
minimum=1,
maximum=10,
step=1,
value=4,
label="Number of Temperature Steps"
)
run_button = gr.Button("Run Temperature Test", variant="primary", size="lg")
with gr.Row():
with gr.Column():
output_text = gr.Textbox(
label="Test Results",
lines=20,
max_lines=50
)
with gr.Column():
excel_file = gr.File(
label="Download Excel Results",
file_types=[".xlsx"]
)
run_button.click(
fn=run_temperature_test,
inputs=[research_question, temp_min, temp_max, temp_steps],
outputs=[output_text, excel_file]
)
gr.Markdown("""
### Instructions:
1. Enter your research question (any topic)
2. Set temperature range (0.0 = most focused, 1.0 = most creative)
3. Choose number of temperature steps to test
4. Click "Run Temperature Test"
5. Download the Excel file with all results
### Examples of research questions:
- "Find papers about machine learning in medical diagnosis"
- "Search for studies on climate change impact on agriculture"
- "Find research on drug interactions with metformin"
- "Look for papers on CRISPR gene editing applications"
### Note:
- Each test takes 2-5 seconds per temperature setting
- Results include publication titles, authors, journals, years, DOIs, and PMIDs
- Only tests with actual search results will be included in the Excel file
""")
return interface
if __name__ == "__main__":
interface = create_interface()
interface.launch() |