Spaces:
Sleeping
Sleeping
Upload folder using huggingface_hub
Browse filesFiles changed (6)
- .gitattributes+1
- app.pyAdded+434
- embedding.pyAdded+48
- faiss_index/index.faissAdded+3
- faiss_index/index.pklAdded+3
- requirements.txt+91-3
32 unmodified lines33343532 unmodified lines*.zip filter=lfs diff=lfs merge=lfs -text*.zst filter=lfs diff=lfs merge=lfs -text*tfevents* filter=lfs diff=lfs merge=lfs -text32 unmodified lines3334353632 unmodified lines*.zip filter=lfs diff=lfs merge=lfs -text*.zst filter=lfs diff=lfs merge=lfs -text*tfevents* filter=lfs diff=lfs merge=lfs -textfaiss_index/index.faiss filter=lfs diff=lfs merge=lfs -text
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434import streamlit as stimport osimport jsonimport timefrom datetime import datetimefrom dotenv import load_dotenvfrom langchain_openai import OpenAIEmbeddings, ChatOpenAIfrom langchain_community.vectorstores import FAISSfrom langchain_classic.chains import RetrievalQAfrom langchain_core.prompts import PromptTemplate
# βββ Page Config ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββst.set_page_config( page_title="Multi-Model Research Assistant", page_icon="π¬", layout="wide", initial_sidebar_state="expanded")
# βββ Custom CSS βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββst.markdown("""<style>@import url('https://fonts.googleapis.com/css2?family=JetBrains+Mono:wght@400;600&family=Syne:wght@400;700;800&display=swap');
/* Base */html, body, [class*="css"] { font-family: 'Syne', sans-serif;}
/* Hide default streamlit branding */#MainMenu, footer, header {visibility: hidden;}
/* Main background */.stApp { background: #0d0f14; color: #e2e8f0;}
/* Sidebar */[data-testid="stSidebar"] { background: #111318 !important; border-right: 1px solid #1e2130;}[data-testid="stSidebar"] * { color: #c4cad6 !important;}
/* Top title bar */.top-bar { background: linear-gradient(90deg, #0f1117 0%, #141822 100%); border-bottom: 1px solid #1e2535; padding: 1rem 2rem; margin: -1rem -1rem 2rem -1rem; display: flex; align-items: center; gap: 1rem;}.top-bar h1 { font-family: 'Syne', sans-serif; font-weight: 800; font-size: 1.6rem; background: linear-gradient(135deg, #60a5fa, #a78bfa, #34d399); -webkit-background-clip: text; -webkit-text-fill-color: transparent; margin: 0;}
/* Model cards */.model-card { background: #13161f; border: 1px solid #1e2535; border-radius: 12px; padding: 1.2rem; height: 100%; transition: border-color 0.2s;}.model-card:hover { border-color: #334155;}.model-badge { display: inline-block; padding: 3px 10px; border-radius: 20px; font-family: 'JetBrains Mono', monospace; font-size: 0.72rem; font-weight: 600; margin-bottom: 0.8rem; letter-spacing: 0.03em;}.badge-Meta { background: #1a2a3a; color: #60a5fa; border: 1px solid #2563eb44; }.badge-qwen { background: #1f2a1a; color: #4ade80; border: 1px solid #16a34a44; }.badge-gemma { background: #2a1a2a; color: #c084fc; border: 1px solid #9333ea44; }
.model-answer { font-size: 0.9rem; line-height: 1.7; color: #cbd5e1; min-height: 120px;}
/* Chat history item */.history-item { background: #13161f; border: 1px solid #1e2535; border-radius: 8px; padding: 0.7rem 1rem; margin-bottom: 0.5rem; cursor: pointer; font-size: 0.85rem; color: #94a3b8; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; transition: all 0.15s;}.history-item:hover { background: #1a1f2e; border-color: #334155; color: #e2e8f0;}.history-timestamp { font-family: 'JetBrains Mono', monospace; font-size: 0.65rem; color: #475569; margin-top: 2px;}
/* Input box */.stChatInputContainer { background: #13161f !important; border: 1px solid #1e2535 !important; border-radius: 12px !important;}
/* Spinner text */.stSpinner > div { border-color: #60a5fa !important;}
/* Divider */hr { border-color: #1e2535 !important; margin: 1rem 0 !important;}
/* Streamlit chat messages */[data-testid="stChatMessage"] { background: #13161f !important; border: 1px solid #1e2535 !important; border-radius: 10px !important; padding: 0.8rem !important; margin-bottom: 0.5rem !important;}
/* Buttons */.stButton > button { background: #1a1f2e !important; color: #94a3b8 !important; border: 1px solid #1e2535 !important; border-radius: 8px !important; font-family: 'JetBrains Mono', monospace !important; font-size: 0.78rem !important; transition: all 0.15s !important;}.stButton > button:hover { background: #1e2535 !important; color: #e2e8f0 !important; border-color: #334155 !important;}
/* Section headers */.section-label { font-family: 'JetBrains Mono', monospace; font-size: 0.7rem; letter-spacing: 0.12em; color: #475569; text-transform: uppercase; margin-bottom: 0.8rem;}
/* Status dots */.status-dot { width: 8px; height: 8px; border-radius: 50%; display: inline-block; margin-right: 6px;}.dot-green { background: #4ade80; box-shadow: 0 0 6px #4ade8088; }.dot-yellow { background: #fbbf24; box-shadow: 0 0 6px #fbbf2488; }.dot-red { background: #f87171; box-shadow: 0 0 6px #f8717188; }</style>""", unsafe_allow_html=True)
# βββ Constants βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββMODELS = { "Meta R1": { "id": "meta-llama/llama-3.3-70b-instruct", "badge_class": "badge-meta", "icon": "π§ ", "desc": "Best for math & reasoning" }, "Qwen3 30B": { "id": "qwen/qwen3-next-80b-a3b-instruct", "badge_class": "badge-qwen", "icon": "β‘", "desc": "Strong at science & analysis" }, "Gemma 3 27B": { "id": "google/gemma-3-27b-it", "badge_class": "badge-gemma", "icon": "β¨", "desc": "Balanced & instruction-tuned" }}
HISTORY_FILE = "chat_history.json"
# βββ History Helpers βββββββββββββββββββββββββββββββββββββββββββββββββββββββββdef load_history(): if os.path.exists(HISTORY_FILE): with open(HISTORY_FILE, "r") as f: return json.load(f) return []
def save_history(history): with open(HISTORY_FILE, "w") as f: json.dump(history, f, indent=2)
def add_to_history(question, answers: dict): history = load_history() history.insert(0, { "id": str(int(time.time())), "question": question, "answers": answers, "timestamp": datetime.now().strftime("%b %d, %H:%M") }) history = history[:50] # keep last 50 only save_history(history) return history
# βββ RAG Loader ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ@st.cache_resource(show_spinner=False)def load_vectorstore(): load_dotenv() api_key = os.environ.get("OPENROUTER_API_KEY") or os.getenv("OPENROUTER_API_KEY") base_url = "https://openrouter.ai/api/v1" index_path = "faiss_index"
if not os.path.exists(index_path): return None, "β No FAISS index found. Run `rag_engine.py` first."
embeddings = OpenAIEmbeddings( model="qwen/qwen3-embedding-8b", openai_api_key=api_key, openai_api_base=base_url, check_embedding_ctx_length=False ) vectorstore = FAISS.load_local( index_path, embeddings, allow_dangerous_deserialization=True ) return vectorstore, None
def build_chain(vectorstore, model_id: str): load_dotenv() api_key = os.environ.get("OPENROUTER_API_KEY") or os.getenv("OPENROUTER_API_KEY") base_url = "https://openrouter.ai/api/v1"
llm = ChatOpenAI( model=model_id, openai_api_key=api_key, openai_api_base=base_url, temperature=0.3, max_tokens=800 )
template = """Use the following context to answer the question.If the answer involves mathematical formulas, format them using LaTeX syntax($$ for block equations, $ for inline math).If the answer is NOT in the context, say: "I don't have enough information in the provided documents to answer this."
Context: {context}
Question: {question}
Answer (Markdown + LaTeX if needed):"""
prompt = PromptTemplate(input_variables=["context", "question"], template=template)
return RetrievalQA.from_chain_type( llm=llm, chain_type="stuff", retriever=vectorstore.as_retriever(search_kwargs={"k": 4}), chain_type_kwargs={"prompt": prompt} )
def query_model(vectorstore, model_id: str, question: str) -> str: try: chain = build_chain(vectorstore, model_id) result = chain.invoke(question)["result"] return result except Exception as e: if "402" in str(e): return "β οΈ Insufficient credits on OpenRouter." elif "rate" in str(e).lower(): return "β οΈ Rate limit hit. Please wait a moment and retry." else: return f"β οΈ Error: {str(e)}"
# βββ Session State Init βββββββββββββββββββββββββββββββββββββββββββββββββββββββif "chat_history" not in st.session_state: st.session_state.chat_history = load_history()
if "current_question" not in st.session_state: st.session_state.current_question = None
if "current_answers" not in st.session_state: st.session_state.current_answers = {}
if "selected_history" not in st.session_state: st.session_state.selected_history = None
# βββ Sidebar βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββwith st.sidebar: st.markdown('<div class="section-label">β System Status</div>', unsafe_allow_html=True)
vectorstore, vs_error = load_vectorstore() if vs_error: st.markdown(f'<span class="status-dot dot-red"></span> Index not found', unsafe_allow_html=True) st.error(vs_error) else: st.markdown('<span class="status-dot dot-green"></span> Knowledge base ready', unsafe_allow_html=True)
st.markdown("---") st.markdown('<div class="section-label">π€ Active Models</div>', unsafe_allow_html=True) for name, info in MODELS.items(): st.markdown(f"{info['icon']} **{name}** β _{info['desc']}_")
st.markdown("---") st.markdown('<div class="section-label">π Chat History</div>', unsafe_allow_html=True)
if st.button("π Clear History", use_container_width=True): st.session_state.chat_history = [] if os.path.exists(HISTORY_FILE): os.remove(HISTORY_FILE) st.session_state.selected_history = None st.rerun()
st.markdown("") for item in st.session_state.chat_history: label = item["question"][:42] + "..." if len(item["question"]) > 42 else item["question"] if st.button(f"π¬ {label}", key=f"hist_{item['id']}", use_container_width=True): st.session_state.selected_history = item st.session_state.current_question = item["question"] st.session_state.current_answers = item["answers"]
# βββ Main Area βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββst.markdown("""<div class="top-bar"> <h1>π¬ Multi-Model Research Assistant</h1></div>""", unsafe_allow_html=True)
# Show current Q&A if anyif st.session_state.current_question: st.markdown(f"#### π {st.session_state.current_question}") st.markdown("---")
cols = st.columns(3) for i, (name, info) in enumerate(MODELS.items()): with cols[i]: answer = st.session_state.current_answers.get(name, "_No answer yet._") st.markdown(f""" <div class="model-card"> <span class="model-badge {info['badge_class']}">{info['icon']} {name}</span> <div class="model-answer"> """, unsafe_allow_html=True) st.markdown(answer) st.markdown("</div></div>", unsafe_allow_html=True)
st.markdown("---")
else: # Welcome screen st.markdown(""" <div style="text-align:center; padding: 3rem 0; color: #475569;"> <div style="font-size: 3rem; margin-bottom: 1rem;">π</div> <div style="font-family: 'Syne', sans-serif; font-size: 1.2rem; color: #64748b;"> Ask anything β get answers from 3 models simultaneously </div> <div style="font-size: 0.85rem; margin-top: 0.5rem; color: #334155;"> Meta R1 Β· Qwen3 30B Β· Gemma 3 27B </div> </div> """, unsafe_allow_html=True)
# βββ Chat Input βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββif prompt := st.chat_input("Ask about your documents..."): if not vectorstore: st.error("Knowledge base not loaded. Please run `rag_engine.py` first.") else: st.session_state.current_question = prompt st.session_state.current_answers = {} st.session_state.selected_history = None
# Show question immediately st.markdown(f"#### π {prompt}") st.markdown("---")
cols = st.columns(3) answers = {}
for i, (name, info) in enumerate(MODELS.items()): with cols[i]: st.markdown(f""" <div class="model-card"> <span class="model-badge {info['badge_class']}">{info['icon']} {name}</span> """, unsafe_allow_html=True)
with st.spinner(f"Querying {name}..."): ans = query_model(vectorstore, info["id"], prompt)
answers[name] = ans st.markdown(ans) st.markdown("</div>", unsafe_allow_html=True)
# Save to history st.session_state.current_answers = answers st.session_state.chat_history = add_to_history(prompt, answers) st.rerun()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748import osfrom dotenv import load_dotenvfrom langchain_community.document_loaders import DirectoryLoader, TextLoaderfrom langchain_text_splitters import RecursiveCharacterTextSplitterfrom langchain_openai import OpenAIEmbeddingsfrom langchain_community.vectorstores import FAISS
def run_embedding_pipeline(folder_path, index_name="faiss_index"): load_dotenv() api_key = os.getenv("OPENROUTER_API_KEY") base_url = "https://openrouter.ai/api/v1" if not api_key: print("β Error: OPENROUTER_API_KEY not found in .env file.") return
# 1. Load Documents from Folder print(f"π Loading .txt files from: {folder_path}...") loader = DirectoryLoader(folder_path, glob="*.txt", loader_cls=TextLoader) documents = loader.load() if not documents: print("β οΈ No documents found. Check your folder path.") return
# 2. Chunking print("βοΈ Splitting documents into chunks...") text_splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=150) texts = text_splitter.split_documents(documents)
# 3. Create Embeddings using Qwen3-8B print("𧬠Generating embeddings (this may take a moment)...") embeddings = OpenAIEmbeddings( model="qwen/qwen3-embedding-8b", openai_api_key=api_key, openai_api_base=base_url, check_embedding_ctx_length=False )
# 4. Save Vector Store Locally vectorstore = FAISS.from_documents(texts, embeddings) vectorstore.save_local(index_name) print(f"β
Success! Vector database saved to folder: '{index_name}'")
if __name__ == "__main__": # Change "pages_text" to your actual folder name target_folder = "pages_text" run_embedding_pipeline(target_folder)123version https://git-lfs.github.com/spec/v1oid sha256:429aa0357143e22fe6eccb3bfdbe3479a162b579eba2b297cc2452d7ad3f9a27size 11288621123version https://git-lfs.github.com/spec/v1oid sha256:2f7099cd35e9a032f803b3cf29b1b28fed8a1d080c5ea4cf997569fe801729absize 571319123altairpandasstreamlit12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091aiohappyeyeballs==2.6.1aiohttp==3.13.3aiosignal==1.4.0altair==6.0.0annotated-types==0.7.0anyio==4.12.1attrs==25.4.0blinker==1.9.0cachetools==7.0.3certifi==2026.2.25charset-normalizer==3.4.5click==8.3.1dataclasses-json==0.6.7distro==1.9.0faiss-cpu==1.13.2frozenlist==1.8.0gitdb==4.0.12GitPython==3.1.46greenlet==3.3.2h11==0.16.0httpcore==1.0.9httpx==0.28.1httpx-sse==0.4.3idna==3.11Jinja2==3.1.6jiter==0.13.0jsonpatch==1.33jsonpointer==3.0.0jsonschema==4.26.0jsonschema-specifications==2025.9.1langchain==1.2.10langchain-classic==1.0.2langchain-community==0.4.1langchain-core==1.2.17langchain-openai==1.1.10langchain-text-splitters==1.1.1langgraph==1.0.10langgraph-checkpoint==4.0.1langgraph-prebuilt==1.0.8langgraph-sdk==0.3.9langsmith==0.7.14MarkupSafe==3.0.3marshmallow==3.26.2multidict==6.7.1mypy_extensions==1.1.0narwhals==2.17.0numpy==2.4.2openai==2.26.0orjson==3.11.7ormsgpack==1.12.2packaging==26.0pandas==2.3.3pdf2image==1.17.0pillow==12.1.1propcache==0.4.1protobuf==6.33.5pyarrow==23.0.1pydantic==2.12.5pydantic-settings==2.13.1pydantic_core==2.41.5pydeck==0.9.1pytesseract==0.3.13python-dateutil==2.9.0.post0python-dotenv==1.2.2pytz==2026.1.post1PyYAML==6.0.3referencing==0.37.0regex==2026.2.28requests==2.32.5requests-toolbelt==1.0.0rpds-py==0.30.0six==1.17.0smmap==5.0.2sniffio==1.3.1SQLAlchemy==2.0.48streamlit==1.55.0tenacity==9.1.4tiktoken==0.12.0toml==0.10.2tornado==6.5.4tqdm==4.67.3typing-inspect==0.9.0typing-inspection==0.4.2typing_extensions==4.15.0tzdata==2025.3urllib3==2.6.3uuid_utils==0.14.1watchdog==6.0.0xxhash==3.6.0yarl==1.23.0zstandard==0.25.0
.gitattributes+1
app.pyAdded+434
embedding.pyAdded+48
faiss_index/index.faissAdded+3
faiss_index/index.pklAdded+3
requirements.txt+91-3