Gradio-NameError: name 'process_user_input' is not defined
%%blocks
import gradio as gr
from llama_cpp import Llama
from langchain_community.llms import LlamaCpp
from langchain.prompts import PromptTemplate
import llama_cpp
from langchain.callbacks.manager import CallbackManager
from sentence_transformers import SentenceTransformer
from langchain.callbacks.streaming_stdout import StreamingStdOutCallbackHandler
import numpy as np
import pandas as pd
import re
import os
from sklearn.metrics.pairwise import cosine_similarity

model = SentenceTransformer('sentence-transformers/paraphrase-multilingual-mpnet-base-v2',device='cpu')

llm = LlamaCpp(
    model_path=r"C:\Users\Cora\.cache\lm-studio\models\YC-Chen\Breeze-7B-Instruct-v1_0-GGUF\breeze-7b-instruct-v1_0-q4_k_m.gguf",
    n_gpu_layers=100,
    n_batch=512,
    n_ctx=3000,
    f16_kv=True,
    callback_manager=CallbackManager([StreamingStdOutCallbackHandler()]),
    verbose=False,
)
embedd_bk=pd.read_pickle(r"C:\Users\Cora\推薦系統實作\bk_description1_角色形容詞_677.pkl")
df_bk=pd.read_excel(r"C:\Users\Cora\推薦系統實作\bk_description1_角色形容詞.xlsx")

def invoke_with_temperature(prompt, temperature=0.4):
    return llm.invoke(prompt, temperature=temperature)

def process_user_input(message):
    
    user_mental_state4= PromptTemplate(
        input_variables=["input"],
        template="""[INST][/INST]"""
    )
    user_character= PromptTemplate(
        input_variables=["input"],
        template="""[INST][/INST]"""
    )
    
    df_user=pd.DataFrame(columns=["輸入內容","形容詞1", "形容詞2", "形容詞3", "角色1", "角色2", "角色3"])
   
    prompt_value1=user_mental_state4.invoke({"input":message})
    string=invoke_with_temperature(prompt_value1)
    #print("\n")

    # 將字符串分割為名詞
    adjectives = [adj.strip() for adj in re.split('[,、，]', string)]
    index=len(df_user)
    df_user.loc[index, '輸入內容'] = message

    # 確保形容詞數量符合欄位數量
    if len(adjectives) == 3:
        df_user.loc[index, '形容詞1'] = adjectives[0]
        df_user.loc[index, '形容詞2'] = adjectives[1]
        df_user.loc[index, '形容詞3'] = adjectives[2]
    df_user.to_excel("user_gradio系統.xlsx")
    return df_user
def embedd_df_user(df_user):
    columns_to_encode=df_user.loc[:,["形容詞1", "形容詞2", "形容詞3"]]

    # 初始化一個空的 DataFrame，用來存儲向量化結果
    embedd_user=df_user[["輸入內容"]]
    #user_em= user_em.assign(形容詞1=None, 形容詞2=None, 形容詞3=None,角色1=None,角色2=None,角色3=None)
    embedd_user= embedd_user.assign(形容詞1=None, 形容詞2=None, 形容詞3=None)
    

    # 遍歷每一個單元格，將結果存入新的 DataFrame 中
    i=len(df_user)-1
    for col in columns_to_encode:
        #print(i,col)
        # 將每個單元格的內容進行向量化
        embedd_user.at[i, col] = model.encode(df_user.at[i, col])           
    
    embedd_user.to_pickle(r"C:\Users\Cora\推薦系統實作\user_gradio系統.pkl")
    
    return embedd_user

def top_n_books_by_average(df, n=3):
    
    # 根据 `average` 列降序排序
    sorted_df = df.sort_values(by='average', ascending=False)
    
    # 选择前 N 行
    top_n_df = sorted_df.head(n)
    
    # 提取书名列
    top_books = top_n_df['書名'].tolist()
    
    return top_books,sorted_df

