Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,50 +1,67 @@
|
|
| 1 |
import streamlit as st
|
| 2 |
import tempfile
|
| 3 |
import os
|
|
|
|
|
|
|
| 4 |
|
| 5 |
-
# --- HUGGING FACE İÇİN SQLITE FIX
|
| 6 |
try:
|
| 7 |
__import__('pysqlite3')
|
| 8 |
import sys
|
| 9 |
sys.modules['sqlite3'] = sys.modules.pop('pysqlite3')
|
| 10 |
except ImportError:
|
| 11 |
pass
|
| 12 |
-
# ------------------------------------
|
| 13 |
|
| 14 |
from langchain_community.document_loaders import PyPDFLoader
|
| 15 |
from langchain_openai import OpenAIEmbeddings, ChatOpenAI
|
| 16 |
from langchain_community.vectorstores import Chroma
|
| 17 |
-
# --- BURASI DÜZELDİ (Standart Import) ---
|
| 18 |
from langchain.text_splitter import RecursiveCharacterTextSplitter
|
| 19 |
-
# ----------------------------------------
|
| 20 |
from langchain.chains import ConversationalRetrievalChain
|
| 21 |
from langchain.memory import ConversationBufferMemory
|
|
|
|
| 22 |
|
| 23 |
# --- SAYFA AYARLARI ---
|
| 24 |
-
st.set_page_config(page_title="🧠 Advanced RAG
|
| 25 |
-
st.title("
|
| 26 |
st.markdown("""
|
| 27 |
-
Bu asistan
|
| 28 |
-
ve sorularını **hafızasında tutarak** cevaplar.
|
| 29 |
""")
|
| 30 |
|
| 31 |
-
# --- API KEY
|
| 32 |
api_key = os.environ.get("OPENAI_API_KEY")
|
| 33 |
-
|
| 34 |
if not api_key:
|
| 35 |
-
st.warning("⚠️ OpenAI API Key
|
| 36 |
st.stop()
|
| 37 |
|
| 38 |
-
# --- SESSION STATE
|
| 39 |
if "messages" not in st.session_state:
|
| 40 |
-
st.session_state.messages = [{"role": "assistant", "content": "Merhaba!
|
| 41 |
if "processed_data" not in st.session_state:
|
| 42 |
st.session_state.processed_data = None
|
| 43 |
|
| 44 |
-
# ---
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 45 |
def process_pdf(uploaded_file):
|
| 46 |
-
"""PDF'i okur, parçalar ve Vektör DB'ye gömer."""
|
| 47 |
-
# Geçici dosya oluştur
|
| 48 |
with tempfile.NamedTemporaryFile(delete=False, suffix=".pdf") as tmp_file:
|
| 49 |
tmp_file.write(uploaded_file.getvalue())
|
| 50 |
tmp_path = tmp_file.name
|
|
@@ -52,54 +69,59 @@ def process_pdf(uploaded_file):
|
|
| 52 |
loader = PyPDFLoader(tmp_path)
|
| 53 |
documents = loader.load()
|
| 54 |
|
| 55 |
-
# 1. Metni Parçala (Chunking)
|
| 56 |
text_splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=100)
|
| 57 |
chunks = text_splitter.split_documents(documents)
|
| 58 |
|
| 59 |
-
# 2. Embedding ve Vector DB (Chroma)
|
| 60 |
embeddings = OpenAIEmbeddings(openai_api_key=api_key)
|
| 61 |
-
|
| 62 |
-
# Persist directory kullanmadan memory'de tutuyoruz (Hız için)
|
| 63 |
vectorstore = Chroma.from_documents(chunks, embeddings)
|
| 64 |
-
|
| 65 |
-
# Geçici dosyayı sil
|
| 66 |
os.remove(tmp_path)
|
| 67 |
-
|
| 68 |
return vectorstore, len(documents)
|
| 69 |
|
| 70 |
-
# --- SIDEBAR
|
| 71 |
with st.sidebar:
|
| 72 |
-
st.header("📂
|
| 73 |
-
uploaded_file = st.file_uploader("PDF Seç", type="pdf")
|
| 74 |
|
| 75 |
if uploaded_file and st.session_state.processed_data is None:
|
| 76 |
-
with st.spinner("🧠
|
| 77 |
try:
|
| 78 |
vectorstore, page_count = process_pdf(uploaded_file)
|
| 79 |
|
| 80 |
-
#
|
| 81 |
-
|
| 82 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 83 |
|
| 84 |
chain = ConversationalRetrievalChain.from_llm(
|
| 85 |
llm=llm,
|
| 86 |
retriever=vectorstore.as_retriever(),
|
| 87 |
-
memory=memory
|
|
|
|
| 88 |
)
|
| 89 |
|
| 90 |
st.session_state.processed_data = chain
|
| 91 |
|
| 92 |
-
#
|
| 93 |
-
|
| 94 |
-
response = chain.invoke({"question": initial_prompt})
|
| 95 |
-
|
| 96 |
-
st.session_state.messages.append({"role": "assistant", "content": f"✅ **Analiz Tamamlandı! ({page_count} Sayfa)**\n\n{response['answer']}"})
|
| 97 |
st.rerun()
|
| 98 |
|
| 99 |
except Exception as e:
|
| 100 |
-
st.error(f"Hata
|
| 101 |
|
| 102 |
-
if st.button("
|
| 103 |
st.session_state.clear()
|
| 104 |
st.rerun()
|
| 105 |
|
|
@@ -107,25 +129,30 @@ with st.sidebar:
|
|
| 107 |
for msg in st.session_state.messages:
|
| 108 |
with st.chat_message(msg["role"]):
|
| 109 |
st.markdown(msg["content"])
|
|
|
|
|
|
|
| 110 |
|
| 111 |
-
if prompt := st.chat_input("
|
| 112 |
-
# Kullanıcı mesajını ekle
|
| 113 |
st.session_state.messages.append({"role": "user", "content": prompt})
|
| 114 |
with st.chat_message("user"):
|
| 115 |
st.markdown(prompt)
|
| 116 |
|
| 117 |
-
# Cevap üret
|
| 118 |
if st.session_state.processed_data:
|
| 119 |
chain = st.session_state.processed_data
|
| 120 |
-
with st.spinner("
|
| 121 |
try:
|
| 122 |
response = chain.invoke({"question": prompt})
|
| 123 |
answer = response["answer"]
|
| 124 |
|
|
|
|
| 125 |
st.session_state.messages.append({"role": "assistant", "content": answer})
|
| 126 |
with st.chat_message("assistant"):
|
| 127 |
st.markdown(answer)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 128 |
except Exception as e:
|
| 129 |
-
st.error(f"
|
| 130 |
else:
|
| 131 |
-
st.warning("Lütfen önce
|
|
|
|
| 1 |
import streamlit as st
|
| 2 |
import tempfile
|
| 3 |
import os
|
| 4 |
+
import re
|
| 5 |
+
import pandas as pd # Grafik verisi için gerekli
|
| 6 |
|
| 7 |
+
# --- HUGGING FACE İÇİN SQLITE FIX ---
|
| 8 |
try:
|
| 9 |
__import__('pysqlite3')
|
| 10 |
import sys
|
| 11 |
sys.modules['sqlite3'] = sys.modules.pop('pysqlite3')
|
| 12 |
except ImportError:
|
| 13 |
pass
|
| 14 |
+
# ------------------------------------
|
| 15 |
|
| 16 |
from langchain_community.document_loaders import PyPDFLoader
|
| 17 |
from langchain_openai import OpenAIEmbeddings, ChatOpenAI
|
| 18 |
from langchain_community.vectorstores import Chroma
|
|
|
|
| 19 |
from langchain.text_splitter import RecursiveCharacterTextSplitter
|
|
|
|
| 20 |
from langchain.chains import ConversationalRetrievalChain
|
| 21 |
from langchain.memory import ConversationBufferMemory
|
| 22 |
+
from langchain.prompts import PromptTemplate
|
| 23 |
|
| 24 |
# --- SAYFA AYARLARI ---
|
| 25 |
+
st.set_page_config(page_title="🧠 Advanced RAG Analyst", layout="wide")
|
| 26 |
+
st.title("📊 AI Data Analyst (Chat with PDF + Visualization)")
|
| 27 |
st.markdown("""
|
| 28 |
+
Bu asistan **akademik makaleleri okur, özetler ve verileri görselleştirir.** Grafik çizdirmek için: *"Sınıf dağılımını gösteren bir bar grafiği çiz"* diyebilirsiniz.
|
|
|
|
| 29 |
""")
|
| 30 |
|
| 31 |
+
# --- API KEY ---
|
| 32 |
api_key = os.environ.get("OPENAI_API_KEY")
|
|
|
|
| 33 |
if not api_key:
|
| 34 |
+
st.warning("⚠️ OpenAI API Key eksik! Settings sekmesinden ekleyin.")
|
| 35 |
st.stop()
|
| 36 |
|
| 37 |
+
# --- SESSION STATE ---
|
| 38 |
if "messages" not in st.session_state:
|
| 39 |
+
st.session_state.messages = [{"role": "assistant", "content": "Merhaba! Analiz etmem için bir PDF yükle. 📈"}]
|
| 40 |
if "processed_data" not in st.session_state:
|
| 41 |
st.session_state.processed_data = None
|
| 42 |
|
| 43 |
+
# --- GRAFİK ÇİZEN SİHİRLİ FONKSİYON ---
|
| 44 |
+
def extract_and_run_code(text):
|
| 45 |
+
"""
|
| 46 |
+
LLM cevabındaki Python kod bloklarını bulur ve çalıştırır.
|
| 47 |
+
"""
|
| 48 |
+
# Regex ile ```python ... ``` arasındaki kodu bul
|
| 49 |
+
code_pattern = r"```python(.*?)```"
|
| 50 |
+
matches = re.findall(code_pattern, text, re.DOTALL)
|
| 51 |
+
|
| 52 |
+
for code in matches:
|
| 53 |
+
code = code.strip()
|
| 54 |
+
# Güvenlik önlemi: Sadece streamlit ve pandas grafiklerine izin ver
|
| 55 |
+
if "st." in code or "pandas" in code:
|
| 56 |
+
try:
|
| 57 |
+
with st.chat_message("assistant"):
|
| 58 |
+
st.info("📊 Grafik oluşturuluyor...")
|
| 59 |
+
exec(code, {"pd": pd, "st": st}) # Kodu çalıştır
|
| 60 |
+
except Exception as e:
|
| 61 |
+
st.error(f"Grafik çizilirken hata oluştu: {e}")
|
| 62 |
+
|
| 63 |
+
# --- PDF İŞLEME ---
|
| 64 |
def process_pdf(uploaded_file):
|
|
|
|
|
|
|
| 65 |
with tempfile.NamedTemporaryFile(delete=False, suffix=".pdf") as tmp_file:
|
| 66 |
tmp_file.write(uploaded_file.getvalue())
|
| 67 |
tmp_path = tmp_file.name
|
|
|
|
| 69 |
loader = PyPDFLoader(tmp_path)
|
| 70 |
documents = loader.load()
|
| 71 |
|
|
|
|
| 72 |
text_splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=100)
|
| 73 |
chunks = text_splitter.split_documents(documents)
|
| 74 |
|
|
|
|
| 75 |
embeddings = OpenAIEmbeddings(openai_api_key=api_key)
|
|
|
|
|
|
|
| 76 |
vectorstore = Chroma.from_documents(chunks, embeddings)
|
|
|
|
|
|
|
| 77 |
os.remove(tmp_path)
|
|
|
|
| 78 |
return vectorstore, len(documents)
|
| 79 |
|
| 80 |
+
# --- SIDEBAR ---
|
| 81 |
with st.sidebar:
|
| 82 |
+
st.header("📂 Veri Yükleme")
|
| 83 |
+
uploaded_file = st.file_uploader("PDF Raporu Seç", type="pdf")
|
| 84 |
|
| 85 |
if uploaded_file and st.session_state.processed_data is None:
|
| 86 |
+
with st.spinner("🧠 Veri analisti belgeyi inceliyor..."):
|
| 87 |
try:
|
| 88 |
vectorstore, page_count = process_pdf(uploaded_file)
|
| 89 |
|
| 90 |
+
# ÖZEL PROMPT: Grafikleri Kod Olarak İste
|
| 91 |
+
custom_template = """
|
| 92 |
+
Sen uzman bir Veri Bilimci ve AI Analistisin. Verilen bağlamı kullanarak soruları cevapla.
|
| 93 |
+
|
| 94 |
+
Eğer kullanıcı bir GRAFİK veya GÖRSELLEŞTİRME isterse:
|
| 95 |
+
1. Veriyi analiz et.
|
| 96 |
+
2. Python kodu yazarak `st.bar_chart`, `st.line_chart` veya `st.write` kullan.
|
| 97 |
+
3. Kodu ```python ... ``` bloğu içine koy.
|
| 98 |
+
|
| 99 |
+
Bağlam: {context}
|
| 100 |
+
Soru: {question}
|
| 101 |
+
Cevap:
|
| 102 |
+
"""
|
| 103 |
+
PROMPT = PromptTemplate(template=custom_template, input_variables=["context", "question"])
|
| 104 |
+
|
| 105 |
+
llm = ChatOpenAI(temperature=0, model_name="gpt-4o-mini", openai_api_key=api_key)
|
| 106 |
+
memory = ConversationBufferMemory(memory_key="chat_history", return_messages=True, output_key='answer')
|
| 107 |
|
| 108 |
chain = ConversationalRetrievalChain.from_llm(
|
| 109 |
llm=llm,
|
| 110 |
retriever=vectorstore.as_retriever(),
|
| 111 |
+
memory=memory,
|
| 112 |
+
combine_docs_chain_kwargs={"prompt": PROMPT}
|
| 113 |
)
|
| 114 |
|
| 115 |
st.session_state.processed_data = chain
|
| 116 |
|
| 117 |
+
# İlk analiz
|
| 118 |
+
st.session_state.messages.append({"role": "assistant", "content": f"✅ **{page_count} sayfa analiz edildi!** Ne çizmemi istersin?"})
|
|
|
|
|
|
|
|
|
|
| 119 |
st.rerun()
|
| 120 |
|
| 121 |
except Exception as e:
|
| 122 |
+
st.error(f"Hata: {str(e)}")
|
| 123 |
|
| 124 |
+
if st.button("Analizi Sıfırla"):
|
| 125 |
st.session_state.clear()
|
| 126 |
st.rerun()
|
| 127 |
|
|
|
|
| 129 |
for msg in st.session_state.messages:
|
| 130 |
with st.chat_message(msg["role"]):
|
| 131 |
st.markdown(msg["content"])
|
| 132 |
+
# Geçmişteki grafikleri tekrar çizmek zor olduğu için sadece metni gösteriyoruz
|
| 133 |
+
# (Canlı çizim aşağıda yapılıyor)
|
| 134 |
|
| 135 |
+
if prompt := st.chat_input("Örn: Sınıf dağılımını grafiğe dök..."):
|
|
|
|
| 136 |
st.session_state.messages.append({"role": "user", "content": prompt})
|
| 137 |
with st.chat_message("user"):
|
| 138 |
st.markdown(prompt)
|
| 139 |
|
|
|
|
| 140 |
if st.session_state.processed_data:
|
| 141 |
chain = st.session_state.processed_data
|
| 142 |
+
with st.spinner("Analiz yapılıyor & Grafik kodlanıyor..."):
|
| 143 |
try:
|
| 144 |
response = chain.invoke({"question": prompt})
|
| 145 |
answer = response["answer"]
|
| 146 |
|
| 147 |
+
# 1. Metin Cevabı Göster
|
| 148 |
st.session_state.messages.append({"role": "assistant", "content": answer})
|
| 149 |
with st.chat_message("assistant"):
|
| 150 |
st.markdown(answer)
|
| 151 |
+
|
| 152 |
+
# 2. Varsa Grafiği Çiz (Sihir Burada)
|
| 153 |
+
extract_and_run_code(answer)
|
| 154 |
+
|
| 155 |
except Exception as e:
|
| 156 |
+
st.error(f"Hata: {e}")
|
| 157 |
else:
|
| 158 |
+
st.warning("Lütfen önce PDF yükleyin.")
|