Spaces:
Running
Running
refactor: Switch RAG source from static path to dynamic download
Browse files- .gradio/certificate.pem +31 -0
- __pycache__/utils.cpython-311.pyc +0 -0
- app.py +209 -176
- requirements.txt +2 -1
.gradio/certificate.pem
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
-----BEGIN CERTIFICATE-----
|
| 2 |
+
MIIFazCCA1OgAwIBAgIRAIIQz7DSQONZRGPgu2OCiwAwDQYJKoZIhvcNAQELBQAw
|
| 3 |
+
TzELMAkGA1UEBhMCVVMxKTAnBgNVBAoTIEludGVybmV0IFNlY3VyaXR5IFJlc2Vh
|
| 4 |
+
cmNoIEdyb3VwMRUwEwYDVQQDEwxJU1JHIFJvb3QgWDEwHhcNMTUwNjA0MTEwNDM4
|
| 5 |
+
WhcNMzUwNjA0MTEwNDM4WjBPMQswCQYDVQQGEwJVUzEpMCcGA1UEChMgSW50ZXJu
|
| 6 |
+
ZXQgU2VjdXJpdHkgUmVzZWFyY2ggR3JvdXAxFTATBgNVBAMTDElTUkcgUm9vdCBY
|
| 7 |
+
MTCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBAK3oJHP0FDfzm54rVygc
|
| 8 |
+
h77ct984kIxuPOZXoHj3dcKi/vVqbvYATyjb3miGbESTtrFj/RQSa78f0uoxmyF+
|
| 9 |
+
0TM8ukj13Xnfs7j/EvEhmkvBioZxaUpmZmyPfjxwv60pIgbz5MDmgK7iS4+3mX6U
|
| 10 |
+
A5/TR5d8mUgjU+g4rk8Kb4Mu0UlXjIB0ttov0DiNewNwIRt18jA8+o+u3dpjq+sW
|
| 11 |
+
T8KOEU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qpZXjFaH3pO3JLF+l+/+sKAIuvtd7u+Nxe5AW0wdeRlN8NwdC
|
| 26 |
+
jNPElpzVmbUq4JUagEiuTDkHzsxHpFKVK7q4+63SM1N95R1NbdWhscdCb+ZAJzVc
|
| 27 |
+
oyi3B43njTOQ5yOf+1CceWxG1bQVs5ZufpsMljq4Ui0/1lvh+wjChP4kqKOJ2qxq
|
| 28 |
+
4RgqsahDYVvTH9w7jXbyLeiNdd8XM2w9U/t7y0Ff/9yi0GE44Za4rF2LN9d11TPA
|
| 29 |
+
mRGunUHBcnWEvgJBQl9nJEiU0Zsnvgc/ubhPgXRR4Xq37Z0j4r7g1SgEEzwxA57d
|
| 30 |
+
emyPxgcYxn/eR44/KJ4EBs+lVDR3veyJm+kXQ99b21/+jh5Xos1AnX5iItreGCc=
|
| 31 |
+
-----END CERTIFICATE-----
|
__pycache__/utils.cpython-311.pyc
ADDED
|
Binary file (4.28 kB). View file
|
|
|
app.py
CHANGED
|
@@ -1,186 +1,219 @@
|
|
| 1 |
-
import torch
|
| 2 |
-
import transformers
|
| 3 |
import gradio as gr
|
|
|
|
|
|
|
| 4 |
from ragatouille import RAGPretrainedModel
|
| 5 |
-
|
|
|
|
| 6 |
import re
|
| 7 |
from datetime import datetime
|
| 8 |
-
import
|
| 9 |
-
import
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 25 |
|
| 26 |
-
|
| 27 |
-
|
|
|
|
|
|
|
|
|
|
| 28 |
|
|
|
|
| 29 |
try:
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
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|
|
|
|
|
|
|
|
| 84 |
|
| 85 |
-
def get_prompt_text(question, context, formatted = True, llm_model_picked = 'mistralai/Mistral-7B-Instruct-v0.3'):
|
| 86 |
-
if formatted:
|
| 87 |
-
sys_instruction = f"Context:\n {context} \n Given the following scientific paper abstracts, take a deep breath and lets think step by step to answer the question. Cite the titles of your sources when answering, do not cite links or dates."
|
| 88 |
-
message = f"Question: {question}"
|
| 89 |
-
|
| 90 |
-
if 'mistralai' in llm_model_picked:
|
| 91 |
-
return f"<s>" + f"[INST] {sys_instruction}" + f" {message}[/INST]"
|
| 92 |
-
|
| 93 |
-
elif 'gemma' in llm_model_picked:
|
| 94 |
-
return f"<bos><start_of_turn>user\n{sys_instruction}" + f" {message}<end_of_turn>\n"
|
| 95 |
-
|
| 96 |
-
return f"Context:\n {context} \n Given the following info, take a deep breath and lets think step by step to answer the question: {question}. Cite the titles of your sources when answering.\n\n"
|
| 97 |
-
|
| 98 |
-
def get_references(question, retriever, k = retrieve_results):
|
| 99 |
-
rag_out = retriever.search(query=question, k=k)
|
| 100 |
-
return rag_out
|
| 101 |
-
|
| 102 |
-
def get_rag(message):
|
| 103 |
-
return get_references(message, RAG)
|
| 104 |
-
|
| 105 |
-
with gr.Blocks(theme = gr.themes.Soft()) as demo:
|
| 106 |
-
header = gr.Markdown(header_text)
|
| 107 |
-
|
| 108 |
with gr.Group():
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
|
| 126 |
-
|
| 127 |
-
|
| 128 |
-
|
| 129 |
-
|
| 130 |
-
|
| 131 |
-
|
| 132 |
-
|
| 133 |
-
except:
|
| 134 |
-
arxiv_search_success = False
|
| 135 |
-
|
| 136 |
-
|
| 137 |
-
if not arxiv_search_success:
|
| 138 |
-
gr.Warning("Arxiv Search not working, switching to semantic search ...")
|
| 139 |
-
rag_out = get_rag(message)
|
| 140 |
-
database_to_use = index_info
|
| 141 |
-
|
| 142 |
-
md_text_updated = mark_text
|
| 143 |
-
for i in range(retrieve_results):
|
| 144 |
-
rag_answer = rag_out[i]
|
| 145 |
-
if i < llm_results_use:
|
| 146 |
-
md_text_paper, prompt_text = get_md_text_abstract(rag_answer, source = database_to_use, return_prompt_formatting = True)
|
| 147 |
-
prompt_text_from_data += f"{i+1}. {prompt_text}"
|
| 148 |
-
else:
|
| 149 |
-
md_text_paper = get_md_text_abstract(rag_answer, source = database_to_use)
|
| 150 |
-
md_text_updated += md_text_paper
|
| 151 |
-
prompt = get_prompt_text(message, prompt_text_from_data, llm_model_picked = llm_model_picked)
|
| 152 |
-
return md_text_updated, prompt
|
| 153 |
-
|
| 154 |
-
def ask_llm(prompt, llm_model_picked = 'mistralai/Mistral-7B-Instruct-v0.3', stream_outputs = False):
|
| 155 |
-
model_disabled_text = "LLM Model is disabled"
|
| 156 |
-
output = ""
|
| 157 |
-
|
| 158 |
-
if llm_model_picked == 'None':
|
| 159 |
-
if stream_outputs:
|
| 160 |
-
for out in model_disabled_text:
|
| 161 |
-
output += out
|
| 162 |
-
yield output
|
| 163 |
-
return output
|
| 164 |
-
else:
|
| 165 |
-
return model_disabled_text
|
| 166 |
-
|
| 167 |
-
client = InferenceClient(llm_model_picked, token = token)
|
| 168 |
-
try:
|
| 169 |
-
stream = client.text_generation(prompt, **generate_kwargs, stream=stream_outputs, details=False, return_full_text=False)
|
| 170 |
-
|
| 171 |
-
except:
|
| 172 |
-
gr.Warning("LLM Inference rate limit reached, try again later!")
|
| 173 |
-
return ""
|
| 174 |
-
|
| 175 |
-
if stream_outputs:
|
| 176 |
-
for response in stream:
|
| 177 |
-
output += response
|
| 178 |
-
yield output
|
| 179 |
-
return output
|
| 180 |
-
else:
|
| 181 |
-
return stream
|
| 182 |
-
|
| 183 |
-
|
| 184 |
-
msg.submit(update_with_rag_md, [msg, llm_results, database_src, llm_model], [gr_md, input]).success(ask_llm, [input, llm_model, stream_results], output_text)
|
| 185 |
-
|
| 186 |
-
demo.queue().launch()
|
|
|
|
|
|
|
|
|
|
| 1 |
import gradio as gr
|
| 2 |
+
import google.generativeai as genai
|
| 3 |
+
from google.generativeai.types import generation_types
|
| 4 |
from ragatouille import RAGPretrainedModel
|
| 5 |
+
import arxiv
|
| 6 |
+
import os
|
| 7 |
import re
|
| 8 |
from datetime import datetime
|
| 9 |
+
from utils import get_md_text_abstract
|
| 10 |
+
from huggingface_hub import snapshot_download
|
| 11 |
+
|
| 12 |
+
# --- Core Configuration ---
|
| 13 |
+
hf_token = os.getenv("HF_TOKEN")
|
| 14 |
+
gemini_api_key = os.getenv("GEMINI_API_KEY")
|
| 15 |
+
RAG_SOURCE = os.getenv("RAG_SOURCE")
|
| 16 |
+
LOCAL_DATA_DIR = './rag_index_data'
|
| 17 |
+
|
| 18 |
+
LLM_MODELS_TO_CHOOSE = [
|
| 19 |
+
'google/gemma-3-4b-it',
|
| 20 |
+
'google/gemma-3-12b-it',
|
| 21 |
+
'google/gemma-3-27b-it',
|
| 22 |
+
'None'
|
| 23 |
+
]
|
| 24 |
+
DEFAULT_LLM_MODEL = 'google/gemma-3-4b-it'
|
| 25 |
+
RETRIEVE_RESULTS = 20
|
| 26 |
+
|
| 27 |
+
# --- Gemini API Configuration ---
|
| 28 |
+
if gemini_api_key:
|
| 29 |
+
genai.configure(api_key=gemini_api_key)
|
| 30 |
+
else:
|
| 31 |
+
print("CRITICAL WARNING: GEMINI_API_KEY environment variable not set. The application will not function without it.")
|
| 32 |
|
| 33 |
+
GEMINI_GENERATION_CONFIG = genai.types.GenerationConfig(
|
| 34 |
+
temperature=0.2,
|
| 35 |
+
max_output_tokens=450,
|
| 36 |
+
top_p=0.95,
|
| 37 |
+
)
|
| 38 |
|
| 39 |
+
# --- RAG & Data Source Setup ---
|
| 40 |
try:
|
| 41 |
+
gr.Info("Setting up the RAG retriever...")
|
| 42 |
+
# If the local index directory doesn't exist, download it from Hugging Face.
|
| 43 |
+
if not os.path.exists(LOCAL_DATA_DIR):
|
| 44 |
+
if not RAG_SOURCE or not hf_token:
|
| 45 |
+
raise ValueError("RAG index not found locally, and RAG_SOURCE or HF_TOKEN environment variables are not set. Cannot download index.")
|
| 46 |
+
|
| 47 |
+
snapshot_download(
|
| 48 |
+
repo_id=RAG_SOURCE,
|
| 49 |
+
repo_type="dataset", # Your index is stored as a dataset repo
|
| 50 |
+
token=hf_token,
|
| 51 |
+
local_dir=LOCAL_DATA_DIR
|
| 52 |
+
)
|
| 53 |
+
gr.Info("Index downloaded successfully.")
|
| 54 |
+
else:
|
| 55 |
+
gr.Info(f"Found existing local index at {LOCAL_DATA_DIR}.")
|
| 56 |
+
|
| 57 |
+
# Load the RAG model from the (now existing) local index path.
|
| 58 |
+
gr.Info(f'''Loading index from {os.path.join(LOCAL_DATA_DIR, "arxiv_colbert")}...''')
|
| 59 |
+
RAG = RAGPretrainedModel.from_index(os.path.join(LOCAL_DATA_DIR, "arxiv_colbert"))
|
| 60 |
+
RAG.search("Test query", k=1) # Warm-up query
|
| 61 |
+
gr.Info("Retriever loaded successfully!")
|
| 62 |
+
|
| 63 |
+
except Exception as e:
|
| 64 |
+
gr.Warning(f"Could not initialize the RAG retriever. The app may not function correctly. Error: {e}")
|
| 65 |
+
RAG = None
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
# --- UI Text and Metadata ---
|
| 69 |
+
MARKDOWN_SEARCH_RESULTS_HEADER = '# 🔍 Search Results\n'
|
| 70 |
+
APP_HEADER_TEXT = "# ArXiv CS RAG\n"
|
| 71 |
+
INDEX_INFO = "Semantic Search"
|
| 72 |
try:
|
| 73 |
+
with open("README.md", "r") as f:
|
| 74 |
+
mdfile = f.read()
|
| 75 |
+
date_match = re.search(r'Index Last Updated : (\d{4}-\d{2}-\d{2})', mdfile)
|
| 76 |
+
if date_match:
|
| 77 |
+
date = date_match.group(1)
|
| 78 |
+
formatted_date = datetime.strptime(date, '%Y-%m-%d').strftime('%d %b %Y')
|
| 79 |
+
APP_HEADER_TEXT += f'Index Last Updated: {formatted_date}\n'
|
| 80 |
+
INDEX_INFO = f"Semantic Search - up to {formatted_date}"
|
| 81 |
+
except Exception:
|
| 82 |
+
print("README.md not found or is invalid. Using default data source info.")
|
| 83 |
+
|
| 84 |
+
DATABASE_CHOICES = [INDEX_INFO, 'Arxiv Search - Latest - (EXPERIMENTAL)']
|
| 85 |
+
ARX_CLIENT = arxiv.Client()
|
| 86 |
+
|
| 87 |
+
# --- Helper Functions ---
|
| 88 |
+
def get_prompt_text(question, context):
|
| 89 |
+
"""Formats the prompt for the Gemma 3 model."""
|
| 90 |
+
system_instruction = (
|
| 91 |
+
"Based on the provided scientific paper abstracts, provide a comprehensive answer of 6-7 lines. "
|
| 92 |
+
"Synthesize information from multiple sources if possible. Your answer must be grounded in the "
|
| 93 |
+
"details found in the abstracts. Cite the titles of the papers you use as sources in your answer."
|
| 94 |
+
)
|
| 95 |
+
message = f"Abstracts:\n{context}\n\nQuestion: {question}"
|
| 96 |
+
return f"{system_instruction}\n\n{message}"
|
| 97 |
+
|
| 98 |
+
def update_with_rag_md(message, llm_results_use, database_choice):
|
| 99 |
+
"""Fetches documents, updates the UI, and creates the final prompt for the LLM."""
|
| 100 |
+
prompt_context = ""
|
| 101 |
+
rag_out = []
|
| 102 |
+
source_used = database_choice
|
| 103 |
+
|
| 104 |
+
try:
|
| 105 |
+
if database_choice == INDEX_INFO and RAG:
|
| 106 |
+
rag_out = RAG.search(message, k=RETRIEVE_RESULTS)
|
| 107 |
+
else:
|
| 108 |
+
rag_out = list(ARX_CLIENT.results(arxiv.Search(query=message, max_results=RETRIEVE_RESULTS, sort_by=arxiv.SortCriterion.Relevance)))
|
| 109 |
+
if not rag_out:
|
| 110 |
+
gr.Warning("Live Arxiv search returned no results. Falling back to semantic search.")
|
| 111 |
+
if RAG:
|
| 112 |
+
rag_out = RAG.search(message, k=RETRIEVE_RESULTS)
|
| 113 |
+
source_used = INDEX_INFO
|
| 114 |
+
except Exception as e:
|
| 115 |
+
gr.Warning(f"An error occurred during search: {e}. Falling back to semantic search.")
|
| 116 |
+
if RAG:
|
| 117 |
+
rag_out = RAG.search(message, k=RETRIEVE_RESULTS)
|
| 118 |
+
source_used = INDEX_INFO
|
| 119 |
+
|
| 120 |
+
md_text_updated = MARKDOWN_SEARCH_RESULTS_HEADER
|
| 121 |
+
for i, rag_answer in enumerate(rag_out):
|
| 122 |
+
md_text_paper, prompt_text = get_md_text_abstract(rag_answer, source=source_used, return_prompt_formatting=True)
|
| 123 |
+
if i < llm_results_use:
|
| 124 |
+
prompt_context += f"{i+1}. {prompt_text}\n"
|
| 125 |
+
md_text_updated += md_text_paper
|
| 126 |
+
|
| 127 |
+
final_prompt = get_prompt_text(message, prompt_context)
|
| 128 |
+
return md_text_updated, final_prompt
|
| 129 |
+
|
| 130 |
+
def ask_gemma_llm(prompt, llm_model_picked, stream_outputs):
|
| 131 |
+
"""Sends a prompt to the Google Gemini API and streams the response."""
|
| 132 |
+
if not prompt or not prompt.strip():
|
| 133 |
+
yield "Error: The generated prompt is empty. Please try a different query."
|
| 134 |
+
return
|
| 135 |
+
|
| 136 |
+
if llm_model_picked == 'None':
|
| 137 |
+
yield "LLM Model is disabled."
|
| 138 |
+
return
|
| 139 |
+
|
| 140 |
+
if not gemini_api_key:
|
| 141 |
+
yield "Error: GEMINI_API_KEY is not configured. Cannot contact the LLM."
|
| 142 |
+
return
|
| 143 |
+
|
| 144 |
+
try:
|
| 145 |
+
safety_settings = [
|
| 146 |
+
{"category": "HARM_CATEGORY_HARASSMENT", "threshold": "BLOCK_ONLY_HIGH"},
|
| 147 |
+
{"category": "HARM_CATEGORY_HATE_SPEECH", "threshold": "BLOCK_ONLY_HIGH"},
|
| 148 |
+
{"category": "HARM_CATEGORY_SEXUALLY_EXPLICIT", "threshold": "BLOCK_ONLY_HIGH"},
|
| 149 |
+
{"category": "HARM_CATEGORY_DANGEROUS_CONTENT", "threshold": "BLOCK_ONLY_HIGH"},
|
| 150 |
+
]
|
| 151 |
+
|
| 152 |
+
gemini_model_name = llm_model_picked.split('/')[-1]
|
| 153 |
+
model = genai.GenerativeModel(gemini_model_name)
|
| 154 |
+
response = model.generate_content(
|
| 155 |
+
prompt,
|
| 156 |
+
generation_config=GEMINI_GENERATION_CONFIG,
|
| 157 |
+
stream=stream_outputs,
|
| 158 |
+
safety_settings=safety_settings
|
| 159 |
+
)
|
| 160 |
+
|
| 161 |
+
if stream_outputs:
|
| 162 |
+
output = ""
|
| 163 |
+
for chunk in response:
|
| 164 |
+
try:
|
| 165 |
+
text = chunk.parts[0].text
|
| 166 |
+
output += text
|
| 167 |
+
yield output
|
| 168 |
+
except (IndexError, AttributeError):
|
| 169 |
+
# Ignore empty chunks, which can occur at the end of a stream.
|
| 170 |
+
pass
|
| 171 |
+
if not output:
|
| 172 |
+
yield "Model returned an empty or blocked stream. This may be due to the safety settings or the nature of the prompt."
|
| 173 |
+
else:
|
| 174 |
+
# Handle non-streaming responses.
|
| 175 |
+
try:
|
| 176 |
+
yield response.parts[0].text
|
| 177 |
+
except (IndexError, AttributeError):
|
| 178 |
+
reason = "UNKNOWN"
|
| 179 |
+
if response.prompt_feedback.block_reason:
|
| 180 |
+
reason = response.prompt_feedback.block_reason.name
|
| 181 |
+
elif response.candidates and not response.candidates[0].content.parts:
|
| 182 |
+
reason = response.candidates[0].finish_reason.name
|
| 183 |
+
yield f"Model returned an empty or blocked response."
|
| 184 |
+
|
| 185 |
+
except Exception as e:
|
| 186 |
+
error_message = f"An error occurred with the Gemini API: {e}"
|
| 187 |
+
print(error_message) # Server side log
|
| 188 |
+
gr.Warning("An error occurred with the Gemini API. Check the server logs for details.")
|
| 189 |
+
yield error_message
|
| 190 |
+
|
| 191 |
+
# --- Gradio User Interface ---
|
| 192 |
+
with gr.Blocks(theme=gr.themes.Soft()) as demo:
|
| 193 |
+
gr.Markdown(APP_HEADER_TEXT)
|
| 194 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 195 |
with gr.Group():
|
| 196 |
+
msg = gr.Textbox(label='Search', placeholder='e.g., What is Mixtral?')
|
| 197 |
+
with gr.Accordion("Advanced Settings", open=False):
|
| 198 |
+
llm_model = gr.Dropdown(choices=LLM_MODELS_TO_CHOOSE, value=DEFAULT_LLM_MODEL, label='LLM Model')
|
| 199 |
+
llm_results = gr.Slider(5, 20, value=10, step=1, label="Top n results as context")
|
| 200 |
+
database_src = gr.Dropdown(choices=DATABASE_CHOICES, value=INDEX_INFO, label='Search Source')
|
| 201 |
+
stream_results = gr.Checkbox(value=True, label="Stream output")
|
| 202 |
+
|
| 203 |
+
output_text = gr.Textbox(label='LLM Answer', placeholder="The model's answer will appear here...", interactive=False, lines=8)
|
| 204 |
+
input_prompt = gr.Textbox(visible=False)
|
| 205 |
+
gr_md = gr.Markdown(MARKDOWN_SEARCH_RESULTS_HEADER)
|
| 206 |
+
|
| 207 |
+
msg.submit(
|
| 208 |
+
fn=update_with_rag_md,
|
| 209 |
+
inputs=[msg, llm_results, database_src],
|
| 210 |
+
outputs=[gr_md, input_prompt]
|
| 211 |
+
).then(
|
| 212 |
+
fn=ask_gemma_llm,
|
| 213 |
+
inputs=[input_prompt, llm_model, stream_results],
|
| 214 |
+
outputs=[output_text]
|
| 215 |
+
)
|
| 216 |
+
|
| 217 |
+
if __name__ == "__main__":
|
| 218 |
+
# Launch the app
|
| 219 |
+
demo.queue().launch()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
requirements.txt
CHANGED
|
@@ -1,4 +1,5 @@
|
|
| 1 |
-
ragatouille
|
|
|
|
| 2 |
huggingface_hub
|
| 3 |
arxiv
|
| 4 |
transformers[torch]<=4.49.0
|
|
|
|
| 1 |
+
ragatouille<0.0.10
|
| 2 |
+
google-generativeai
|
| 3 |
huggingface_hub
|
| 4 |
arxiv
|
| 5 |
transformers[torch]<=4.49.0
|