R_errorchecker / app.py
keefereuther's picture
Cursor
Migrate R Debug Coach from Streamlit to Gradio with file uploads
5894803
Raw History Blame Contribute Delete
7.3 kB
import base64
import mimetypes
import os
import gradio as gr
import litellm
import pypdf
from dotenv import load_dotenv
import config
load_dotenv()
def _resolve_openai_base() -> str:
raw = (os.environ.get("OPENAI_API_BASE") or os.environ.get("OPENAI_BASE_URL") or "").strip()
if not raw:
return ""
base = raw.rstrip("/")
if not base.endswith("/v1"):
base += "/v1"
return base
OPENAI_BASE = _resolve_openai_base()
if OPENAI_BASE:
os.environ["OPENAI_API_BASE"] = OPENAI_BASE
MODEL_NAME = config.ai_model
try:
_supported = set(litellm.get_supported_openai_params(model=MODEL_NAME) or [])
except Exception:
_supported = {"max_tokens", "temperature", "frequency_penalty", "presence_penalty"}
_wanted = {
"temperature": config.temperature,
"max_tokens": config.max_tokens,
"frequency_penalty": config.frequency_penalty,
"presence_penalty": config.presence_penalty,
}
GEN_PARAMS = {k: v for k, v in _wanted.items() if v is not None and k in _supported}
_skipped = [k for k, v in _wanted.items() if v is not None and k not in _supported]
print(
f"[config] MODEL_NAME={MODEL_NAME} | OPENAI_API_BASE={OPENAI_BASE or '(unset)'} | "
f"OPENAI_API_KEY set={bool(os.environ.get('OPENAI_API_KEY'))} | "
f"gen_params={GEN_PARAMS} | skipped_unsupported={_skipped}"
)
if MODEL_NAME.startswith("openai/") and not OPENAI_BASE:
print(
"[config] WARNING: no OPENAI_API_BASE is set, but the model is "
f"'{MODEL_NAME}'. Requests will go to api.openai.com unless the endpoint is configured."
)
def _build_completion_kwargs() -> dict:
completion_kwargs = {}
if MODEL_NAME.startswith("openai/") and OPENAI_BASE:
completion_kwargs["api_base"] = OPENAI_BASE
completion_kwargs["api_key"] = os.environ.get("OPENAI_API_KEY")
completion_kwargs.update(GEN_PARAMS)
return completion_kwargs
def _opening_history():
return [{"role": "assistant", "content": config.opening_message}]
def encode_file_to_base64(file_path):
mime_type, _ = mimetypes.guess_type(file_path)
if not mime_type:
mime_type = "image/jpeg"
with open(file_path, "rb") as file:
encoded = base64.b64encode(file.read()).decode("utf-8")
return f"data:{mime_type};base64,{encoded}"
def _build_user_content(message):
current_content = []
user_text = message.get("text", "")
if user_text:
current_content.append({"type": "text", "text": user_text})
for file_path in message.get("files", []):
mime_type, _ = mimetypes.guess_type(file_path)
if mime_type and mime_type.startswith("image/"):
base64_url = encode_file_to_base64(file_path)
current_content.append(
{"type": "image_url", "image_url": {"url": base64_url}}
)
elif file_path.lower().endswith(".pdf"):
try:
reader = pypdf.PdfReader(file_path)
pdf_text = ""
for i, page in enumerate(reader.pages):
extracted = page.extract_text()
if extracted:
pdf_text += f"--- Page {i + 1} ---\n{extracted}\n\n"
doc_text = (
f"\n\n--- PDF Document: {os.path.basename(file_path)} ---\n"
f"{pdf_text}\n--- End PDF ---\n"
)
current_content.append({"type": "text", "text": doc_text})
except Exception as e:
current_content.append(
{
"type": "text",
"text": (
f"\n[System: Could not read PDF {os.path.basename(file_path)}. "
f"Error: {str(e)}]\n"
),
}
)
else:
try:
with open(file_path, "r", encoding="utf-8") as f:
file_text = f.read()
doc_text = (
f"\n\n--- Document: {os.path.basename(file_path)} ---\n"
f"{file_text}\n--- End Document ---\n"
)
current_content.append({"type": "text", "text": doc_text})
except Exception:
current_content.append(
{
"type": "text",
"text": (
f"\n[System: Could not read file: {os.path.basename(file_path)}]\n"
),
}
)
return current_content
def predict(message, history):
messages = [{"role": "system", "content": config.prompt}]
for msg in history:
if isinstance(msg.get("content"), str):
messages.append({"role": msg["role"], "content": msg["content"]})
messages.append({"role": "user", "content": _build_user_content(message)})
partial_message = ""
completion_kwargs = _build_completion_kwargs()
try:
response = litellm.completion(
model=MODEL_NAME,
messages=messages,
stream=True,
**completion_kwargs,
)
for chunk in response:
if not chunk.choices:
continue
delta = chunk.choices[0].delta.content
if delta:
partial_message += delta
yield partial_message
except Exception as e:
yield (
f"**An error occurred:** {e}\n\n"
"*Check your API keys, OPENAI_API_BASE, and model name in config.py.*"
)
def verify_login(username, password):
users_env = os.environ.get("ALLOWED_USERS", "")
if not users_env:
return False
try:
valid_users = dict(pair.split(":", 1) for pair in users_env.split(","))
except ValueError:
return False
return valid_users.get(username) == password
with gr.Blocks(fill_height=True) as demo:
with gr.Sidebar(open=False):
gr.Markdown(config.warning_message)
gr.Markdown("---")
gr.Markdown(
"<small>Licensed under "
'<a href="https://www.gnu.org/licenses/gpl-3.0.en.html">GNU GPL v3.0</a></small>'
)
chatbot = gr.Chatbot(
value=_opening_history(),
height="100%",
)
chatbot.clear(fn=lambda: _opening_history(), outputs=chatbot)
gr.ChatInterface(
fn=predict,
multimodal=True,
chatbot=chatbot,
textbox=gr.MultimodalTextbox(
placeholder="Type your message here, or upload an .R/.Rmd/.qmd file...",
file_types=["image", ".txt", ".csv", ".py", ".md", ".json", ".pdf", ".R", ".Rmd", ".qmd"],
scale=7,
),
fill_height=True,
)
if __name__ == "__main__":
_i18n = gr.I18n(
en={
"login": {
"login": "Log in",
"username": "Username",
"password": "Password",
"incorrect_credentials": "Incorrect username or password.",
"enable_cookies": (
"If you are visiting a HuggingFace Space in Incognito mode, "
"you must enable third party cookies."
),
},
},
)
demo.launch(auth=verify_login, i18n=_i18n)