Spaces:
Paused
Paused
Update app.py
Browse files1234567891051 unmodified lines6263646566676869707172737475762 unmodified lines798081828384858687888990919293942 unmodified lines9798991001011022 unmodified lines1051061071081091101111121131141151162 unmodified lines11912012112212312463 unmodified lines18818919019119219319416 unmodified lines2112122132142152162172181 unmodified line220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263import gradio as grfrom openai import OpenAIimport osimport jsonfrom urllib.parse import quoteimport html# Initialize OpenAI client with API key and base URL from environment variablesclient = OpenAI(api_key=os.environ["OPENAI_API_KEY"],51 unmodified lineselse:return None, f"Error: {error_msg}"def generate_search_page(query, page=1):"""Generate a full HTML search results page."""if not query.strip():return """<html><head><title>LLM Search Engine</title></head><body style="font-family: Arial, sans-serif;"><h1>LLM Search Engine</h1><form id="search-form"><input type="text" name="query" placeholder="Type your search here..."><input type="submit" value="Search"><input type="hidden" name="page" value="1">2 unmodified lines</body></html>"""results, error = fetch_search_results(query)if error:return f"""<html><head><title>LLM Search Engine</title></head><body style="font-family: Arial, sans-serif;"><h1>LLM Search Engine</h1><form id="search-form"><input type="text" name="query" value="{html.escape(query)}"><input type="submit" value="Search"><input type="hidden" name="page" value="1">2 unmodified lines</body></html>"""# Calculate pagination boundariesstart_idx = (page - 1) * RESULTS_PER_PAGE2 unmodified lines# Ensure indices are within boundsif start_idx >= len(results):return f"""<html><head><title>LLM Search Engine</title></head><body style="font-family: Arial, sans-serif;"><h1>LLM Search Engine</h1><form id="search-form"><input type="text" name="query" value="{html.escape(query)}"><input type="submit" value="Search"><input type="hidden" name="page" value="1">2 unmodified lines</body></html>"""paginated_results = results[start_idx:end_idx]63 unmodified lines</head><body><h1>LLM Search Engine</h1><form class="search-box" id="search-form"><input type="text" name="query" value="{html.escape(query)}"><input type="submit" value="Search"><input type="hidden" name="page" value="1">16 unmodified lines# Pagination linksencoded_query = quote(query)prev_link = f'<a href="?query={encoded_query}&page={page-1}" onclick="updatePage(event, \'{encoded_query}\', {page-1})">Previous</a>' if page > 1 else '<span>Previous</span>'next_link = f'<a href="?query={encoded_query}&page={page+1}" onclick="updatePage(event, \'{encoded_query}\', {page+1})">Next</a>' if page < total_pages else '<span>Next</span>'html_content += f"""</div><div class="pagination">1 unmodified line<span>Page {page} of {total_pages}</span>{next_link}</div><script>function updatePage(event, query, page) {{event.preventDefault();window.history.pushState({{}}, '', '?query=' + encodeURIComponent(query) + '&page=' + page);document.getElementById('search-form').query.value = query;document.getElementById('search-form').page.value = page;document.getElementById('search-form').onsubmit(event);}}document.getElementById('search-form').onsubmit = function(event) {{event.preventDefault();var query = this.query.value;var page = this.page.value;window.location.href = '?query=' + encodeURIComponent(query) + '&page=' + page;}};</script></body></html>"""return html_content# Define the Gradio app with Blockswith gr.Blocks(title="LLM Search Engine") as app:output_html = gr.HTML()def update_page(query, page):try:page = int(page)except (ValueError, TypeError):page = 1return generate_search_page(query, page)# Initial load with URL parametersapp.load(fn=update_page,inputs=None,outputs=output_html,_js="() => [new URLSearchParams(window.location.search).get('query') || '', new URLSearchParams(window.location.search).get('page') || '1']")app.launch()12345678910111251 unmodified lines64656667686970717273747576777879808182838485862 unmodified lines89909192939495969798991001011021031041052 unmodified lines1081091101111121131142 unmodified lines1171181191201211221231241251261271282 unmodified lines13113213313413513613763 unmodified lines20120220320420520620716 unmodified lines2242252262272282292302311 unmodified line233234235236237238239240241242243from flask import Flask, request, render_template_stringfrom openai import OpenAIimport osimport jsonfrom urllib.parse import quoteimport htmlapp = Flask(__name__)# Initialize OpenAI client with API key and base URL from environment variablesclient = OpenAI(api_key=os.environ["OPENAI_API_KEY"],51 unmodified lineselse:return None, f"Error: {error_msg}"@app.route('/', methods=['GET'])def search_page():"""Generate and serve the search results page."""query = request.args.get('query', '')page = request.args.get('page', '1')try:page = int(page)except ValueError:page = 1if not query.strip():html_content = """<html><head><title>LLM Search Engine</title></head><body style="font-family: Arial, sans-serif;"><h1>LLM Search Engine</h1><form method="get" action="/"><input type="text" name="query" placeholder="Type your search here..."><input type="submit" value="Search"><input type="hidden" name="page" value="1">2 unmodified lines</body></html>"""return render_template_string(html_content)results, error = fetch_search_results(query)if error:html_content = f"""<html><head><title>LLM Search Engine</title></head><body style="font-family: Arial, sans-serif;"><h1>LLM Search Engine</h1><form method="get" action="/"><input type="text" name="query" value="{html.escape(query)}"><input type="submit" value="Search"><input type="hidden" name="page" value="1">2 unmodified lines</body></html>"""return render_template_string(html_content)# Calculate pagination boundariesstart_idx = (page - 1) * RESULTS_PER_PAGE2 unmodified lines# Ensure indices are within boundsif start_idx >= len(results):html_content = f"""<html><head><title>LLM Search Engine</title></head><body style="font-family: Arial, sans-serif;"><h1>LLM Search Engine</h1><form method="get" action="/"><input type="text" name="query" value="{html.escape(query)}"><input type="submit" value="Search"><input type="hidden" name="page" value="1">2 unmodified lines</body></html>"""return render_template_string(html_content)paginated_results = results[start_idx:end_idx]63 unmodified lines</head><body><h1>LLM Search Engine</h1><form class="search-box" method="get" action="/"><input type="text" name="query" value="{html.escape(query)}"><input type="submit" value="Search"><input type="hidden" name="page" value="1">16 unmodified lines# Pagination linksencoded_query = quote(query)prev_link = f'<a href="/?query={encoded_query}&page={page-1}">Previous</a>' if page > 1 else '<span>Previous</span>'next_link = f'<a href="/?query={encoded_query}&page={page+1}">Next</a>' if page < total_pages else '<span>Next</span>'html_content += f"""</div><div class="pagination">1 unmodified line<span>Page {page} of {total_pages}</span>{next_link}</div></body></html>"""return render_template_string(html_content)if __name__ == '__main__':app.run(debug=True, host='0.0.0.0', port=int(os.environ.get("PORT", 5000)))
app.py+28-48