Spaces:
Runtime error
Runtime error
Create app.py
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206import streamlit as stfrom langchain_groq import ChatGroqfrom langchain.chains import LLMChainfrom langchain.prompts import PromptTemplatefrom duckduckgo_search import DDGSfrom langchain_community.tools import DuckDuckGoSearchRunfrom langchain_community.utilities import DuckDuckGoSearchAPIWrapperimport reimport clipboardimport ioimport osimport pandas as pdfrom PyPDF2 import PdfFileReaderfrom PIL import Imageimport pytesseractimport requestsfrom bs4 import BeautifulSoup
# Groq APIキーの設定GROQ_API_KEY = os.getenv("GROQ_API_KEY")
# Streamlitアプリケーションの設定st.set_page_config(page_title="COM COM AI", page_icon="🤖", layout="wide")
# セッション状態の初期化if 'messages' not in st.session_state: st.session_state.messages = []if 'uploaded_file_content' not in st.session_state: st.session_state.uploaded_file_content = None
def read_pdf(file): pdf = PdfFileReader(file) content = "" for page_num in range(pdf.getNumPages()): page = pdf.getPage(page_num) content += page.extract_text() return content
def read_csv(file): df = pd.read_csv(file) return df.to_string()
def read_image(file): image = Image.open(file) text = pytesseract.image_to_string(image) return text
def fetch_webpage_text(url): response = requests.get(url) if response.status_code != 200: return "ウェブページを取得できませんでした。" soup = BeautifulSoup(response.text, 'html.parser') paragraphs = soup.find_all('p') text_content = ' '.join([paragraph.get_text() for paragraph in paragraphs]) return text_content
# サイドバーにAIモデルの選択、モード選択、ファイルアップロードを配置with st.sidebar: ai_model = st.selectbox( "AIモデルを選択してください", ["gemma-7b-it", "gemma2-9b-it", "llama3-70b-8192", "llama3-8b-8192", "mixtral-8x7b-32768"], key="model_select" ) mode = st.selectbox( "モードを選択してください", ["focus", "writing", "summary", "知恵袋", "video"], key="mode_select" ) # ファイルアップロード機能 uploaded_file = st.file_uploader("ファイルをアップロード", type=["txt", "pdf", "csv", "py", "html", "css", "js", "cs", "php", "java", "png", "jpg"]) if uploaded_file is not None: file_extension = uploaded_file.name.split('.')[-1].lower() if file_extension in ['txt', 'py', 'html', 'css', 'js', 'cs', 'php', 'java']: stringio = io.StringIO(uploaded_file.getvalue().decode("utf-8")) st.session_state.uploaded_file_content = stringio.read() elif file_extension == 'pdf': st.session_state.uploaded_file_content = read_pdf(uploaded_file) elif file_extension == 'csv': st.session_state.uploaded_file_content = read_csv(uploaded_file) elif file_extension in ['png', 'jpg']: st.session_state.uploaded_file_content = read_image(uploaded_file) st.success(f"ファイル '{uploaded_file.name}' がアップロードされました。") # 会話をクリアするボタン if st.button("🔥 会話をクリア"): st.session_state.messages = [] st.session_state.uploaded_file_content = None
# メインコンテンツst.title("COM COM AI")
# チャット履歴の表示for message in st.session_state.messages: with st.chat_message(message["role"]): st.markdown(message["content"])
# ユーザー入力if prompt := st.chat_input("メッセージを入力してください"): st.session_state.messages.append({"role": "user", "content": prompt}) with st.chat_message("user"): st.markdown(prompt)
# LLMの初期化 llm = ChatGroq(temperature=0.7, groq_api_key=GROQ_API_KEY, model_name=ai_model)
with st.chat_message("assistant"): message_placeholder = st.empty() full_response = ""
# アップロードされたファイルの内容を考慮してプロンプトを作成 if st.session_state.uploaded_file_content: prompt = f"以下のファイル内容を参考にして回答してください:\n\n{st.session_state.uploaded_file_content}\n\nユーザーの質問: {prompt}"
if mode == "focus": # DuckDuckGo検索の実行 with DDGS() as ddgs: search_results = list(ddgs.text(prompt, max_results=5))
prompt_template = PromptTemplate( input_variables=["query", "search_results"], template="質問: {query}\n\n検索結果: {search_results}\n\n上記の情報に基づいて、詳細な回答を提供してください:" )
chain = LLMChain(llm=llm, prompt=prompt_template) full_response = chain.invoke({"query": prompt, "search_results": search_results})["text"]
message_placeholder.markdown(full_response) if search_results: for result in search_results[:3]: st.markdown(f"参考URL: {result['href']}")
elif mode == "writing": prompt_template = PromptTemplate( input_variables=["topic"], template="次のトピックについて包括的な記事を書いてください: {topic}\n\n導入、主要なポイント、および結論を含めてください。" )
chain = LLMChain(llm=llm, prompt=prompt_template) full_response = chain.invoke({"topic": prompt})["text"]
message_placeholder.markdown(full_response)
elif mode == "summary": prompt_template = PromptTemplate( input_variables=["text"], template="次のテキストを簡潔に要約してください:\n\n{text}\n\n主要なポイントを捉えた簡潔な要約を提供してください。" )
chain = LLMChain(llm=llm, prompt=prompt_template) full_response = chain.invoke({"text": prompt})["text"]
message_placeholder.markdown(full_response)
elif mode == "知恵袋": prompt_template = PromptTemplate( input_variables=["question"], template="あなたは知恵袋の回答者です。以下の質問に対して、丁寧かつ詳細に回答してください:\n\n質問: {question}\n\n回答:" )
chain = LLMChain(llm=llm, prompt=prompt_template) full_response = chain.invoke({"question": prompt})["text"]
message_placeholder.markdown(full_response)
elif mode == "video": ddg_search = DuckDuckGoSearchAPIWrapper() videos = ddg_search.results(f"{prompt} site:youtube.com", max_results=5) if videos: for video in videos[:4]: video_url = video['link'] video_id = None youtube_patterns = [ r"(?<=v=)[^&#]+", r"(?<=be/)[^&#]+", r"(?<=embed/)[^&#]+" ] for pattern in youtube_patterns: match = re.search(pattern, video_url) if match: video_id = match.group() break if video_id: st.markdown(f""" <div style="position: relative; padding-bottom: 56.25%; height: 0; overflow: hidden;"> <iframe src="https://www.youtube.com/embed/{video_id}?playsinline=1" style="position: absolute; top: 0; left: 0; width: 100%; height: 100%;" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen> </iframe> </div> """, unsafe_allow_html=True) st.markdown(f"関連動画: {video['title']}") else: st.warning(f"動画IDを抽出できませんでした: {video_url}") else: full_response = "関連動画が見つかりませんでした。" message_placeholder.markdown(full_response)
# コピー機能の追加 if st.button("📋 生成されたテキストをコピー"): clipboard.copy(full_response) st.success("テキストがクリップボードにコピーされました!")app.pyAdded+206