def similarity(embedd_user,embedd_bk,df_bk):
    df_similarity= pd.DataFrame(df_bk[['書名',"內容簡介","URL","形容詞1", "形容詞2", "形容詞3", '角色1', '角色2', '角色3']])
    df_similarity['average'] = np.nan
    #for p in range(len(embedd_user)): 
    index=len(embedd_user)-1               
    for k in range(len(embedd_bk)):
            list=[]
            for i in range(1,4):
                for j in range(3,6):
                    vec1=embedd_user.iloc[index,i]#i是第i個形容詞，數字是第幾個是使用者輸入
                    vec2=embedd_bk.iloc[k,j]
                    similarity = cosine_similarity([vec1], [vec2])
                    list.append(similarity[0][0])
            # 计算总和
            total_sum = sum(list)
            # 计算数量
            count = len(list)
            # 计算平均值
            average = total_sum / count
            df_similarity.loc[k,'average']=average

    top_books,sorted_df = top_n_books_by_average(df_similarity)
    return sorted_df     

def filter(sorted_df):
    filter_prompt4 = PromptTemplate(
        input_variables=["mental_issue", "user_identity"," book","book_reader", "book_description"],
        template="""[INST][/INST]"""
     )
    df_filter=sorted_df.iloc[:20,:]
    df_filter = df_filter.reset_index(drop=True)
    df_filter=df_filter.assign(推薦=None)  

    p=len(df_user)-1
    for k in range(len(df_filter)):    
        word=df_user["輸入內容"].iloc[p]
        #book_reader = df_filter["角色1"].iloc[p] + "or" + df_filter["角色2"].iloc[p] + "or" + df_filter["角色3"].iloc[p]
        book=df_filter["書名"].iloc[k] 
        book_reader = df_filter["角色1"].iloc[k] 
        user_identity = df_user["角色1"].iloc[p]
        mental_issue=df_user["形容詞1"].iloc[p]+"、"+df_user["形容詞2"].iloc[p]+"、"+df_user["形容詞3"].iloc[p]
        book_description=df_filter["形容詞1"].iloc[k]+"、"+df_filter["形容詞2"].iloc[k]+"、"+df_filter["形容詞3"].iloc[k]
        print(book_reader)
        print(user_identity)
        #output = filter_prompt1.invoke({"user_identity": user_identity, "book_reader": book_reader})
        output = filter_prompt4.invoke({"mental_issue":mental_issue,"user_identity": user_identity, "book":book,"book_description":book_description,"book_reader": book_reader})
        string2=invoke_with_temperature(output)
        df_filter.loc[k, '推薦'] =string2
        df_recommend=df_filter[df_filter["推薦"].str.strip() == "是"]
        
    return df_recommend
def output_content(df_recommend):
    content_prompt = PromptTemplate(
        input_variables=["content"],
        template="""[INST][/INST]"""
    )

    a=0
    title=df_recommend.loc[a,"書名"]
   prompt_value1=recommend_prompt.invoke({"title":title,"URL":URL,"summary":summary})
    
    recommend_prompt = PromptTemplate(
        input_variables=["title"],
        template=
     )
    prompt_value1=recommend_prompt.invoke({"title":title})
    output=invoke_with_temperature(prompt_value1,temperature=0.4)
    return output                   
               
def main_pipeline(message,history):         
    df_user=process_user_input(message)
    embedd_user=embedd_df_user(df_user)
    sorted_df=similarity(embedd_user,embedd_bk,df_bk)
    df_filter=filter(sorted_df)
    final=output_content(df_filter)
    return final  

demo=gr.ChatInterface(main_pipeline)

if __name__ == "__main__":
       demo.launch()This is my whole code. I’m trying to build a book recommendation app on Gradio.However, I keep meeting the problem ofNameError: name ‘process_user_input’ is not defined.But I have already define it before main_pipeline. I would be grateful if someone could help me figure it out. Thank you so much!
2024-11-19T13:39:02Z
You made typo around this area.def output_content(df_recommend):
    content_prompt = PromptTemplate(
        input_variables=["content"],
        template="""[INST][/INST]"""
    )

    a=0
    title=df_recommend.loc[a,"書名"]
   prompt_value1=recommend_prompt.invoke({"title":title,"URL":URL,"summary":summary}) # here!
    
    recommend_prompt = PromptTemplate(
        input_variables=["title"],
        template= # here!
     )
    prompt_value1=recommend_prompt.invoke({"title":title})
    output=invoke_with_temperature(prompt_value1,temperature=0.4)
    return output
