supertakerin2 commited on
Commit
2bd32ae
·
verified ·
1 Parent(s): 2298fb1

Delete app.py

Browse files
Files changed (1) hide show
  1. app.py +0 -207
app.py DELETED
@@ -1,207 +0,0 @@
1
- import streamlit as st
2
- from langchain_groq import ChatGroq
3
- from langchain.chains import LLMChain
4
- from langchain.prompts import PromptTemplate
5
- from duckduckgo_search import DDGS
6
- from langchain_community.tools import DuckDuckGoSearchRun
7
- from langchain_community.utilities import DuckDuckGoSearchAPIWrapper
8
- import re
9
- import clipboard
10
- import io
11
- import os
12
- import pandas as pd
13
- from PyPDF2 import PdfFileReader
14
- from PIL import Image
15
- import pytesseract
16
- import requests
17
- from bs4 import BeautifulSoup
18
-
19
- # Groq APIキーの設定
20
- GROQ_API_KEY = os.getenv("GROQ_API_KEY")
21
-
22
- # Streamlitアプリケーションの設定
23
- st.set_page_config(page_title="COM COM AI", page_icon="🤖", layout="wide")
24
-
25
- # セッション状態の初期化
26
- if 'messages' not in st.session_state:
27
- st.session_state.messages = []
28
- if 'uploaded_file_content' not in st.session_state:
29
- st.session_state.uploaded_file_content = None
30
-
31
- def read_pdf(file):
32
- pdf = PdfFileReader(file)
33
- content = ""
34
- for page_num in range(pdf.getNumPages()):
35
- page = pdf.getPage(page_num)
36
- content += page.extract_text()
37
- return content
38
-
39
- def read_csv(file):
40
- df = pd.read_csv(file)
41
- return df.to_string()
42
-
43
- def read_image(file):
44
- image = Image.open(file)
45
- text = pytesseract.image_to_string(image)
46
- return text
47
-
48
- def fetch_webpage_text(url):
49
- response = requests.get(url)
50
- if response.status_code != 200:
51
- return "ウェブページを取得できませんでした。"
52
- soup = BeautifulSoup(response.text, 'html.parser')
53
- paragraphs = soup.find_all('p')
54
- text_content = ' '.join([paragraph.get_text() for paragraph in paragraphs])
55
- return text_content
56
-
57
- # サイドバーにAIモデルの選択、モード選択、ファイルアップロードを配置
58
- with st.sidebar:
59
- ai_model = st.selectbox(
60
- "AIモデルを選択してください",
61
- ["gemma-7b-it", "gemma2-9b-it", "llama3-70b-8192", "llama3-8b-8192", "mixtral-8x7b-32768"],
62
- key="model_select"
63
- )
64
- mode = st.selectbox(
65
- "モードを選択してください",
66
- ["focus", "writing", "summary", "知恵袋", "video"],
67
- key="mode_select"
68
- )
69
-
70
- # ファイルアップロード機能
71
- uploaded_file = st.file_uploader("ファイルをアップロード", type=["txt", "pdf", "csv", "py", "html", "css", "js", "cs", "php", "java", "png", "jpg"])
72
- if uploaded_file is not None:
73
- file_extension = uploaded_file.name.split('.')[-1].lower()
74
- if file_extension in ['txt', 'py', 'html', 'css', 'js', 'cs', 'php', 'java']:
75
- stringio = io.StringIO(uploaded_file.getvalue().decode("utf-8"))
76
- st.session_state.uploaded_file_content = stringio.read()
77
- elif file_extension == 'pdf':
78
- st.session_state.uploaded_file_content = read_pdf(uploaded_file)
79
- elif file_extension == 'csv':
80
- st.session_state.uploaded_file_content = read_csv(uploaded_file)
81
- elif file_extension in ['png', 'jpg']:
82
- st.session_state.uploaded_file_content = read_image(uploaded_file)
83
- st.success(f"ファイル '{uploaded_file.name}' がアップロードされました。")
84
-
85
- # 会話をクリアするボタン
86
- if st.button("🔥 会話をクリア"):
87
- st.session_state.messages = []
88
- st.session_state.uploaded_file_content = None
89
-
90
- # メインコンテンツ
91
- st.title("COM COM AI")
92
-
93
- # チャット履歴の表示
94
- for message in st.session_state.messages:
95
- with st.chat_message(message["role"]):
96
- st.markdown(message["content"])
97
-
98
- # ユーザー入力
99
- if prompt := st.chat_input("メッセージを入力してください"):
100
- st.session_state.messages.append({"role": "user", "content": prompt})
101
- with st.chat_message("user"):
102
- st.markdown(prompt)
103
-
104
- # LLMの初期化
105
- llm = ChatGroq(temperature=0.7, groq_api_key=GROQ_API_KEY, model_name=ai_model)
106
-
107
- with st.chat_message("assistant"):
108
- message_placeholder = st.empty()
109
- full_response = ""
110
-
111
- # アップロードされたファイルの内容を考慮してプロンプトを作成
112
- if st.session_state.uploaded_file_content:
113
- prompt = f"以下のファイル内容を参考にして回答してください:\n\n{st.session_state.uploaded_file_content}\n\nユーザーの質問: {prompt}"
114
-
115
- if mode == "focus":
116
- # DuckDuckGo検索の実行
117
- with DDGS() as ddgs:
118
- search_results = list(ddgs.text(prompt, max_results=5))
119
-
120
- prompt_template = PromptTemplate(
121
- input_variables=["query", "search_results"],
122
- template="質問: {query}\n\n検索結果: {search_results}\n\n上記の情報に基づいて、詳細な回答を提供してください:"
123
- )
124
-
125
- chain = LLMChain(llm=llm, prompt=prompt_template)
126
- full_response = chain.invoke({"query": prompt, "search_results": search_results})["text"]
127
-
128
- message_placeholder.markdown(full_response)
129
- if search_results:
130
- for result in search_results[:3]:
131
- st.markdown(f"参考URL: {result['href']}")
132
-
133
- elif mode == "writing":
134
- prompt_template = PromptTemplate(
135
- input_variables=["topic"],
136
- template="次のトピックについて包括的な記事を書いてください: {topic}\n\n導入、主要なポイント、および結論を含めてください。"
137
- )
138
-
139
- chain = LLMChain(llm=llm, prompt=prompt_template)
140
- full_response = chain.invoke({"topic": prompt})["text"]
141
-
142
- message_placeholder.markdown(full_response)
143
-
144
- elif mode == "summary":
145
- prompt_template = PromptTemplate(
146
- input_variables=["text"],
147
- template="次のテキストを簡潔に要約してください:\n\n{text}\n\n主要なポイントを捉えた簡潔な要約を提供してください。"
148
- )
149
-
150
- chain = LLMChain(llm=llm, prompt=prompt_template)
151
- full_response = chain.invoke({"text": prompt})["text"]
152
-
153
- message_placeholder.markdown(full_response)
154
-
155
- elif mode == "知恵袋":
156
- prompt_template = PromptTemplate(
157
- input_variables=["question"],
158
- template="あなたは知恵袋の回答者です。以下の質問に対して、丁寧かつ詳細に回答してください:\n\n質問: {question}\n\n回答:"
159
- )
160
-
161
- chain = LLMChain(llm=llm, prompt=prompt_template)
162
- full_response = chain.invoke({"question": prompt})["text"]
163
-
164
- message_placeholder.markdown(full_response)
165
-
166
- elif mode == "video":
167
- ddg_search = DuckDuckGoSearchAPIWrapper()
168
- videos = ddg_search.results(f"{prompt} site:youtube.com", max_results=5)
169
-
170
- if videos:
171
- for video in videos[:4]:
172
- video_url = video['link']
173
- video_id = None
174
- youtube_patterns = [
175
- r"(?<=v=)[^&#]+",
176
- r"(?<=be/)[^&#]+",
177
- r"(?<=embed/)[^&#]+"
178
- ]
179
- for pattern in youtube_patterns:
180
- match = re.search(pattern, video_url)
181
- if match:
182
- video_id = match.group()
183
- break
184
-
185
- if video_id:
186
- invidious_instance = "https://invidious.snopyta.org" # 任意のInvidiousインスタンスを使用
187
- st.markdown(f"""
188
- <div style="position: relative; padding-bottom: 56.25%; height: 0; overflow: hidden;">
189
- <iframe src="{invidious_instance}/embed/{video_id}?playsinline=1&autoplay=1&mute=1"
190
- style="position: absolute; top: 0; left: 0; width: 100%; height: 100%;"
191
- frameborder="0"
192
- allow="autoplay; encrypted-media"
193
- allowfullscreen>
194
- </iframe>
195
- </div>
196
- """, unsafe_allow_html=True)
197
- st.markdown(f"関連動画: {video['title']}")
198
- else:
199
- st.warning(f"動画IDを抽出できませんでした: {video_url}")
200
- else:
201
- full_response = "関連動画が見つかりませんでした。"
202
- message_placeholder.markdown(full_response)
203
-
204
- # コピー機能の追加
205
- if st.button("📋 生成されたテキストをコピー"):
206
- clipboard.copy(full_response)
207
- st.success("テキストがクリップボードにコピーされました!")