Spaces:
Paused
Paused
Download app.py from aysan98/validation: direct link, hf CLI and curl.
- Browser
- Download file 11.9 kB
-
https://huggingface.co/spaces/aysan98/validation/resolve/main/app.py
- Command line
-
hf download hf://spaces/aysan98/validation/app.py
-
curl -L -o app.py https://huggingface.co/spaces/aysan98/validation/resolve/main/app.py
11.9 kB
| 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() |