2024-11-20T16:05:05Z
It’s not a typo, I just omit some of my prompt. But thank you for trying to help me.
2024-11-21T05:03:08Z
I see. So it’s the logic part…I’ll try running it later.
2024-11-21T11:36:35Z
I made the loading part a dummy, and it started up.huggingface.cotest code - a Hugging Face Space by John6666Discover amazing ML apps made by the community
2024-11-21T16:50:29Z
Thank you for helping me. I can show the interface too, but once typing words, it appears error. I am not sure why it can not load the function that I define before the main_pipeline()
2024-11-22T02:31:44Z
In this demo, the model and data are dummy figures, so it crashes there.It seems that the function call itself is being performed normally.It may depend on the version of Gradio. For now, I recommend 4.44.0 or below. If it becomes more stable, 5 should be fine.
2024-11-22T18:12:12Z
I changed the version to 4.44.0, but it seemed nothing had changed.I try to use a simple code to test where goes wrong.this case appears error too. It seems the problem is that it cannot get the process_input( )Can you help me try this?  Thank you so much!import gradio as grdef process_user_input(message):return messagedef main_pipeline(message, history):response = process_user_input(message)return responsechat_interface = gr.ChatInterface(main_pipeline,type=“messages”)ifname== “main”:chat_interface.launch()
2024-11-23T02:13:06Z
It started up when I did this.huggingface.cotest code - a Hugging Face Space by John6666Discover amazing ML apps made by the communityimport gradio as gr

def process_user_input(message):
    return message

def main_pipeline(message, history):
    response = process_user_input(message)
    return response

chat_interface = gr.ChatInterface(main_pipeline, type="messages")

if __name__ == "__main__":
    chat_interface.launch()BTW, ``` ``` is good but ```py ``` is more cool for Python code.
2024-11-23T03:49:36Z
After running your code on my laptop, I discover that the key problem is that everytime I start to run the code, I put “%%blocks” in the first line of the code. It was that caused the problem of calling function in “main_pipeline” cannot be read. Do you know why?
2024-11-23T04:24:16Z
Oh, I see. It was a problem that depended on the development environment!I’ve never used Jupyter, but it’s probably a problem specific to Jupyter.I don’t know how to solve it… I can’t find anything by searching.github.com/gradio-app/gradioEmit warning when using an interface in reload modegradio-app:main←gradio-app:3035-blocks-magic-with-interfacesopened10:03PM - 03 Feb 23 UTCfreddyaboulton+6-1# Description

Fixes #3035 by emitting a warning when a cell run with `%%block…s` has an Interface. 

Can't think of a way to fix the issue in a backwards compatible way. 

I tried skipping the duplicate id check for the magic command but then the demo rendering is messed up (as expected). See below with the code from the reproducer in the original issue:

![image](https://user-images.githubusercontent.com/41651716/216719071-01673134-22f7-469b-8a7f-ed4421fc60d0.png)

If you already have a full Interface or blocks app defined, the benefit of the %%blocks magic as opposed to re-running the cell is marginal in my opinion. 

What the warning looks like from jupyter

![image](https://user-images.githubusercontent.com/41651716/216719687-9e2792fe-63e0-4ca3-911d-cde666353caa.png)



# Checklist:

- [ ] I have performed a self-review of my own code
- [ ] I have added a short summary of my change to the CHANGELOG.md
- [ ] My code follows the style guidelines of this project
- [ ] I have commented my code in hard-to-understand areas
- [ ] I have made corresponding changes to the documentation
- [ ] I have added tests that prove my fix is effective or that my feature works
- [ ] New and existing unit tests pass locally with my changes


# A note about the CHANGELOG

Hello 👋 and thank you for contributing to Gradio!

All pull requests must update the change log located in CHANGELOG.md, unless the pull request is labeled with the "no-changelog-update" label.

Please add a brief summary of the change to the Upcoming Release > Full Changelog section of the CHANGELOG.md file and include
a link to the PR (formatted in markdown) and a link to your github profile (if you like). For example, "* Added a cool new feature by `[@myusername](link-to-your-github-profile)` in `[PR 11111](https://github.com/gradio-app/gradio/pull/11111)`".

If you would like to elaborate on your change further, feel free to include a longer explanation in the other sections.
If you would like an image/gif/video showcasing your feature, it may be best to edit the CHANGELOG file using the 
GitHub web UI since that lets you upload files directly via drag-and-drop.gradio.appDeveloping Faster With Reload ModeA Step-by-Step Gradio Tutorial
2024-11-23T08:21:08Z
Thank you! It works without the %%block.