import gradio as gr from google import genai import httpx import tempfile import os # Retrieve API key from environment variable client = genai.Client(api_key=os.getenv("GOOGLE_API_KEY")) def invoke(question): doc_url = "https://www.twse.com.tw/pdf/ch/"+question+"_ch.pdf" doc_data = httpx.get(doc_url) if doc_data.status_code != 200: response = '查無股票代號!請輸入台灣上市股票代號!' else: with tempfile.NamedTemporaryFile(suffix=".pdf", delete=False) as temp_file: temp_file.write(doc_data.content) temp_file_path = temp_file.name sample_doc = client.files.upload(file=temp_file_path) prompt = "你是投信分析師,請以中文分項說明公司股市價量表現、融資融卷、內外資進出及財務資訊,並分析近期公司股市展望給投資人具體的專業建議!" try: response = client.models.generate_content( model="gemini-2.0-flash", contents=[sample_doc, "請摘要說明"], config=genai.types.GenerateContentConfig( max_output_tokens=3000, temperature=0.3,) ).text except: response = 'Gemini 回應出錯!請輸入台灣上市股票代號!' return response description = """請輸入台灣上市股票代號!""" gr.close_all() demo = gr.Interface(fn = invoke, inputs = [gr.Textbox(label = "Question", lines = 1)], outputs = [gr.Textbox(label = "Response", lines = 1)], title = "Generative AI - Gemini", description = description) demo.launch()